branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>// // CZPeperNote.swift // CZPeper // // Created by Cui on 16/4/11. // Copyright © 2016年 Cui. All rights reserved. // import Foundation import UIKit class CZPaperNoteView: UIView { }<file_sep>// // CZPeperPageControl.swift // CZPeper // // Created by Cui on 16/4/11. // Copyright © 2016年 Cui. All rights reserved. // import Foundation import UIKit class CZPaperPageControl: UIView { var titles : [String?]? }<file_sep>// // CZPeperWall.swift // CZPeper // // Created by Cui on 16/4/11. // Copyright © 2016年 Cui. All rights reserved. // import Foundation import UIKit class CZPaperWallScroll: UIScrollView { var categorys : [CZPaperCategory]? }<file_sep>// // CZPaper.swift // CZPeper // // Created by Cui on 16/4/11. // Copyright © 2016年 Cui. All rights reserved. // import Foundation import UIKit var screenWidth : CGFloat { return UIScreen.mainScreen().bounds.width } var screenHeight : CGFloat { return UIScreen.mainScreen().bounds.height } var testCategory : [CZPaperCategory] { let c1 = CZPaperCategory(img: UIImage(named: "1"), tit: "标题1") let c2 = CZPaperCategory(img: UIImage(named: "2"), tit: "ceshi2") let c3 = CZPaperCategory(img: UIImage(named: "3"), tit: "这是啥?") return [c1, c2, c3] } class CZPaperViewController: UIViewController { private var paperWall : CZPaperWallScroll? private var paperPageControl : CZPaperPageControl? var wall : CZPaperWallScroll { get { if let w = paperWall { return w }else{ let w = CZPaperWallScroll() w.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenWidth) w.categorys = testCategory paperWall = w return w } } } var pageC : CZPaperPageControl { if let p = paperPageControl { return p }else{ let p = CZPaperPageControl() p.frame = CGRect(x: 0, y: 15, width: screenWidth, height: 80) p.titles = testCategory.map{ $0.title } paperPageControl = p return p } } override func viewDidLoad() { super.viewDidLoad() } }<file_sep>// // CZPaperCategory.swift // CZPeper // // Created by Cui on 16/4/11. // Copyright © 2016年 Cui. All rights reserved. // import Foundation import UIKit class CZPaperCategory { var image : UIImage? var title : String? init(img : UIImage?, tit : String?) { image = img title = tit } } //extension Array where Element : CZPaperCategory { // func titles() -> [String?]? { // return self.map { $0.title } // } //}
67a23d9bee5a2356e1144b6540dc04f9773e4015
[ "Swift" ]
5
Swift
xiaocuihero/CZPeper
dca36641dd80016013381af854ac953dd7594311
68100f78d563cf4de9e6ee92b0f6b8f82cf700d3
refs/heads/master
<file_sep>from lxml.html.builder import E from lxml.html import tostring, fromstring from brutemark.markdown import markdown def test_inline_HTML(): test = \ """<table> <tr> <td>Foo</td> </tr> </table>""" root = E("div", **{"class":"markdown_root"}) expected = \ """<div class="brutemark_root"><table> <tr> <td>Foo</td> </tr> </table></div>""" actual = markdown(test, pretty_print=False) assert actual == expected<file_sep>import re from . import regexs class Token(object): __slots__ = ("content", "start", "stop", "attrs") REGEX = None CONTENT_RULES = [] def __init__(self, content, start, stop, **attrs): self.content = content self.start = start self.stop = stop self.attrs = attrs def __repr__(self): # pragma: no cover return f"<{self.__class__.__name__} content={self.content!r}>" def contains_token(self, other_token): return other_token.stop <= self.stop and other_token.start >= self.start def render(self): product = [] if isinstance(self.content, str): product.append(self.content) else: for element in self.content: if hasattr(element, "render"): product.append(element.render()) else: product.append(element) return " ".join(product) @classmethod def Consume(cls, raw): """ Consume is complicated versus Line tokens because it expects to start with str and convert that to pre:str, token, post:str on success OR pre:str, None, None on a miss """ assert cls.REGEX is not None, f"{cls!r} expected to have REGEX attribute not None for {raw!r}" # assert len(cls.CONTENT_RULES) != 0, f"{cls!r} must have CONTENT_RULES set" product = None post = None regexs = [cls.REGEX]if isinstance(cls.REGEX, list) is False else cls.REGEX for regex in regexs: match = regex.search(raw) if match is not None: match_start = match.start() match_end = match.end() product = cls(match.group("content"), match_start, match_end) return raw, product else: return raw, None class RawText(Token): @classmethod def Consume(cls, raw): return cls(raw) class Text(Token): REGEX = re.compile(r"(.+)") @classmethod def Render(cls, token): return token.content class EmphasisText(Token): REGEX = [regexs.EMPHASIS_underscore, regexs.EMPHASIS_star] class StrongText(Token): REGEX = [regexs.STRONG_star, regexs.STRONG_underscore] class Anchor(Token): REGEX = [regexs.ANCHOR_title, regexs.ANCHOR_simple] @classmethod def Consume(cls, raw): """ Consume is complicated versus Line tokens because it expects to start with str and convert that to pre:str, token, post:str on success OR pre:str, None, None on a miss """ assert cls.REGEX is not None, f"{cls!r} expected to have REGEX attribute not None for {raw!r}" # assert len(cls.CONTENT_RULES) != 0, f"{cls!r} must have CONTENT_RULES set" product = None post = None regexs = [cls.REGEX]if isinstance(cls.REGEX, list) is False else cls.REGEX for regex in regexs: match = regex.search(raw) if match is not None: match_start = match.start(0) match_end = match.end(0)+1 groups = match.groupdict() if "content" in groups: del groups['content'] product = cls(match.group(1), match_start, match_end, **groups) return raw, product else: return raw, None class Image(Token): REGEX = [regexs.IMAGE_title, regexs.IMAGE_simple] <file_sep>[pytest] addopts=--cov=brutemark --cov-config=.coveragec --cov-report term --cov-report html <file_sep>import re """ # Line based token containers As denoted by `^` in the regex """ BLANK = re.compile(r"^$") #TODO this will fail to match correctly if a line is `<div><p>foo bar</p></div>` HTML_LINE = re.compile( r""" \s{0,3} (?P<content>\<[^\>]+\>) #Match <ANYTHING> that is wrapped with greater/less than symbols """, re.VERBOSE) CODE_LINE = re.compile(r"(^\ {4})|(^\t)") START_WS = re.compile(r"^(\s+)") QUOTED = re.compile(r"^(\>) (?P<content>.*)") ORDERED_ITEM = re.compile(r"^\d+\. (?P<content>.*)") # (Numeric)(period) UNORDERED_ITEM = re.compile(r"^\* (?P<content>.*)") LINE_HEADER = re.compile(r"""^(?P<depth>\#+)\ (?P<content>.*)""") """ Body tokens """ ANCHOR_simple = re.compile(r"""\[ (?P<content>[^\]]+) \] \( (?P<href>[^\)]+) \)""", re.VERBOSE) ANCHOR_title = re.compile(r"""\[ (?P<content>[^\]]+) \] \( (?P<href>[^\)]+) \"(?P<title>[^\"]+)\" \)""", re.VERBOSE) IMAGE_simple = re.compile(r"""\!\[(?P<content>[^\]]+)\]\((?P<href>[^\)]+)\)""") IMAGE_title = re.compile(r"""\!\[(?P<content>[^\]]+)\]\((?P<href>[^\)]+) \"(?P<title>[^\"]+)\"\)""") STRONG_underscore = re.compile(r"""(\_{2}(?P<content>[^_]+)\_{2})""") STRONG_star = re.compile( r"""( (?<!\\) \*{2} (?P<content>[^_]+) (?<!\\) \*{2} )""", re.VERBOSE) EMPHASIS_underscore = re.compile( r"""( (?<!\_) #if there is double __ at the start, ignore \_ (?P<content>[^\_]+) \_ (?!\_) #if there is double __ at the end, ignore )""", re.VERBOSE) EMPHASIS_star = re.compile( r""" (?<!\\) (?<!\*) \* (?P<content>[^\*]+) (?<!\\) \* (?!\*) """, re.VERBOSE) <file_sep> from brutemark.parser import TokenizeLine from brutemark.line_tokens import QuotedLine blockquote = """> Single line blockquote""" nested_blockquote = """ > Single line blockquote that is nested""" def test_blockquote_consumes_string_correctly(): _, actual = QuotedLine.TestAndConsume(blockquote) assert actual is not None assert isinstance(actual, QuotedLine) assert actual.content == "Single line blockquote" _, actual = QuotedLine.TestAndConsume(nested_blockquote) assert isinstance(actual, QuotedLine) assert actual.nested == True assert actual.content == "Single line blockquote that is nested" def test_detects_blockquote(): tokenized_line = TokenizeLine(blockquote, None, []) assert isinstance(tokenized_line, QuotedLine) assert tokenized_line.nested is False def test_blockquote_detected_and_is_nested(): tokenized_line = TokenizeLine(nested_blockquote, None, []) assert tokenized_line.nested is True <file_sep>from lxml.html.builder import E from lxml.html import tostring import textwrap from brutemark.markdown import markdown, ROOT_CONTAINER from brutemark import line_tokens def test_simple_generation_single_header(): test = \ textwrap.dedent(""" # Hello World """).strip() expected = tostring( E("div", E("h1", "Hello World"), **{"class":"brutemark_root"} ), pretty_print=True, encoding="unicode" ) actual = markdown(test) assert actual == expected def test_simple__multiline_paragraph(): test = \ """ This is a test of the assembler. This line should be followed by a br tag """ test = textwrap.dedent(test).strip() expected_text =\ [ "This is a test of the assembler. ", "This line should be followed by a ", E("br"), "br tag" ] root_kwargs = {"class":"brutemark_root"} root = E("div", E("p", *expected_text), **root_kwargs) expected = tostring(root,pretty_print=True, encoding="unicode") actual_string = markdown(test) assert expected == actual_string def test_simple_multiline_code(): test = [ " This is a code block", " that spans", " multiple lines" ] test = "\n".join(test) expected_text = \ [ "This is a code block\n", "that spans\n", "multiple lines" ] root_kwargs = {"class": "brutemark_root"} expected = tostring( E("div", E("pre", E("code", *expected_text) ), ** root_kwargs ), pretty_print=True, encoding="unicode" ) actual = markdown(test) assert actual == expected def test_simple_multiple_ordered_list(): test = "\n".join([ "1. First item", "2. Second item" ]) root_kwargs = {"class": "brutemark_root"} expected = tostring( E("div", E("ol", E("li", "First item"), E("li", "Second item") ), ** root_kwargs ), pretty_print = True, encoding = "unicode" ) actual = markdown(test) assert actual == expected def test_mixed_lists(): test = "\n".join([ "1. item 1", " * subitem A", "2. item 2" ]) expected = tostring( E("div", E("ol", E("li","item 1", E("ul", E("li", "subitem A")) ), E("li", "item 2") ), **{"class":"brutemark_root"} ), pretty_print=True, encoding="unicode" ) actual = markdown(test) assert actual == expected def test_multidepth_lists(): test = "\n".join([ "1. item 1", " * subitem A", " * subitem B", " 12. super nested item" "2. item 2" ]) expected = tostring( E("div", E("ol", E("li","item 1", E("ul", E("li", "subitem A"), E("li", "subitem B", E("ol", E("li", "super nested item") ) ) ) ), E("li", "item 2") ), **{"class":"brutemark_root"} ), pretty_print = False, encoding='unicode' ).replace("\n", "") actual = markdown(test, pretty_print=False) assert actual == expected<file_sep>from brutemark.parser import Blocker, TokenizeBody, TokenizeLine from brutemark.line_tokens import HTMLLine, CodeLine test_document = """<table> <tr> <td>Hello</td> <td>World</td> </tr> </table>""" def test_htmlline_correctly_consumes_the_correct_line_and_ignores_tabbed_or_spaced_lines(): """ raw html lines cannot be tabbed/spaced to avoid mixing them up with CodeLine's """ _, actual = HTMLLine.TestAndConsume("<span>") assert actual is not None assert isinstance(actual, HTMLLine) _, actual = HTMLLine.TestAndConsume(" <dd>") assert actual is not None assert isinstance(actual, HTMLLine) _, actual = HTMLLine.TestAndConsume(" <dt bar=\"123\">") assert actual is not None assert isinstance(actual, HTMLLine) _, actual = HTMLLine.TestAndConsume("<dt bar=\"123\">") def test_tokenize_line_recognizes_html(): blocks = Blocker(test_document) for block in blocks: for line in block: product = TokenizeLine(line) assert isinstance(product, (HTMLLine, CodeLine,))<file_sep>from brutemark.parser import TokenizeLine from brutemark.line_tokens import CodeLine, BlankLine tabbed_code ="\tA=123" spaced_code = " A=123" nested_tabbed_code = "\t A=123" nested_spaced_code = " A=123" def test_detected_tabbed_codeline(): tokenized_line = TokenizeLine(tabbed_code, BlankLine, []) assert isinstance(tokenized_line, CodeLine) def test_detected_spaced_codeline(): tokenized_line = TokenizeLine(spaced_code, BlankLine, []) assert isinstance(tokenized_line, CodeLine) def test_nested_tabbed_code(): tokenized_line = TokenizeLine(nested_tabbed_code, BlankLine, []) assert isinstance(tokenized_line, CodeLine) assert tokenized_line.nested == 2 def test_nested_spaced_code(): tokenized_line = TokenizeLine(nested_spaced_code, BlankLine, []) assert isinstance(tokenized_line, CodeLine) assert tokenized_line.nested == 2<file_sep> from lxml.html import tostring from brutemark.parser import TokenizeLine, TokenizeBody from brutemark.line_tokens import HeaderLine, Line tests = [ "# h1", "## h2", "### h3", "#### h4", "##### h5", "###### h6" ] nested_tests = [ " # h1", " ## h2", " ### h3", " #### h4", " ##### h5", " ###### h6" ] def test_all_headers(): for position, test_str in enumerate(tests): token = TokenizeLine(test_str, None, ) assert isinstance(token, HeaderLine) assert token.level == position + 1, f"Expected {position+1} for level but got {token.level} with {test_str!r}" assert token.nested == False def test_all_nested_headers(): for position, test_str in enumerate(nested_tests): token = TokenizeLine(test_str) assert isinstance(token, HeaderLine) assert token.level == position + 1, f"Expected {position+1} for level but got {token.level} with {test_str!r}" assert token.nested == 2 def test_header_content_is_correct(): for position, test_str in enumerate(tests): token = TokenizeLine(test_str) assert token.content == f"h{token.level}" def test_headerline_consumes_text_correctly(): _, actual = HeaderLine.TestAndConsume("## h2") assert actual.content == "h2" def test_headers_render_correctly(): for i in range(1,4): test = "#" * i test += f" h{i}" expected = f"<h{i}>h{i}</h{i}>" _, token = HeaderLine.TestAndConsume(test) token.content = TokenizeBody(token.content) actual = HeaderLine.Render([token]) actual_text = tostring(actual).decode() assert actual_text == expected, f"Got {actual_text!r} for level {token.level}" <file_sep>from brutemark.parser import Blocker test = \ """This is paragraph one it is all on one line and then given two empty lines this is paragraph two it is broken into individual blocks with no spaces between them This is paragraph three , it is kind of nonsensical because the whole thing is one word followed by a space and then a carriage return. """ def test_total_block_count_is_three(): blocks = Blocker(test) assert len(blocks) == 3 def test_block_sizes_are_correct(): blocks = Blocker(test) assert len(blocks[0]) == 1 assert len(blocks[1]) == 3 assert len(blocks[2]) == 27<file_sep>from brutemark.parser import TokenizeLine from brutemark.line_tokens import OrderedItemLine, UnorderedItemLine ordered_line = "123. Hello World" nested_ordered_line = " 123. Hello World" unordered_line = "* Hello World" nested_unordered_line = " * Hello World" def test_ordered_line_items(): tokenized_line = TokenizeLine(ordered_line) assert isinstance(tokenized_line, OrderedItemLine) assert tokenized_line.nested == 0 tokenized_line = TokenizeLine(nested_ordered_line) assert isinstance(tokenized_line, OrderedItemLine) assert tokenized_line.nested == 2 def test_unordered_line_items(): tokenized_line = TokenizeLine(unordered_line) assert isinstance(tokenized_line, UnorderedItemLine) assert tokenized_line.nested == 0 tokenized_line = TokenizeLine(nested_unordered_line) assert isinstance(tokenized_line, UnorderedItemLine) assert tokenized_line.nested == 2<file_sep>from brutemark.parser import TokenizeBody from brutemark.body_tokens import Text, StrongText, EmphasisText def test_emphasis_star_is_negated_by_slash(): leading_test = r"Hello \*world*" expected = Text(leading_test, 0, len(leading_test)) actual = TokenizeBody(leading_test) assert len(actual) == 1 assert isinstance(actual[0], Text) assert actual[0].content == leading_test trailing_test = r"Hello *World\*" expected = Text(trailing_test, 0, len(trailing_test)) actual = TokenizeBody(trailing_test) assert len(actual) == 1 assert isinstance(actual[0], Text) assert actual[0].content == trailing_test _, leading_token = EmphasisText.Consume(leading_test) assert leading_token is None _, trailing_test = EmphasisText.Consume(trailing_test) assert trailing_test is None def test_emphasis_consume_matches(): test = "Hello _World_" expected = EmphasisText("World",6,13) actual_text, actual_token = EmphasisText.Consume(test) # type: EmphasisText assert actual_token is not None assert actual_token.start == expected.start assert actual_token.content == expected.content assert actual_token.stop == expected.stop def test_strong_consumes_match(): test = "Hello __World__" expected = StrongText("World",6,15) actual_text, actual_token = StrongText.Consume(test) assert actual_token is not None assert actual_token.start == expected.start assert actual_token.stop == expected.stop assert actual_token.content == expected.content def test_detects_strong_markdown(): test = "Hello __world__" expected = [Text("Hello ",0,6), StrongText("world",7,13)] actual = TokenizeBody(test) assert isinstance(actual[0], Text) assert isinstance(actual[1], StrongText) def test_detects_emphasis_markdown(): test = "Hello _World_" expected = [Text("Hello ",0,6), EmphasisText("World",7,13)] actual = TokenizeBody(test) assert isinstance(actual[0], Text) assert isinstance(actual[1], EmphasisText) def test_emphasis_consumes_nested_strongtext(): test = "_Hello **World**_" expected_content = "Hello **World**" expected = EmphasisText("Hello **World**", 0, 17) actual_text, actual_token = EmphasisText.Consume(test) assert actual_token is not None assert actual_token.content == expected_content assert actual_token.start == expected.start assert actual_token.stop == expected.stop def test_strong_nested_in_emphasis(): test = "_Hello **World**_" expected = [ EmphasisText( [ Text("Hello ",0,6), StrongText("World", 0 , 7) ], 0,17 ) ] actual = TokenizeBody(test) assert len(actual) == 1 assert isinstance(actual[0], EmphasisText) assert actual[0].content[0].content == expected[0].content[0].content<file_sep>from brutemark.parser import TokenizeLine from brutemark.line_tokens import OrderedItemLine, UnorderedItemLine def test__line_tokens__OrdereredItemLine__testconsume_detects_ordered_items_correctly(): normal_test = "123. Hello World" expected = OrderedItemLine("Hello World", False) _, actual = OrderedItemLine.TestAndConsume(normal_test) assert actual is not None assert actual.content == expected.content assert actual.nested == 0 nested_test = " 123. Hello World" expected = UnorderedItemLine("Hello World", True) actual = TokenizeLine(nested_test) assert isinstance(actual, OrderedItemLine) assert actual.content == expected.content assert actual.nested == 2 def test__line_tokens__UnorderedItemLine__testconsume_detects_unordered_items_correctly(): normal_test = "* Hello World" expected = UnorderedItemLine("Hello World", False) _, actual = UnorderedItemLine.TestAndConsume(normal_test) assert actual is not None assert actual.content == expected.content assert actual.nested == 0 nested_test = " * Hello World" expected = UnorderedItemLine("Hello World", True) actual = TokenizeLine(nested_test) assert actual is not None assert isinstance(actual, UnorderedItemLine) assert actual.content == expected.content assert actual.nested == 3 <file_sep>from brutemark.line_tokens import Line from brutemark.parser import Blocker, TokenizeLine test = """# Hello World This is a code line This is a nested code line #2 > This is a block quote ## Second hello world in h2 * Unordered item 1 This is a nested code line * Unordered item 2 321. Ordered item 1 * Unordered item 3 1. Ordered Item 2 """ def test_assure_blocker_works(): blocks = Blocker(test) assert len(blocks) == 1 lines = blocks[0] assert len(lines) == 12 def test_feeding_lines_to_tokenizeline_does_not_break(): tokenized_blocks = [] for raw_blocks in Blocker(test): tokenized_line = [] for raw_line in raw_blocks: token = TokenizeLine(raw_line, None, [Line]) assert isinstance(token, Line) tokenized_line.append(token) tokenized_blocks.append(tokenized_line) assert len(tokenized_blocks) == 1 assert len(tokenized_blocks[0]) == 12 <file_sep>import textwrap from lxml.html.builder import E from lxml.html import fromstring from . import regexs from . import body_tokens def test_nested(raw): match = regexs.START_WS.match(raw) depth = 0 if match is not None: lead = raw[:match.end()] raw = raw[match.end():] depth = lead.count(" ") depth += lead.count("\t") return raw, depth class Line(object): REGEX = None PROCESS_BODY = False CAN_NEST = False ALLOWED_NESTED = [] CAN_CONTAIN = [body_tokens.Text] PROCESSORS = [] def __init__(self, content, nested=False): self.content = content self.nested = nested @classmethod def Contains(cls, new_line): return type(new_line) == cls @classmethod def Render(cls, elements): lines = [] for element in elements: lines.append(element.render()) body = "\n".join(lines) element = E(cls.__name__) element.text = body return element def render(self): line = [] for element in self.content: if hasattr(element, "render"): line.append(element.render()) else: line.append(element) return " ".join(line) @classmethod def TestAndConsume(cls, raw): assert cls.REGEX is not None, f"While processing {raw!r}\nExpected {cls} to have a REGEX assigned" product = None raw, is_nested = test_nested(raw) match = cls.REGEX.match(raw) if match is not None: product = cls(match.group("content"), is_nested) return raw, product class BlankLine(Line): @classmethod def Render(cls, elements): #No matter how many blanklines, just do one <br/> return E("br") class TextLine(Line): PROCESS_BODY = True @classmethod def Contains(cls, new_token): return type(new_token) == cls def can_nest(self, new_line): """ Paragraph/text lines can be merged together """ return type(new_line) == TextLine @classmethod def TestAndConsume(cls, raw): raw, is_nested = test_nested(raw) return cls(raw, is_nested) @classmethod def Render(cls, children): lines = [] for child_token in children: child_token.render(lines) paragraph = E("p", *lines) return paragraph def render(self, container:list): for body_token in self.content: container.append(body_token.render()) if hasattr(container[-1], "endswith"): if container[-1].endswith(" "): container.append(E("br")) return container class QuotedLine(Line): REGEX = regexs.QUOTED PROCESS_BODY = True CAN_NEST = False class HTMLLine(Line): REGEX = regexs.HTML_LINE CAN_NEST = False # PROCESS_BODY is defaulted to False @classmethod def TestAndConsume(cls, raw): product = None match = cls.REGEX.match(raw) is_nested = False if match is not None: product = cls(raw, is_nested) return raw, product @classmethod def Render(cls, elements): content = [x.content for x in elements] content = "\n".join(content) return fromstring(content) class CodeLine(Line): REGEX = regexs.CODE_LINE CAN_CONTAIN = [None, body_tokens.RawText, body_tokens.Text] # PROCESS_BODY is defaulted to False @classmethod def TestAndConsume(cls, raw): assert cls.REGEX is not None, f"Expected {cls} to have a REGEX assigned" product = None match = cls.REGEX.match(raw) if match is not None: raw, is_nested = test_nested(raw[match.end():]) product = cls(raw, is_nested) return raw, product @classmethod def Render(cls, elements): lines = [] for element in elements: # Codeline does not have preprocessed bodies lines.append(element.content) body = "\n".join(lines) return E("pre", E("code", body)) class OrderedItemLine(Line): REGEX = regexs.ORDERED_ITEM PROCESS_BODY = True CAN_NEST = True @classmethod def Render(cls, elements): lines = [] for token in elements: if type(token) != cls: lines.append(token.Render([token.content] + [token.children])) elif hasattr(token, "render"): lines.append(token.render()) else: lines.append(E("li", token.content)) return E("ol", *lines) def render(self): from collections import defaultdict pieces = [] grouped = defaultdict(list) for element in self.content: grouped[type(element)].append(element) for content_type, elements in grouped.items(): if content_type not in [body_tokens.Text, body_tokens.EmphasisText, body_tokens.StrongText]: pieces.append(content_type.Render(elements)) else: for element in elements: pieces.append(element.render()) return E("li", *pieces) @classmethod def Contains(cls, new_line:Line) -> bool: if cls == type(new_line): return True elif new_line.nested is True: return True return False class UnorderedItemLine(Line): REGEX = regexs.UNORDERED_ITEM PROCESS_BODY = True CAN_NEST = True @classmethod def Render(cls, elements): lines = [] for token in elements: if hasattr(token, "render"): lines.append(token.render()) else: lines.append(E("li", token.content)) return E("ul", *lines) def render(self): pieces = [] for element in self.content: if hasattr(element, "render"): pieces.append(element.render()) else: pieces.append(element) return E("li", *pieces) class HeaderLine(Line): REGEX = regexs.LINE_HEADER PROCESS_BODY = True CAN_NEST = False def __init__(self, raw, is_nested=False, level=1): self.level= level super().__init__(raw, is_nested) @classmethod def TestAndConsume(cls, raw): product = None raw, is_nested = test_nested(raw) match = cls.REGEX.match(raw) if match is not None: level = match.string.strip().count("#") product = cls(match.group("content"), is_nested, level) return raw, product @classmethod def Render(cls, elements=None): assert len(elements) == 1 sub_elements = [x.render() for x in elements[0].content] header = E(f"h{elements[0].level}", *sub_elements) return header def render(self): raise NotImplementedError("HeaderLine is rendered through classmethod Render") """ HACK """ Line.PROCESSORS = [HTMLLine, CodeLine, QuotedLine, UnorderedItemLine, OrderedItemLine, HeaderLine] HTMLLine.PROCESSORS = [HTMLLine] CodeLine.PROCESSORS = [CodeLine] QuotedLine.PROCESSORS = [QuotedLine, TextLine] UnorderedItemLine.PROCESSORS = Line.PROCESSORS OrderedItemLine.PROCESSORS = Line.PROCESSORS HeaderLine.PROCESSORS = [BlankLine] BlankLine.PROCESSORS= Line.PROCESSORS <file_sep>r""" """ import re from enum import Enum, auto from collections import namedtuple from . import regexs from . import line_tokens from . import body_tokens # from .line_tokens import CodeLine, UnorderedItemLine, OrderedItemLine, QuotedLine, HeaderLine, BlankLine, TextLine # from .body_tokens import Token, RawText, Text, EmphasisText, StrongText, Anchor, Image def Blocker(raw_text): blocks = [] raw_lines = raw_text.split("\n") buffer = [] spaces = 0 while len(raw_lines): line = raw_lines.pop(0) buffer.append(line) if line == "": spaces += 1 else: spaces = 0 if spaces >= 2: if buffer: if buffer[-2] == "" and buffer[-1] == "": blocks.append(buffer[:-2]) else: blocks.append(buffer) buffer = [] spaces = 0 if buffer: blocks.append(buffer) return blocks """ Line based tokens ================= """ class BodyTokenizer(): """ given a string like hello __world__ this *is* a **test** of [Markdown](https://daringfireball.net/projects/markdown/ "Markdown homepage") creates [ Text("Hello "), Emphasis(Text("world")), Text(" this "), Emphasis(Text("is")), Text(" a "), Strong(Text("test"), Text(" of "), Anchor(body=Text("Markdown",href="https://daringfireball.net/projects/markdown/", title="Markdown homepage") ] :param raw:str :return: """ def __init__(self): self.processors = [ body_tokens.EmphasisText, body_tokens.StrongText, body_tokens.Anchor, body_tokens.Image ] self.default_processor = [body_tokens.Text] def process(self, raw:str)->[]: product = [] for processor in self.processors: _, token = processor.Consume(raw) if token is not None: pre = post = None if token.start != 0: product.extend(TokenizeBody(raw[:token.start])) token.content = TokenizeBody(token.content) product.append(token) if token.stop != len(raw): product.extend(TokenizeBody(raw[token.stop:])) break else: product.append(body_tokens.Text(raw, 0, len(raw))) return product body_tokenizer = BodyTokenizer() TokenizeBody = body_tokenizer.process class LineTokenizer(object): def __init__(self): self.processors = [ line_tokens.HTMLLine, line_tokens.CodeLine, line_tokens.QuotedLine, line_tokens.UnorderedItemLine, line_tokens.OrderedItemLine, line_tokens.HeaderLine ] def process(self, raw:str, last_token:line_tokens.Line = None, stack=None)->line_tokens.Line: is_nested = False stack = [] if stack is None else stack current_processors = last_token.PROCESSORS if last_token is not None else self.processors if raw.strip() == "": return line_tokens.BlankLine(raw, False) for processor in current_processors: _, product = processor.TestAndConsume(raw) if product is not None: return product break else: return line_tokens.TextLine.TestAndConsume(raw) line_tokenizer = LineTokenizer() TokenizeLine = line_tokenizer.process<file_sep>from lxml.html.builder import E from lxml.html import tostring from collections import defaultdict from .parser import TokenizeLine, TokenizeBody, Blocker class ROOT_CONTAINER: def __init__(self): self.content = None @classmethod def Contains(cls, child): return True @classmethod def Render(cls, elements): grouped = defaultdict(list) for element in elements: if hasattr(element, "render"): pass def render(self, content, children): leafs = [] for child in children: if hasattr(child, "render"): leafs.append(child.render) else: leafs.append(child) return E("div", **leafs) class Tree: def __init__(self, token=None, parent=None, nested=0): self.type = type(token) self.content = token self.nested = nested self.parent = parent self.children = [] @classmethod def MakeRoot(cls): return cls(ROOT_CONTAINER(),parent=None) def __repr__(self): return f"<{self.__class__.__name__} type={self.type!r}>" def add_child(self, child_token): branch = Tree(child_token, self, nested=child_token.nested) self.children.append(branch) return branch def add(self, line_token): if self.type == ROOT_CONTAINER: branch = self.add_child(line_token) elif self.type.Contains(line_token) is False: branch = self.parent.add(line_token) elif self.type.Contains(line_token) is True: if line_token.nested > self.nested: self.content.content.append(line_token) branch = Tree(line_token, self) elif line_token.nested < self.nested: branch = self.parent.add_child(line_token) else: self.add_child(line_token) branch = self else: branch = self.add_child(line_token) return branch def render(self, parent_element = None): if self.type == ROOT_CONTAINER: kwargs = {"class": "brutemark_root"} parent_element = E("div", **kwargs) for branch in self.children: branch.render(parent_element) else: branches = [self.content] branches.extend([x.content for x in self.children]) child_element = self.type.Render(branches) parent_element.append(child_element) return parent_element def markdown(raw_string, return_tree=False, pretty_print=True): tokenized_document = [] for block in Blocker(raw_string): tokenized_block = [] last_token = None for line in block: last_token = line_token = TokenizeLine(line, last_token=last_token, stack=tokenized_block) if line_token.PROCESS_BODY is True: line_token.content = TokenizeBody(line_token.content) tokenized_block.append(line_token) tokenized_document.append(tokenized_block) tokenized_block = [] #Consolidate lines in a block root = Tree.MakeRoot() current_branch = root for block in tokenized_document: for line in block: current_branch = current_branch.add(line) if return_tree is not False: return root elif pretty_print is not True: return tostring(root.render(), encoding="unicode") else: return tostring(root.render(), pretty_print=pretty_print, encoding="unicode")
32dac874fe24d0332341fabebb524167c9dda1f3
[ "Python", "INI" ]
17
Python
devdave/brutemark
2e85a5483c70809ee7cfd7818537c8b1d1b366cc
08c41ecc07a20884634f3a212eda106bc74799a3
refs/heads/master
<file_sep>/*(c) <NAME> 2009 - license: http://www.opensource.org/licenses/mit-license.php*/ function MBCalendar(m, y) { this.m = m; this.y = y; this.weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; } MBCalendar.prototype.$ = function(s) {return document.getElementById(s)}; // export as array MBCalendar.prototype.toArray = function() { var d; var dates = []; for (var i=1;i<32;i++) { d = new Date(this.y,this.m-1, i); if (d.getMonth() == this.m-1) dates.push(d); } return dates; }; // export as html MBCalendar.prototype.toHTML = function() { var i; var ret, dayId, dayClass; ret = dayId = dayClass = ''; var dates = this.toArray(); ret += '<table class="cal">' + '<tr>'; for (i in [0,1,2,3,4,5,6]) ret += '<th>' + this.weekDays[parseInt(dates[i].getDay())].substr(0,1) + '</th>'; ret += '</tr><tr>'; for (i in dates) { var d = dates[i]; if ((parseInt(i) % 7) == 0) ret += '</tr>'; if ((parseInt(i)+1 % 7==0) && i<dates .length) ret += '<tr>'; dayClass = 'y'+d.getFullYear() + ' m' +(d.getMonth()+1) + ' d' + d.getDate(); dayId = 'day-' + parseInt(d.getTime()/86400000); ret += '<td id="' + dayId + '" class="' + dayClass +'">' + dates[i].getDate() + '</td>'; } ret = ret + '</dates></table>'; return ret; }; window.onload = function() { var $ = function(s) {return document.getElementById(s)}; var c; $('showCal').onclick = function() { var y = $('year').value; var m = $('month').value; c = new MBCalendar(m, y); $('out').innerHTML = c.toHTML(); }; $('prev').onclick = function() { var d = new Date(c.y,c.m-2,1); c = new MBCalendar(d.getMonth()+1, d.getFullYear()); $('out').innerHTML = c.toHTML(); } $('next').onclick = function() { var d = new Date(c.y,c.m,1); c = new MBCalendar(d.getMonth()+1, d.getFullYear()); $('out').innerHTML = c.toHTML(); } };<file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order Report</h1> <p>Request Status</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? $businessCard = new BusinessCard(); $sql= "select * from Orders, Campus where empCampus=idCampus AND recdFmPrinter = '1'"; $stmt=$businessCard->rawSelect($sql); $row_count = $stmt->rowCount(); if($row_count < 1) { echo "<h3>There are no completed orders</h3>"; } else { ?> <h2 align='center'>Completed Orders</h2> <button onclick="window.location.href='print_form.php?type=completed'">Print</button><p> <div class="table-responsive"> <table class="table table-striped table-bordered"> <tr> <td><h4>Name</h4></td><td><h4>Date Requested</h4></td><td><h4>Date Completed</h4></td> </tr> <? foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { echo "<tr>"; echo "<td>"; ?> <a href="orderdetails.php?idOrders=<? echo $row['idOrders'] ?>" ><? echo $row['empName'] ?></a> <? echo "</td>"; echo "<td>"; echo $row['dateReceived']; echo "</td>"; echo "<td>"; echo $row['dateFmPrinter']; echo "</td>"; echo "</tr>"; } ?> </table> </div> <? } ?> <h3><a href="admin.php">Go to Admin Page</a></h3> <h3><a href="http://highlands.edu">Exit</a></h3> </div> </div> </body> </html><file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order</h1> <p>Send to Printer</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? if(@!$_POST['OrderID']) { echo "<h2>Please select at least one order</h2>"; echo "<h3><a onclick='window.history.back();'>Return to List</a></h3>"; exit(0); } $businessCard = new BusinessCard(); $sql = "SELECT * FROM Orders, Campus where empCampus=idCampus AND idOrders IN ("; $count=count ($_POST['OrderID']); $i = 1; $_SESSION['OrderID'] = $_POST['OrderID']; foreach($_SESSION['OrderID'] as $OrderID) { if($i < $count ) { $sql=$sql . "'" . $OrderID . "',"; $i++; } else { $sql=$sql . "'" . $OrderID . "')"; } } $_SESSION['sql'] = $sql; ?> <h2>The following requests will be forwarded to the printer</h2> <br> <br> <div class="table-responsive"> <table class="table table-bordered"> <tr> <td><h4>Name</h4></td><td><h4>Title</h4></td><td><h4>Campus</h4></td><td><h4>Contact Info</h4></td> </tr> <? foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { echo "<tr>"; echo "<td>"; echo $row['empName']; echo "</td>"; echo "<td>"; echo $row['empTitle1'] . "<br>"; echo $row['empTitle2']; echo "</td>"; echo "<td>"; echo $row['nameCampus']; echo "</td>"; echo "<td>"; echo $row['empContact1'] . "<br>"; echo $row['empContact2'] . "<br>"; echo $row['empContact3'] . "<br>"; echo $row['empContact4'] . "<br>"; echo "</td>"; echo "</tr>"; } ?> </table> <br> <button onclick="window.location.href='emailtoprinter.php'">Continue</button> <h3><a href="javascript:history.go(-1)">Return to list</a></h3> <h3><a href="admin.php">Go to Admin Page</a></h3> <h3><a href="http://highlands.edu">Exit</a></h3> </div> </div> </body> </html> <file_sep><?php /* * Get Group Count by Campus */ // Save new asessment to database function ViewGroupCount() { include 'dbConn.php'; try { // PHP PDO SQL Statement $sql = "SELECT campus, COUNT(ohdate) AS Ct FROM submissions WHERE ohdate >= CURDATE() GROUP BY campus;"; $stm = $dbhopenhouse->prepare($sql); $stm->execute(); // Fetch the results in a numbered array $getEvents = $stm->fetchALL(PDO::FETCH_NUM); $badge = ""; foreach ($getEvents as $row) { $badge .= '<button class="btn btn-info" type="button"> <span class="badge"> '.$row[1].' </span> '.$row[0].'</button> | '; } echo $badge; // Close the dbh connection $dbhopenhouse = null; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } } ViewGroupCount(); <file_sep><? include "inc/init.php"; $type = $_GET['type']; if($type=='completed') { $sql= "select * from Orders, Campus where empCampus=idCampus AND recdFmPrinter = '1'"; } elseif($type=='printer') { $sql= "select * from Orders, Campus where empCampus=idCampus AND sentToPrinter = '1' AND recdFmPrinter <> '1'"; } else { $sql= "select * from Orders, Campus where empCampus=idCampus ORDER BY empName"; } $businessCard = new BusinessCard(); $stmt=$businessCard->rawSelect($sql); $row_count = $stmt->rowCount(); ?> <script language="Javascript1.2"> function printpage() { window.print(); } </script> <body onload="printpage()"> <table width="1020" cellpadding="5" cellspacing="0" border="0"><td align="left" style="font-size: 20px; font-weight: bold;">Business Card Requests</td></tr></table> <div style="padding: 20px; width: 990px; text-align: left;"> <table width="980" cellpadding="5" cellspacing="0" border="0"> <tr> <td valign="top"> <table width="950" cellpadding="5" cellspacing="0" border="1"> <tr><td width="220"><b>Employee Name</b></td><td><b>Requestor</b></td><td><b>Date Requested</b></td><td><b>Date to Printer</b></td><td><b>Date Completed</b></td></tr> <? foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { ?> <tr><td width="220"><? echo $row['empName'] ?></td><td><? echo $row['reqName'] ?></td><td><? echo $row['dateReceived'] ?></td><td><? echo $row['dateToPrinter'] ?></td><td><? echo $row['dateFmPrinter'] ?></td></tr> <? }?> </table> </body> </html> <file_sep><? include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Confirmation</h1> <p>Request Business Cards Online <br> <br> </p> </div> <?php $crud= new Crud(); $_SESSION['empName']=$_POST['empName']; $_SESSION['empTitle']= $_POST['empTitle']; $_SESSION['empContact'] = $_POST['empContact']; $_SESSION['empCampus'] = $_POST['empCampus']; $_SESSION['empFund'] = $_POST['empFund']; $_SESSION['empDept'] = $_POST['empDept']; $_SESSION['empProgram'] = $_POST['empProgram']; $_SESSION['empClass'] = $_POST['empClass']; $_SESSION['empProject'] = $_POST['empProject']; ?> <h2 style="color: yellow; text-align:center">Please proof your information carefully before submitting.</h2> <h2 style="color: yellow; text-align:center">The information you provide will be copied directly to the business card template and no additional proof will be provided.</h2> <h2 style="color: yellow; text-align:center"> For questions, please contact <NAME> at x6784.</h2> <div class="well" style="padding:20px 100px 10px 100px;"> <h3>Name</h3> <h4><? echo $_SESSION['empName']; ?></h4> <p> <h3>Title</h3> <h4><? echo $_SESSION['empTitle']; ?></h4> <p> <h3>Contact</h3> <h4><? echo $_SESSION['empContact']; ?></h4> <p> <h3>Campus</h3> <h4><? echo $_SESSION['empCampus']; ?></h4> <p> <h3>Budget Information</h3> <h4><? echo $_SESSION['empDept'] . " " . $_SESSION['empProgram'] . " " . $_SESSION['empClass'] . " " . $_SESSION['empProject']; ?></h4> <input type="button" onclick="location.href='thankyou.php';" value="Submit Business Card Request" /><p><p> <input type="button" onclick="window.history.back();" value="Return to Submission Form" /> </div><file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Resubmission</h1> <p>Your business card order has been resubmitted</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? $idOrders = $_GET['idOrders']; $empName = $_GET['empName']; $empTitle1 = $_GET['empTitle1']; $empTitle2 = $_GET['empTitle2']; $empContact1 = $_GET['empContact1']; $empContact2 = $_GET['empContact2']; $empContact3 = $_GET['empContact3']; $empContact4 = $_GET['empContact4']; $empFund = $_GET['empFund']; $empDept = $_GET['empDept']; $empProgram = $_GET['empProgram']; $empClass = $_GET['empClass']; $empProject = $_GET['empProject']; $businessCard = new BusinessCard(); $sql="UPDATE `Orders` SET `rejected`='0' ,`empName` = '" . $empName . "' , `empTitle1` = '" . $empTitle1 . "' , `empTitle2` = '" . $empTitle2 . "' ,`empContact1` = '" . $empContact1 . "' ,`empContact2` = '" . $empContact2 . "' , `empContact3` = '" . $empContact3 . "' , `empContact4` = '" . $empContact4 . "' , `empFund` = '" . $empFund . "' ,`empDept` = '" . $empDept . "' ,`empProgram` = '" . $empProgram . "' ,`empClass` = '" . $empClass . "' ,empProject = '" . $empProject . "' WHERE `idOrders` ='$idOrders'" ; $businessCard->rawQuery($sql); ?> <h2>Thank you!!</h2> <h3><a href="http://highlands.edu">Exit</a></h3> </div> </div> <body> <html> <file_sep><?php date_default_timezone_set('UTC'); $name = "Testing"; $phone = "1234569874"; $email = "<EMAIL>"; $attending = "25"; $major = "Math"; $dates = "Testing date 00/00/2314"; // PHP PDO globalize connection string // Connection parameters $user = "webguy"; $pass = "<PASSWORD>"; $host = "127.0.0.1"; $dbname = "openhouse"; // Set Database Handle $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $sql = "SELECT * FROM submissions"; $stm = $dbh->prepare($sql); $stm->execute(); $results = $stm->fetch(PDO::FETCH_ASSOC); echo "stuff should be here"; print_r($results); ?> <file_sep><?php /* * Get Event Request ready for ajax jQuery call */ // Save new asessment to database function ViewEventRequest() { include 'dbConn.php'; try { echo "<legend>Open House Schedules</legend>"; // PHP PDO SQL Statement $sql = "SELECT campus, ohdate, name, (SELECT COUNT(DISTINCT ohdate) AS totalrows FROM submissions WHERE campus = 'Floyd/Rome, GA') as totalrows FROM submissions WHERE campus = 'Floyd/Rome, GA' ORDER BY ohdate ASC;"; $stm = $dbhopenhouse->prepare($sql); $stm->execute(); // Fetch the results in a numbered array $getEvents = $stm->fetchALL(PDO::FETCH_NUM); print_r($getEvents); // Close the dbh connection $dbhopenhouse = null; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } } ViewEventRequest(); <file_sep><?php /* * Get Event Dates ready for ajax jQuery call */ // Filter out post variables for security $value = htmlentities($_POST['campVal'], ENT_QUOTES, 'UTF-8'); // Save new asessment to database function ViewEventRequest($value) { include 'dbConn.php'; try { echo "<legend>Open House Schedules</legend>"; // PHP PDO SQL Statement $sql = "SELECT campus, ohdate FROM submissions WHERE campus = :value1 GROUP BY ohdate;"; $stm = $dbhopenhouse->prepare($sql); $stm->bindParam(':value1', $value); $stm->execute(); // Fetch the results in a numbered array $getEvents = $stm->fetchALL(PDO::FETCH_NUM); $opt = "<option disabled selected>select date to view</option>"; foreach ($getEvents as $row) { $opt .= "<option value='" . $row[1] . "'>" . date("F j, Y, g:i a", strtotime($row[1])) . "</option>"; } echo $opt; // Close the dbh connection $dbhopenhouse = null; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } } ViewEventRequest($value); <file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order</h1> <p>Cards have been marked a delivered</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? $empName = $_GET['empName']; $reqName = $_GET['reqName']; $reqEmail = $_GET['reqEmail']; $idOrders = $_GET['idOrders']; $rejectComments = $_GET['rejectComments']; $idOrders = $_GET['idOrders']; $my_date = date("Y-m-d"); $businessCard = new BusinessCard(); $sql="UPDATE `Orders` SET `rejected`='1' ,`dateRejected` = '" . $my_date . "' , rejectComments = '" . $rejectComments . "' WHERE `idOrders` ='$idOrders'" ; $businessCard->rawQuery($sql); reject_mail($idOrders, $empName, $rejectComments, $servername, $reqName, $reqEmail) ?> <h2>An email has been sent to Requestor</h2> <h3><a href="requests.php">Return to pending list</a></h3> <h3><a href="admin.php">Go to Admin Page</a></h3> <h3><a href="http://highlands.edu">Exit</a></h3> </div> </div> <body> <html> <file_sep>// View events functions $(function() { $.ajax({ url: "ldapLib/loginCheck.php", success: function(data) { console.log(data); if (data == "not_logged_in"){ window.location.replace("https://forms.highlands.edu/studentlife/login.php"); } else { $("#chk").html(data); // echo out whatever is returned } return false; } }); }); <file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order Report</h1> <p>Sent to Printer</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? $businessCard = new BusinessCard(); $sql= "select * from Orders, Campus where empCampus=idCampus AND sentToPrinter = '1' AND recdFmPrinter <> '1'"; //$sql= "select * from Orders, Campus where empCampus=idCampus AND sentToPrinter = '1'"; $stmt=$businessCard->rawSelect($sql); $row_count = $stmt->rowCount(); if($row_count < 1) { echo "<h3>There are no orders with the printer</h3>"; } else { ?> <h2 align='center'>Received from Printer</h2> <button onclick="window.location.href='print_form.php?type=printer'">Print</button><p> <div class="table-responsive"> <table class="table" border="1"> <tr> <td><h4>Name</h4></td><td><h4>Title</h4></td><td><h4>Campus</h4></td><td><h4>Contact Info</h4></td><td><h4>Date <br>Requested</h4></td><td><h4>Date Sent <br> to Printer</h4></td><td><h4>Received <br> from Printer</h4></td> </tr> <form action="receivedfromprinter.php" id="frmRecd" method="post"> <h3 align='center'>Date Received from Printer<input type="date" id="recdDate" id="dateReceived" name="Received" min="2015-10-20" required=""></h3> <h4 id="errorMsg" align='center' style="color:red"></h4> <? foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { echo "<tr>"; echo "<td>"; echo $row['empName']; echo "</td>"; echo "<td>"; echo $row['empTitle1'] . "<br>"; echo $row['empTitle2']; echo "</td>"; echo "<td>"; echo $row['nameCampus']; echo "</td>"; echo "<td>"; echo $row['empContact1'] . "<br>"; echo $row['empContact2'] . "<br>"; echo $row['empContact3'] . "<br>"; echo $row['empContact4']; echo "</td>"; echo "<td>"; echo $row['dateReceived']; echo "</td>"; echo "<td>"; echo $row['dateToPrinter']; echo "</td>"; echo "<td align='center'>"; ?> <input type="checkbox" name="OrderID[]" value="<? echo $row['idOrders'] ?>" /> <? echo "</td>"; echo "</tr>"; } ?> </table> </div> <br> <input type="submit" /> </form> <? } ?> <h3><a href="admin.php">Go to Admin Page</a></h3> <h3><a href="http://highlands.edu">Exit</a></h3> </div> <script> alert("text"); </script> </body> </html><file_sep><?php /* * Get Event Request ready for ajax jQuery call */ // Filter out post variables for security $campus = htmlentities($_POST['campus'], ENT_QUOTES, 'UTF-8'); $ohdate = htmlentities($_POST['getdate'], ENT_QUOTES, 'UTF-8'); // Save new event to database function AddOpenHouse($campus, $ohdate) { require_once 'dbConn.php'; try { // PHP PDO SQL Statement $sql = "INSERT INTO opendates (campus,eventdate)" ."VALUES (:campus,:eventdate)"; $stm = $dbhopenhouse->prepare($sql); $stm->bindParam(':campus', $campus); $stm->bindParam(':eventdate', $ohdate); $stm->execute(); // Close the dbh connection $dbhopenhouse = null; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } } AddOpenHouse($campus, $ohdate); <file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order</h1> <p>Send to Printer</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? $businessCards = new BusinessCard(); //$sql="UPDATE `Orders` SET `sentToPrinter`='1' WHERE `idOrders` IN ("; $sql = "SELECT * FROM Business_card.Orders where idOrders IN ("; $count=count ($_POST['OrderID']); $i = 1; $_SESSION['OrderID'] = $_POST['OrderID']; foreach($_POST['OrderID'] as $OrderID) { if($i < $count ) { $sql=$sql . "'" . $OrderID . "',"; $i++; } else { $sql=$sql . "'" . $OrderID . "')"; } } ?> <h2>The following requests will be forwarded to the printer</h2> <br> <br> <table border="1"> <tr> <td width='200'><h4>Name</h4></td><td width='300'><h4>Title</h4></td><td width='100'><h4>Campus</h4></td><td width='400'><h4>Contact Info</h4></td> </tr> <? foreach($businessCards->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { echo "<tr>"; echo "<td>"; echo $row['empName']; echo "</td>"; echo "<td>"; echo $row['empTitle']; echo "</td>"; echo "<td>"; echo $row['empCampus']; echo "</td>"; echo "<td>"; echo $row['empContact']; echo "</td>"; /* echo "<td>"; echo $row['empFund'] . " " . $row['empDept'] . " " . $row['empProgram'] . " " . $row['empClass'] . " " . $row['empProject']; echo "</td>"; */ echo "</tr>"; } ?> </table> <br> <button onclick="window.location.href='sent.php'">Continue</button> <file_sep><?php include "inc/header.inc"; include "inc/init.php"; $mail_sql = $_SESSION['sql']; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order</h1> <p>Send to Printer</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? //Create today's date variable $my_date = date("Y-m-d"); $businessCard = new BusinessCard(); $sql="UPDATE `Orders` SET `sentToPrinter`='1' ,`dateToPrinter` = '" . $my_date . "' WHERE `idOrders` IN ("; // $sql = "SELECT * FROM Business_card.Orders where idOrders IN ("; $count=count ($_SESSION['OrderID']); $i = 1; foreach($_SESSION['OrderID'] as $OrderID) { if($i < $count ) { $sql=$sql . "'" . $OrderID . "',"; $i++; } else { $sql=$sql . "'" . $OrderID . "')"; } } $businessCard->rawQuery($sql); //$to = "<EMAIL>"; $to = "<EMAIL>"; $subject = "A Business Card order has been submitted by Georgia Highlands College"; $message = " <html> <head> <title>A Business Card order has been submitted by Georgia Highlands College</title> </head> <body> <h2>A Business Card order has been submitted by Georgia Highlands College</h2> <table border='1'> <tr> <th width='200'>Employee Name</th> <th width='200'>Title 1</th> <th width='200'>Title 2</th> <th width='400'>Address</th> <th width='400'>Contact Info</th> </tr> <tr>"; foreach($businessCard->rawSelect($mail_sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { $message=$message ."<td>" . $row['empName'] . "</td>"; $message=$message ."<td>" . $row['empTitle1'] . "</td>"; $message=$message ."<td>" . $row['empTitle2'] . "</td>"; $message=$message ."<td>" . $row['addressCampus'] . "<br>highlands.edu</td>"; $message=$message ."<td>" . $row['empContact1'] . "<br>" . $row['empContact2'] . "<br>" . $row['empContact3'] . "<br>" . $row['empContact4'] . "</td>"; $message=$message . "</tr>"; } $message = $message . "</table> </body> </html>"; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: <<EMAIL>>' . "\r\n"; $headers .= 'Cc: <EMAIL>' . "\r\n"; mail($to,$subject,$message,$headers); ?> <h2>Thank you!!</h2> <h3><a href="admin.php">Go to Admin Page</a></h3> <h3><a href="http://highlands.edu">Exit</a></h3> </div> </div> <body> <html> <file_sep><? include "inc/header.inc" ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order Form</h1> <p>Request Business Cards Online <br> <br> </p> </div> <?php include "inc/class.Crud.inc"; $crud= new Crud(); //echo $crud->conn(); //print_r($_POST); $empName=$_POST['empName']; $empTitle= $_POST['empTitle']; $empContact = $_POST['empContact']; $empCampus = $_POST['empCampus']; $empFund = $_POST['fund']; $empDept = $_POST['dept']; $empProgram = $_POST['program']; $empClass = $_POST['class']; $empProject = $_POST['project']; $sql="INSERT INTO Orders (empName, empTitle, empContact, empCampus, empFund, empDept, empProgram, empClass, empProject) VALUES ('$empName', '$empTitle', '$empContact', '$empCampus','$empFund','$empDept', '$empProgram','$empClass','$empProject')"; $crud->rawQuery($sql); ?> <div class="well" style="padding:20px 100px 10px 100px;"> <h2>Thank you for your order!!</h2> </div><file_sep>// this is the id of the form $("#addopen").click(function(e) { e.preventDefault(); var url = "php/addOpenHouse.php"; // the script where you handle the form input. $.ajax({ type: "POST", url: url, data: $("#addopenhouse").serialize(), // serializes the form's elements. success: function(data) { $("#results").hide(); $("#messageSaved").html('<div class="alert alert-dismissable alert-success"><button type="button" class="close" data-dismiss="alert">x</button><h3>Date Saved and Published!</h3></div>').delay(2000).fadeOut(4500); $("#results").delay(2000).fadeIn(3000); } }); return false; // avoid to execute the actual submit of the form. }); // On Campus Select Set Select Date Picker $('#selectCampus').on('change', function(e) { e.preventDefault(); var campVal = $(this).val(); $(function() { $.ajax({ type: "POST", url: "php/getDates.php", data: {'campVal': campVal}, success: function(data) { $("#selectDate").html(data); // echo out whatever is returned return false; } }); }); }); $(function() { $.ajax({ type: "POST", url: "php/getGroupCount.php", //data: $('.form').serialize(), success: function(data){ $('#groupcnt').html(data); return false; } }); }); /* $('#selectCamp').submit(function () { $.ajax({ type: "POST", url: "php/showDates.php", data: $("#selectCamp").serialize(), // serializes the form's elements. success: function() { $("#results").html("Download File..."); // echo out whatever is returned return false; } }); }); */ <file_sep><?php /* * Get Event Request ready for ajax jQuery call */ $eventId = htmlentities($_POST['id'], ENT_QUOTES, 'UTF-8'); //Adds commas only if another item follows in the list function formatArray($incomingArray) { $incomingArrayLength = count($incomingArray); $incomingArrayOutput = ""; foreach ($incomingArray as $key=>$arrayItem) { $incomingArrayOutput .= $arrayItem; if (($incomingArrayLength - 1) > $key) { $incomingArrayOutput .= ", "; } } return $incomingArrayOutput; } // Save new asessment to database function PrintEventDetail($eventId) { include 'dbConn.php'; try { // PHP PDO SQL Statement $sql = "SELECT * FROM studentlife.eventRequest WHERE id = :eventId"; $stm = $dbh->prepare($sql); $stm->bindParam(':eventId', $eventId); $stm->execute(); // Fetch the results in a numbered array $getEvents = $stm->fetchALL(PDO::FETCH_NUM); $print = ''; foreach($getEvents as $row) { $campus = json_decode($row[1], TRUE); $typeEvent = json_decode($row[31], TRUE); $clubs = json_decode($row[4], TRUE); $setup = json_decode($row[8], TRUE); $files = json_decode($row[23], TRUE); $print .= '<button type="button" class="btn btn-info printClose" style="margin:0px auto; position:relative; width:200px;">Close</button>'; $print .= "<div class='row' style='border:solid 1px #ccc;'>"; $print .= "<div class='col-sm-6'>"; $print .= "<h2>Requested Event</h2>"; $print .= "<p>Event Name: " . $row[2] . "</p>"; $print .= "<p>Event Type: " . formatArray($typeEvent) . "</p>"; $print .= "<p>Start Date: " . $row[5] . "</p>"; $print .= "<p>End Date: " . $row[6] . "</p>"; $print .= "<p>For Campus: " . formatArray($campus) . "</p>"; $print .= "<p>Description: " . $row[3] . "</p>"; $print .= "</div>"; $print .= "<div class='col-sm-6'>"; $print .= "<h2>Contact</h2>"; $print .= "<p>Requested By: $row[24]</p>"; $print .= "<p>Club Advisor:"; // show only Yes or No if ($row[26] == 1) {$print .= "&nbsp;Yes</p>";} if ($row[26] == 0) {$print .= "&nbsp;No</p>";} $print .= "<p>For Clubs: " . formatArray($clubs) . "</p>"; $print .= "<p>Contact Email: " . $row[25] . "</a></p>"; $print .= "</div></div>"; $print .= "<div class='row' style='border:solid 1px #ccc;'>"; $print .= "<div class='col-sm-6'>"; $print .= "<h2>Set Up Request</h2>"; $print .= "<p>Set Up: " . formatArray($setup) . "</p>"; // only show if equal 1 if ($row[9] == 1) { $print .= "<p>Chairs: " . $row[10] . "</p>"; } if ($row[11] == 1) { $print .= "<p>Tables: " . $row[12] . "</p>"; } if ($row[13] == 1) { $print .= "<p>Other: " . $row[14] . "</p>"; } $print .= "<p>Room: " . $row[7] . "</p>"; $print .= "<p>Comments: " . $row[27] . "</p>"; $print .= "<p>Estimated Total Cost: " . $row[33] . "</p>"; $print .= "</div>"; $print .= "<div class='col-sm-6'>"; $print .= "<h2>Food</h2>"; $print .= "<p>Food Type: " . $row[15] . "</p>"; $print .= "<p>Food Source: " . $row[16] . "</p>"; $print .= "<p>Food Cost: " . $row[17] . "</p>"; $print .= "<p>Food Reason: " . $row[21] . "</p>"; $print .= "<p>Attendance: " . $row[18] . "</p>"; $print .= "<p>Per Diem: " . $row[19] . "</p>"; $print .= "<p>Payment: " . $row[20] . "</p>"; $print .= "<p>Future Food Events: " . $row[22] . "</p>"; $print .= "</div></div>"; } echo $print; // Close the dbh connection $dbh = null; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } } PrintEventDetail($eventId); <file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order</h1> <p>Cards have been marked a delivered</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? $delDate = $_GET['Returned']; $delComments = $_GET['delComments']; $idOrders = $_GET['idOrders']; $businessCard = new BusinessCard(); $sql="UPDATE `Orders` SET `delivered`='1' ,`dateDelivered` = '" . $delDate . "' , delComments = '" . $delComments . "' WHERE `idOrders` ='$idOrders'" ; $businessCard->rawQuery($sql); ?> <h2>Thank you!!</h2> <h3><a href="printed.php">Deliver more Cards</a></h3> <h3><a href="admin.php">Go to Admin Page</a></h3> <h3><a href="http://highlands.edu">Exit</a></h3> </div> </div> <body> <html> <file_sep><? include "inc/init.php"; $sql= "select * from Orders, Campus where sentToPrinter <> '1' AND rejected <> '1' AND empCampus = idCampus ORDER BY dateReceived DESC" ; $businessCard = new BusinessCard(); $stmt=$businessCard->rawSelect($sql); $row_count = $stmt->rowCount(); ?> <script language="Javascript1.2"> function printpage() { window.print(); } </script> <body onload="printpage()"> <table width="1020" cellpadding="5" cellspacing="0" border="0"><td align="left" style="font-size: 20px; font-weight: bold;">Business Card Requests</td></tr></table> <div style="padding: 20px; width: 990px; text-align: left;"> <table width="980" cellpadding="5" cellspacing="0" border="0"> <tr> <td valign="top"> <table width="950" cellpadding="5" cellspacing="0" border="1"> <tr><td width="180"><b>Employee Name</b></td><td><b>Title</b></td><td><b>Campus</b></td><td><b>Requestor</b></td><td><b>Accting</b></td><td><b>Date Requested</b></td></tr> <? foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { ?> <tr><td width="180"><? echo $row['empName'] ?></td><td><? echo $row['reqName'] ?></td><td><? echo $row['nameCampus'] ?></td><td><? echo $row['reqName'] ?></td> <td><? echo $row['empFund'] ?>&nbsp;<? echo $row['empDept'] ?><? echo $row['empProgram'] ?>&nbsp;<? echo $row['empClass'] ?>&nbsp;<? echo $row['empProject'] ?>&nbsp;</td><td><? echo $row['dateReceived'] ?>&nbsp;</td></tr> <? }?> </table> </body> </html> <file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order Report</h1> <p>All Orders</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? $businessCard = new BusinessCard(); $sql= "select * from Orders, Campus where empCampus=idCampus ORDER BY empName"; $stmt=$businessCard->rawSelect($sql); $row_count = $stmt->rowCount(); if($row_count < 1) { echo "<h3>There are no orders </h3>"; } else { ?> <h2 align='center'>All Orders</h2> <button onclick="window.location.href='print_form.php?type=all'">Print</button><p> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover"> <tr> <td><h4>Employee Name</h4></td><td><h4>Requestor</h4></td><td><h4>Date Requested</h4></td><td><h4>Date Completed</h4></td> </tr> <? foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { echo "<tr>"; echo "<td>"; ?> <a href="orderdetails.php?idOrders=<? echo $row['idOrders'] ?>" ><? echo $row['empName'] ?></a> <? echo "</td>"; echo "<td>"; echo $row['reqName']; echo "</td>"; echo "<td>"; echo $row['dateReceived']; echo "</td>"; echo "<td>"; echo $row['dateFmPrinter']; echo "</td>"; echo "</tr>"; } ?> <? } ?> </table> </div> <h3><a href="admin.php">Go to Admin Page</a></h3> <h3><a href="http://highlands.edu">Exit</a></h3> </div> </div> </body> </html> <file_sep><?php /* * Get Event Status ready for ajax jQuery call */ $eventId = intval($_POST['id']); $status = intval($_POST['value']); $archived = 0; // Save new asessment to database function setEventStatus($eventId, $status, $archived) { include 'dbConn.php'; include 'PHPMailer/PHPMailerAutoload.php'; /* Prepare the sql statements */ $sqlUpdate = "UPDATE studentlife.eventRequest SET eStatus = :status, archived = :archived WHERE id = :id"; $sthUpdate = $dbh->prepare($sqlUpdate); $sthUpdate->bindParam(":status", $status); $sthUpdate->bindParam(":archived", $archived); $sthUpdate->bindParam(":id", $eventId); $sthUpdate->execute(); $sqlSelect = "SELECT * FROM studentlife.eventRequest WHERE id = :eventId"; $sthSelect = $dbh->prepare($sqlSelect); $sthSelect->bindParam(":eventId", $eventId); $sthSelect->execute(); // Fetch the results in a numbered array $results = $sthSelect->fetchALL(PDO::FETCH_NUM); $campuses = json_decode($results[0][1], TRUE); $pcampus = ''; foreach ($campuses as $campus) { $pcampus .= "$campus, "; } $clubs = json_decode($results[0][4], TRUE); $pclubs = ''; foreach ($clubs as $club) { $pclubs .= "$club, "; } $setups = json_decode($results[0][8], TRUE); $psetup = ''; foreach ($setups as $setup) { $psetup .= "$setup, "; } if ($results[0][29] == 1) { //Create a new PHPMailer instance $mail = new PHPMailer(); //Tell PHPMailer to use SMTP $mail->isSMTP(); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = 0; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; //Set the hostname of the mail server $mail->Host = "mail.highlands.edu"; //Set the SMTP port number - likely to be 25, 465 or 587 $mail->Port = 25; //Whether to use SMTP authentication $mail->SMTPAuth = false; //Set who the message is to be sent from $mail->setFrom('<EMAIL>', 'Student Life'); //Set an alternative reply-to address $mail->addReplyTo('<EMAIL>', 'Student Life'); //Set who the message is to be sent to $mail->addAddress('<EMAIL>', 'Webmaster TLP'); $mail->addAddress($results[0][25], $results[0][24]); //Set the subject line $mail->Subject = "Event " . $results[0][2] . " is Approved! Details Inside."; //Read an HTML message body from an external file, convert referenced images to embedded, //convert HTML into a basic plain-text alternative body //$mail->msgHTML(file_get_contents('emailContent/emailContent.html'), dirname(__FILE__)); // Set email format to HTML $mail->isHTML(true); $mail->Body = 'Thank you for your online event submission.' . '<br/>Your event <strong>' . $results[0][2] . '</strong> is Approved. Please keep this email for your records.<br/><hr/>' . '<strong>Event Details:</strong><br/>' . 'Event Name: ' . $results[0][2] . '<br/>' . 'Start Date: ' . $results[0][5] . '<br/>' . 'End Date: ' . $results[0][6] . '<br/>' . 'For Campus: ' . $pcampus . '<hr/>' . 'For Clubs: ' . $pclubs . '<hr/>' . '<strong>Set Up Request:</strong><br/>' . 'Set Up: ' . $psetup . '<br/>' . 'Chairs: ' . $results[0][10] . '<br/>' . 'Tables: ' . $results[0][12] . '<br/>' . 'Other: ' . $results[0][14] . '<br/>' . 'Room: ' . $results[0][7] . '<br/>' . 'Comments: ' . $results[0][27] . '<hr/>' . '<strong>Food Request:</strong><br/>' . 'Food Type: ' . $results[0][15] . '<br/>' . 'Food Source: ' . $results[0][16] . '<br/>' . 'Food Cost: ' . $results[0][17] . '<br/>' . 'Food Reason: ' . $results[0][21] . '<br/>' . 'Future Food Events: ' . $results[0][22] . '<br/>' . 'Attendance: ' . $results[0][18] . '<br/>' . 'Per Diem: ' . $results[0][19] . '<br/>' . 'Payment: ' . $results[0][20] . '<br/><hr/>' . 'If you have any questions or concerns, please contact your student life coordinator.' . '<br/><br/>Thank You, <br/>Student Life'; //Replace the plain text body with one created manually $mail->AltBody = "Thank you for your online event submission.\r\n" . "Your event submission has been Approved. Please keep this email for your records.\r\n" . "If you have any questions or concerns, please contact your student life coordinator.\r\n\r\n" . "Thank You, \nStudent Life"; //Attach an image file // $mail->addAttachment('someFile.png'); //send the message, check for errors if (!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent to " . $results[0][25]; } } if ($results[0][29] == 0) { //Create a new PHPMailer instance $mail = new PHPMailer(); //Tell PHPMailer to use SMTP $mail->isSMTP(); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = 0; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; //Set the hostname of the mail server $mail->Host = "mail.highlands.edu"; //Set the SMTP port number - likely to be 25, 465 or 587 $mail->Port = 25; //Whether to use SMTP authentication $mail->SMTPAuth = false; //Set who the message is to be sent from $mail->setFrom('<EMAIL>', 'Student Life'); //Set an alternative reply-to address $mail->addReplyTo('<EMAIL>', 'Student Life'); //Set who the message is to be sent to $mail->addAddress('<EMAIL>', 'Webmaster TLP'); $mail->addAddress($results[0][25], $results[0][24]); //Set the subject line $mail->Subject = "Event " . $results[0][2] . " is Denied! Details Inside."; //Read an HTML message body from an external file, convert referenced images to embedded, //convert HTML into a basic plain-text alternative body //$mail->msgHTML(file_get_contents('emailContent/emailContent.html'), dirname(__FILE__)); // Set email format to HTML $mail->isHTML(true); $mail->Body = 'Thank you for your online event submission.' . '<br/>Your event ' . $results[0][2] . ' has been Denied. Please keep this email for your records.<br/><br/>' . 'A student life coordinator will be contacting you about this event and details on how you can improve your submission to have your event approved.' . '<br/><br/>Contact your student life coordinator with any questions you may have.' . '<br/><br/>Thank You, <br/>Student Life'; //Replace the plain text body with one created manually $mail->AltBody = "Thank you for your online event submission.\r\n" . "Your event has been Denied. \r\n" . "A student life coordinator will be contacting you about this event and details on how you can improve your submission to have your event approved.\r\n" . "Contact your student life coordinator with any questions you may have.\r\n\r\n" . "Thank You, \r\nStudent Life"; //Attach an image file // $mail->addAttachment('someFile.png'); //send the message, check for errors if (!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent " . $results[0][25]; } } // Close the dbh connection $dbh = null; } setEventStatus($eventId, $status, $archived); <file_sep><?php /* * Get Event Request ready for ajax jQuery call */ // Filter out post variables for security $name = htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8'); $phone = htmlentities($_POST['phone'], ENT_QUOTES, 'UTF-8'); $phone = preg_replace('/[^\d-]+/', '', $phone); $email = htmlentities($_POST['email'], ENT_QUOTES, 'UTF-8'); $attending = htmlentities($_POST['attending'], ENT_QUOTES, 'UTF-8'); $major = htmlentities($_POST['major'], ENT_QUOTES, 'UTF-8'); $ohdate = htmlentities($_POST['rsvp'], ENT_QUOTES, 'UTF-8'); // Save new event to database function InsertOpenHouse($name, $phone, $email, $attending, $major, $ohdate) { require_once 'dbConn.php'; $timestamp = date("Y-m-d H:i:s"); try { $sqlCampus = "SELECT opendates.campus, submissions.ohdate, opendates.eventdate FROM submissions, opendates WHERE submissions.ohdate = :ohdateCampus AND submissions.ohdate = opendates.eventdate;"; $stmCampus = $dbhopenhouse->prepare($sqlCampus); $stmCampus->bindParam(':ohdateCampus', $ohdate); $stmCampus->execute(); // Fetch the results in a numbered array $getstmCampus = $stmCampus->fetchALL(PDO::FETCH_NUM); $campus = $getstmCampus[0][0]; // PHP PDO SQL Statement $sql = "INSERT INTO submissions (name,phone,email,attendingguest,major,datesubmitted,campus,ohdate)" ."VALUES (:name,:phone,:email,:attending,:major,:timestamp,:campus,:ohdate)"; $stm = $dbhopenhouse->prepare($sql); $stm->bindParam(':name', $name); $stm->bindParam(':phone', $phone); $stm->bindParam(':email', $email); $stm->bindParam(':attending', $attending); $stm->bindParam(':major', $major); $stm->bindParam(':timestamp', $timestamp); $stm->bindParam(':campus', $campus); $stm->bindParam(':ohdate', $ohdate); $stm->execute(); // Close the dbh connection $dbhopenhouse = null; //SMTP needs accurate times, and the PHP time zone MUST be set //This should be done in your php.ini, but this is how to do it if you don't have access to that //date_default_timezone_set('Etc/UTC'); require_once 'PHPMailer/PHPMailerAutoload.php'; //Create a new PHPMailer instance $mail = new PHPMailer(); //Tell PHPMailer to use SMTP $mail->isSMTP(); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = 0; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; //Set the hostname of the mail server $mail->Host = "mail.highlands.edu"; //Set the SMTP port number - likely to be 25, 465 or 587 $mail->Port = 25; //Whether to use SMTP authentication $mail->SMTPAuth = false; //Set who the message is to be sent from $mail->setFrom('<EMAIL>', 'Preview Day at GHC'); //Set an alternative reply-to address $mail->addReplyTo('<EMAIL>', 'Preview Day at GHC'); //Set who the message is to be sent to $mail->addAddress('<EMAIL>', 'Preview Day'); $mail->addAddress('<EMAIL>', 'Preview Day'); //Set the subject line $mail->Subject = "New Preview View Submission"; //Read an HTML message body from an external file, convert referenced images to embedded, //convert HTML into a basic plain-text alternative body //$mail->msgHTML(file_get_contents('emailContent/emailContent.html'), dirname(__FILE__)); // Set email format to HTML $mail->isHTML(true); $mail->Body = 'A request to attend an Preview Day was submitted from ' . $name . ' for ' . $ohdate; //Replace the plain text body with one created manually $mail->AltBody = 'A request to attend an Preview Day was submitted from ' . $name . ' for ' . $ohdate; //Attach an image file // $mail->addAttachment('someFile.png'); //send the message, check for errors if (!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent!"; } } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } } InsertOpenHouse($name, $phone, $email, $attending, $major, $ohdate); <file_sep><?php $html = new DOMDocument('1.0', 'iso-8859-1'); $html->formatOutput = true; $elem = $html->createElement('input'); $elem->setAttribute('type','button'); $elem->setAttribute('value','My Button'); $elem->setAttribute('style','width:125px'); $html->appendChild($elem); echo html_entity_decode($html->saveHTML()); ?> <file_sep><?php //include "inc/header.inc"; include "inc/init.php"; $businessCards = new BusinessCard(); $sql="UPDATE `Orders` SET `sentToPrinter`='1' WHERE `idOrders` IN ("; $count=count ($_GET['OrderID']); $i = 1; foreach($_GET['OrderID'] as $OrderID) { if($i < $count ) { $sql=$sql . "'" . $OrderID . "',"; $i++; } else { $sql=$sql . "'" . $OrderID . "')"; } } echo $sql; echo "<br>"; echo "UPDATE `Orders` SET `sentToPrinter`='1' WHERE `idOrders` IN ('29','30')"; $businessCards->rawQuery($sql); ?><file_sep><? include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Confirmation</h1> <p>Request Business Cards Online <br> <br> </p> </div> <?php $businessCard= new BusinessCard(); $empName=$_SESSION['empName']; $empTitle1= $_SESSION['empTitle1']; $empTitle2= $_SESSION['empTitle2']; $empContact1 = $_SESSION['empContact1']; $empContact2 = $_SESSION['empContact2']; $empContact3 = $_SESSION['empContact3']; $empContact4 = $_SESSION['empContact4']; $empCampus = $_SESSION['empCampus']; $empFund = $_SESSION['empFund']; $empDept = $_SESSION['empDept']; $empProgram = $_SESSION['empProgram']; $empClass = $_SESSION['empClass']; $empProject = $_SESSION['empProject']; $reqName = $_SESSION['reqName']; $reqEmail = $_SESSION['reqEmail']; $dateReceived = date("Y-m-d"); $campus_sql="SELECT nameCampus FROM Campus where idCampus = $empCampus"; foreach($businessCard->rawSelect($campus_sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { echo $nameCampus = $row['nameCampus']; } $sql="INSERT INTO Orders (empName, empTitle1, empTitle2, empContact1, empContact2, empContact3, empContact4,empCampus, empFund, empDept, empProgram, empClass, empProject, reqName, reqEmail, dateReceived) VALUES ('$empName', '$empTitle1', '$empTitle2', '$empContact1', '$empContact2', '$empContact3', '$empContact4' , '$empCampus','$empFund','$empDept', '$empProgram','$empClass','$empProject','$reqName','$reqEmail','$dateReceived')"; echo "test"; $businessCard->rawQuery($sql); send_mail($empName, $nameCampus , $servername, $reqName); ?> <div class="well" style="padding:20px 100px 10px 100px;"> <h1>Thank you</h1> <h2>Your request has been forwarded for processing</h2> </div> <div class="well" style="padding:20px 100px 10px 100px;"> <h2><a href="index.php">Request more business cards</a></h2> <h2><a href="http://highlands.edu">Exit</a></h2> </div> <file_sep><?php session_start(); $servername = $_SERVER['SERVER_NAME']; //include crud include_once 'class.Crud.inc'; include_once 'class.BusinessCard.inc'; include_once 'php_functions.inc'; ?><file_sep><? include "inc/header.inc"; include "inc/init.php"; $businessCard = new BusinessCard(); $idOrders = $_GET['idOrders']; $sql= "Select * from Orders, Campus where empCampus=idCampus AND idOrders = $idOrders"; foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { $empName = $row['empName']; $empTitle1 = $row['empTitle1']; $empTitle2 = $row['empTitle2']; $nameCampus = $row['nameCampus']; $empContact1 = $row['empContact1']; $empContact2 = $row['empContact2']; $empContact3 = $row['empContact3']; $empContact4 = $row['empContact4']; $reqName = $row['reqName']; $reqEmail = $row['reqEmail']; $empFund = $row['empFund']; $empDept = $row['empDept']; $empProgram = $row['empProgram']; $empClass = $row['empClass']; $empProject = $row['empProject']; $rejectComments = $row['rejectComments']; } ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Rejected Business Card Order</h1> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <fieldset> <!-- Form Name --> <h2> Please correct information and click submit </h2> <form action="user_resubmit.php" method="get"> <div class="form-group col-md-8"> <!-- Text input--> <h3>Name</h3> <input class="form-control" name="empName" type="text" value="<? echo $empName ?>"> <!-- Text input--> <h3>Title</h3> <input class="form-control" name="empTitle1" type="text" value="<? echo $empTitle1 ?>"> <br> <input class="form-control" name="empTitle2" type="text" value="<? echo $empTitle2 ?>"> <!-- Text input--> <h3>Contact Information</h3> <input class="form-control" name="empContact1" type="text" value="<? echo $empContact1 ?>"> <br> <input class="form-control" name="empContact2" type="text" value="<? echo $empContact2 ?>"> <br> <input class="form-control" name="empContact3" type="text" value="<? echo $empContact3 ?>"> <br> <input class="form-control" name="empContact4" type="text" value="<? echo $empContact4 ?>"> <h3>Campus</h3> <inputclass="form-control" value="<? echo $nameCampus ?>"> <br> <h3>Requestor's Name</h3> <input class="form-control" value="<? echo $reqName ?>"> <!-- Text input--> <h3>Requestor's Email Address</h3> <input class="form-control" type="email" value="<? echo $reqEmail ?>"> <h3>Rejector's comments</h3> <input size="100" value="<? echo $rejectComments ?>"> <h3>Budget Information</h3> <p> <input class="form-control" maxlength="5" name="empFund" type="text" value="<? echo $empFund ?>"> <input class="form-control" maxlength="7" name="empDept" type="text" value="<? echo $empDept ?>"> <input class="form-control" maxlength="5" name="empProgram" type="text" value="<? echo $empProgram ?>"> <input class="form-control" maxlength="5" name="empClass" type="text" value="<? echo $empClass ?>"> <input class="form-control" maxlength="20" name="empProject" type="text" value="<? echo $empProject ?>"> <input type="hidden" name="idOrders" value="<? echo $idOrders ?>" /> <p> <input type="submit" value="Submit" /> </form> </div> </body> </html> <file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order Report</h1> <p>Request Status</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? $businessCard = new BusinessCard(); $sql= "select * from Orders, Campus where empCampus=idCampus AND recdFmPrinter = '1' AND delivered <> '1'"; $stmt=$businessCard->rawSelect($sql); $row_count = $stmt->rowCount(); if($row_count < 1) { echo "<h3>There are no orders received from the printer</h3>"; } else { ?> <h2 align='center'>Ready for Delivery</h2> <div class="table-responsive"> <table class="table table-bordered table-striped"> <tr> <td width='300'><h4>Name</h4></td><td width='300'><h4>Title</h4></td><td width='100'><h4>Campus</h4></td><td width='200'><h4>Contact Info</h4></td><td width='150'><h4>Date Rec.</h4></td> </tr> <? foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { echo "<tr>"; echo "<td>"; ?> <a href="delivery.php?idOrders=<? echo $row['idOrders'] ?>" ><? echo $row['empName'] ?></a> <? echo "</td>"; echo "<td>"; echo $row['empTitle1'] . "<br>"; echo $row['empTitle2']; echo "</td>"; echo "<td>"; echo $row['nameCampus']; echo "</td>"; echo "<td>"; echo $row['empContact1'] . "<br>"; echo $row['empContact2'] . "<br>"; echo $row['empContact3'] . "<br>"; echo $row['empContact4'] . "<br>"; echo "</td>"; echo "<td>"; echo $row['dateFmPrinter']; echo "</td>"; echo "</tr>"; } ?> </table> </div> <? } ?> <h3><a href="admin.php">Go to Admin Page</a></h3> <h3><a href="http://highlands.edu">Exit</a></h3> </div> </div> </body> </html><file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order</h1> <p>Send to Printer</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? if(@!$_POST['OrderID']) { echo "<h2>Please select at least one order</h2>"; echo "<h3><a onclick='window.history.back();'>Return to List</a></h3>"; exit(0); } $businessCard = new BusinessCard(); $sql = "SELECT * FROM Orders, Campus where empCampus=idCampus AND idOrders IN ("; $count=count ($_POST['OrderID']); $i = 1; $_SESSION['OrderID'] = $_POST['OrderID']; foreach($_SESSION['OrderID'] as $OrderID) { if($i < $count ) { $sql=$sql . "'" . $OrderID . "',"; $i++; } else { $sql=$sql . "'" . $OrderID . "')"; } } $_SESSION['sql'] = $sql; ?> <h2>The following requests will be forwarded to the printer</h2> <br> <br> <table border="1"> <tr> <td width='200'><h4>Name</h4></td><td width='300'><h4>Title</h4></td><td width='100'><h4>Campus</h4></td><td width='400'><h4>Contact Info</h4></td> </tr> <? foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { echo "<tr>"; echo "<td>"; echo $row['empName']; echo "</td>"; echo "<td>"; echo $row['empTitle1'] . "<br>"; echo $row['empTitle2']; echo "</td>"; echo "<td>"; echo $row['nameCampus']; echo "</td>"; echo "<td>"; echo $row['empContact1'] . "<br>"; echo $row['empContact2'] . "<br>"; echo $row['empContact3'] . "<br>"; echo $row['empContact4'] . "<br>"; echo "</td>"; echo "</tr>"; } ?> </table> <br> <button onclick="window.location.href='sent.php'">Continue</button> <h3><a href="admin.php">Go to Admin Page</a></h3> <h3><a href="http://highlands.edu">Exit</a></h3> <? /* $to = "<EMAIL>"; $subject = "A Business Card order has been submitted by Georgia Highlands College"; $message = " <html> <head> <title>A Business Card order has been submitted by Georgia Highlands College</title> </head> <body> <h2>A Business Card order has been submitted by Georgia Highlands College</h2> <table border='1'> <tr> <th width='200'>Employee Name</th> <th width='200'>Title</th> <th width='400'>Campus</th> <th width='400'>Contact Info</th> </tr> <tr>"; foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { $message=$message ."<td>" . $row['empName'] . "</td>"; $message=$message ."<td>" . $row['empTitle1'] . "<br>" . $row['empTitle2'] . "</td>"; $message=$message ."<td>" . $row['nameCampus'] . "</td>"; $message=$message ."<td>" . $row['empContact1'] . "<br>" . $row['empContact2'] . "<br>" . $row['empContact3'] . "<br>" . $row['empContact4'] . "</td>"; $message=$message . "</tr>"; } $message = $message . "</table> </body> </html>"; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: <<EMAIL>>' . "\r\n"; //$headers .= 'Cc: <EMAIL>' . "\r\n"; mail($to,$subject,$message,$headers); */ ?> </div> </div> </body> </html> <file_sep><?php /* * Connect to DB using PHP PDO * TODO add in SSL and encryption methods */ date_default_timezone_set('UTC'); // PHP PDO globalize connection string global $dbhopenhouse; // Connection parameters $user = "webguy"; $pass = "<PASSWORD>"; $host = "127.0.0.1"; $dbname = "openhouse"; // Set Database Handle $dbhopenhouse = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); <file_sep>/* * copyrights 2014 GHC */ // submit form for validation clientside first $(function() { $('#openhouse').validate({// initialize the plugin // your rules and options, submitHandler: function(form) { $.ajax({ type: 'post', url: 'php/insertEvent.php', data: $(form).serialize(), success: function(responseData) { console.log(responseData); $(".messageSaved").html('<div class="alert alert-dismissable alert-success"><button type="button" class="close" data-dismiss="alert">x</button><h3>You successfully submitted your Preview Day at Georgia Highlands College.<br/>You will be contacted by a Preview Day Coordinator shortly.</h3><button type="button" class="btn btn-default" id="closebtn">Goto Highlands.edu</button></div>').fadeIn(); $(".well").fadeOut(); $('html, body').animate({scrollTop: $('.container').offset().top}, 'slow'); $("#closebtn").click(function(){ window.location.href = "http://www.highlands.edu"; }); }, error: function(responseData) { console.log('Ajax request not recieved!'); } }); // resets fields $("#openhouse").each(function() { this.reset(); }); return false; // blocks redirect after submission via ajax } }); }); // View events functions $(function() { $.ajax({ url: "php/viewOpenHouses.php", success: function(data) { console.log(data); $("#results").html(data); // echo out whatever is returned return false; } }); }); <file_sep><?php class Crud { protected $db; private $dsn = "mysql:host=localhost;dbname=Business_card"; private $username = "marc"; private $password = "<PASSWORD>"; /** * * Set variables * */ public function __set($name, $value) { switch($name) { case 'username': $this->username = $value; break; case 'password': $this->password = $value; break; case 'dsn': $this->dsn = $value; break; default: throw new Exception("$name is invalid"); } } /** * * @check variables have default value * */ public function __isset($name) { switch($name) { case 'username': $this->username = null; break; case 'password': $this->password = null; break; } } /** * * @Connect to the database and set the error mode to Exception * * @Throws PDOException on failure * */ public function conn() { isset($this->username); isset($this->password); if (!$this->db instanceof PDO) { $this->db = new PDO($this->dsn, $this->username, $this->password); $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } } /*** * * @select values from table * * @access public * * @param string $table The name of the table * * @param string $fieldname * * @param string $id * * @return array on success or throw PDOException on failure * */ public function dbSelect($table, $fieldname=null, $id=null) { $this->conn(); $sql = "SELECT * FROM `$table` WHERE `$fieldname`=:id"; $stmt = $this->db->prepare($sql); $stmt->bindParam(':id', $id); $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } /** * * @execute a raw query * * @access public * * @param string $sql * * @return array * */ public function rawSelect($sql) { $this->conn(); return $this->db->query($sql); } /** * * @run a raw query * * @param string The query to run * */ public function rawQuery($sql) { $this->conn(); $this->db->query($sql); } /** * * @Insert a value into a table * * @acces public * * @param string $table * * @param array $values * * @return int The last Insert Id on success or throw PDOexeption on failure * */ public function dbInsert($table, $values) { $this->conn(); /*** snarg the field names from the first array member ***/ $fieldnames = array_keys($values[0]); /*** now build the query ***/ $size = sizeof($fieldnames); $i = 1; $sql = "INSERT INTO $table"; /*** set the field names ***/ $fields = '( ' . implode(' ,', $fieldnames) . ' )'; /*** set the placeholders ***/ $bound = '(:' . implode(', :', $fieldnames) . ' )'; /*** put the query together ***/ $sql .= $fields.' VALUES '.$bound; /*** prepare and execute ***/ $stmt = $this->db->prepare($sql); foreach($values as $vals) { $stmt->execute($vals); } return $last_id = $this->db->lastInsertId(); } /** * * @Update a value in a table * * @access public * * @param string $table * * @param string $fieldname, The field to be updated * * @param string $value The new value * * @param string $pk The primary key * * @param string $id The id * * @throws PDOException on failure * */ public function dbUpdate($table, $fieldname, $value, $pk, $id) { $this->conn(); $sql = "UPDATE `$table` SET `$fieldname`='{$value}' WHERE `$pk` = :id"; $stmt = $this->db->prepare($sql); $stmt->bindParam(':id', $id, PDO::PARAM_STR); $stmt->execute(); } /** * * @Delete a record from a table * * @access public * * @param string $table * * @param string $fieldname * * @param string $id * * @throws PDOexception on failure * */ public function dbDelete($table, $fieldname, $id) { $this->conn(); $sql = "DELETE FROM `$table` WHERE `$fieldname` = :id"; $stmt = $this->db->prepare($sql); $stmt->bindParam(':id', $id, PDO::PARAM_STR); $stmt->execute(); } /** * * @execute a raw query * * @access public * * @param string $username * * @return array * */ /* public function userInfo($username) { $this->conn(); $sql ="select * from users as us inner join team_user as ut on us.user_id = ut.user_id inner join team te on ut.team_id=te.team_id where user_username='$username'"; return $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC); } */ /* public function userInfo($username) { $i = 0; $this->conn(); $sql ="select user_lname as lname, user_fname as fname, user_username as user_name, team_name, ut.team_id as team_id from users as us inner join team_user as ut on us.user_id = ut.user_id inner join team te on ut.team_id=te.team_id where user_username='$username'"; $stmt = $this->db->prepare($sql); $stmt->bindParam(':id', $id); $stmt->execute(); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach($rows as $row) { ++$i; foreach($row as $fieldname=>$value) { $this->$fieldname=$value; } } return $i; } */ public function teamInfo($team_id) { $this->conn(); $sql ="select * from team where team_id='$team_id'"; $stmt = $this->db->prepare($sql); $stmt->bindParam(':id', $id); $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } } /*** end of class ***/ ?><file_sep><?php $to = "<EMAIL>"; $subject = "A Business Card order has been submitted by Georgia Highlands College"; $message = " <html> <head> <title>A Business Card order has been submitted by Georgia Highlands College</title> </head> <body> <h2>A Business Card order has been submitted by Georgia Highlands College</h2> <table border='1'> <tr> <th width='200'>Employee Name</th> <th width='200'>Title</th> <th width='400'>Campus</th> <th width='400'>Contact Info</th> </tr> <tr> <td>"; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: <<EMAIL>>' . "\r\n"; //$headers .= 'Cc: <EMAIL>' . "\r\n"; mail($to,$subject,$message,$headers); ?><file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order Report</h1> <p>Sent to Printer</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? $businessCards = new BusinessCard(); $sql= "select * from Orders, Campus where empCampus=idCampus AND sentToPrinter = '1' AND recdFmPrinter = '1'"; ?> <h2 align='center'>Returned from Printer</h2> <table border="1"> <tr> <td width='200'><h4>Name</h4></td><td width='200'><h4>Title</h4></td><td width='100'><h4>Campus</h4></td><td width='200'><h4>Contact Info</h4></td><td width='150'><h4>Date <br>Requested</h4></td><td width='150'><h4>Date Sent <br> to Printer</h4></td><td width='140'><h4>Returned <br> from Printer</h4></td> </tr> <form action="returned.php" method="post"> <h3 align='center'>Date returned from Printer<input type="date" name="Returned" min="2015-10-20" required=""></h3> <? foreach($businessCards->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { echo "<tr>"; echo "<td>"; echo $row['empName']; echo "</td>"; echo "<td>"; echo $row['empTitle1'] . "<br>"; echo $row['empTitle2']; echo "</td>"; echo "<td>"; echo $row['nameCampus']; echo "</td>"; echo "<td>"; echo $row['empContact1'] . "<br>"; echo $row['empContact2'] . "<br>"; echo $row['empContact3'] . "<br>"; echo $row['empContact4']; echo "</td>"; echo "<td>"; echo $row['submitDate']; echo "</td>"; echo "<td>"; echo $row['dateToPrinter']; echo "</td>"; echo "<td align='center'>"; ?> <input type="checkbox" name="OrderID[]" value="<? echo $row['idOrders'] ?>" /> <? echo "</td>"; echo "</tr>"; } ?> </table> <br> <input type="submit" /> </form> <h3><a href="admin.php">Go to Admin Page</a></h3> <h3><a href="http://highlands.edu">Exit</a></h3> </div> <file_sep><?php header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=open-house.csv'); /* * Get Event Dates ready for ajax jQuery call */ // Filter out post variables for security $selectCampus = htmlentities($_POST['selectCampus'], ENT_QUOTES, 'UTF-8'); $selectDate = htmlentities($_POST['selectDate'], ENT_QUOTES, 'UTF-8'); // Save new asessment to database function ShowEventRequest($selectCampus, $selectDate) { // output headers so that the file is downloaded rather than displayed include 'dbConn.php'; try { // PHP PDO SQL Statement $sql = "SELECT name,phone,email,attendingguest,major,campus,ohdate FROM submissions WHERE campus = :value1 AND ohdate = :value2;"; $stm = $dbhopenhouse->prepare($sql); $stm->bindParam(':value1', $selectCampus); $stm->bindParam(':value2', $selectDate); $stm->execute(); // Fetch the results in a numbered array $getEvents = $stm->fetchALL(PDO::FETCH_NUM); // Generate CSV File // create a file pointer connected to the output stream $output = fopen('php://output', 'w'); $delimiter = ","; // output the column headings fputcsv($output, array('Name', 'Phone', 'Email', 'Guests', 'Major', 'Campus', 'Open House'), $delimiter); // loop over the rows, outputting them foreach ($getEvents as $line) { fputcsv($output, $line, $delimiter); } // Close the file fclose($output); // Close the dbh connection $dbhopenhouse = null; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } } ShowEventRequest($selectCampus, $selectDate); <file_sep><? function send_mail($user_name, $campus, $servername, $reqname) { $to = "<EMAIL>"; $subject = "A Business Card order has been submitted by " . $reqname; $message = " <html> <head> <title>A Business Card order has been submitted by " . $reqname . "</title> </head> <body> <h2>A Business Card order has been submitted by " . $reqname . "</h2> <table border='1'> <tr> <th width='200'>Employee Name</th> <th width='200'>Campus</th> <th width='400'>Link to Submissions</th> </tr> <tr> <td>" . $user_name . "</td> <td>" . $campus . "</td> <td><a href='http://" . $servername . "/businesscards/requests.php'>Click to view</a></td> </tr> </table> </body> </html> "; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: <<EMAIL>>' . "\r\n"; //$headers .= 'Cc: <EMAIL>' . "\r\n"; mail($to,$subject,$message,$headers); } function reject_mail($order_id, $user_name, $comments, $servername, $reqname, $reqemail) { $to = $reqemail; $subject = "Your Business Card order for " . $user_name . " has been rejected" ; $message = " <html> <head> <title>Your Business Card order for " . $user_name . " has been rejected</title> </head> <body> <h2>Your Business Card order for " . $user_name . " has been rejected</h2> <table border='1'> <tr> <th width='200'>Employee Name</th> <th width='400'>Comments</th> <th width='400'>Link to Order</th> </tr> <tr> <td>" . $user_name . "</td> <td>" . $comments . "</td> <td><a href='http://" . $servername . "/businesscards/resubmit.php?idOrders=" . $order_id . "'>Click to view</a></td> </tr> </table> </body> </html> "; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: <<EMAIL>>' . "\r\n"; //$headers .= 'Cc: <EMAIL>' . "\r\n"; mail($to,$subject,$message,$headers); } ?><file_sep><?php class BusinessCard extends Crud { public $idOrders; public $empName; public $empTitle; public $empContact; public $empCampus; public $empFund; public $empDept; public $empProgram; public $empClass; public $empProject; public $submitDate; public $sentToPrinter; public function BusinessCardList($sql) { $i = 0; $this->conn(); $stmt = $this->db->prepare($sql); $stmt->bindParam(':id', $id); $stmt->execute(); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); echo "<table border='1'>"; foreach($rows as $row) { echo "<tr>"; ++$i; foreach($row as $fieldname=>$value) { echo "<td>"; echo $this->$fieldname=$value; echo "</td>"; } echo "</tr>"; } echo "</table>"; return $i; } }// Class ending ?><file_sep><?php $dbuser_ghcinform = 'ghcinform'; $dbpass_ghcinform = '<PASSWORD>'; $dbuser_heart2heart = 'heart2heart'; $dbpass_heart2heart = '<PASSWORD>'; $dbuser_highlander = 'highlander'; $dbpass_highlander = '<PASSWORD>'; $dbuser_writers = 'writers'; $dbpass_writers = '<PASSWORD>'; $dbuser_elearningbits = 'elearningbits'; $dbpass_elearningbits = '<PASSWORD>'; ?> <file_sep><? include "inc/header.inc"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order Form</h1> <p>Request Business Cards Online <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <form action="verify.php" method="post"> <fieldset> <!-- Form Name --> <h2> Business Card Details </h2> <div class="form-group col-md-8"> <!-- Text input--> <h3>Name</h3> <input name="empName" type="text" maxlength="80" placeholder="full name" class="form-control" required=""> <!-- Text input--> <h3>Title</h3> <input name="empTitle1" type="text" maxlength="80" placeholder="Title Line 1 (required)" class="form-control" required=""> <br> <input name="empTitle2" type="text" maxlength="45" placeholder="Title Line 2 (optional)" class="form-control" > <!-- Text input--> <h3>Contact Information<h3> <h4>Please do not include campus address or school web address</h4> <input name="empContact1" type="text" maxlength="45" placeholder="Contact Information Line 1 (required)" class="form-control" required=""> <br> <input name="empContact2" type="text" maxlength="45" placeholder="Contact Information Line 2 (optional)" class="form-control" > <br> <input name="empContact3" type="text" maxlength="45" placeholder="Contact Information Line 3 (optional)" class="form-control" > <br> <input name="empContact4" type="text" maxlength="45" placeholder="Contact Information Line 4 (optional)" class="form-control"> <h3>Campus</h3> <h4>Campus address and school web address will be included on the card</h4> <input type="radio" name="empCampus" value="1" required="" />Floyd<br> <input type="radio" name="empCampus" value="2" required="" />Cartersville<br> <input type="radio" name="empCampus" value="3" required="" />Paulding<br> <input type="radio" name="empCampus" value="4" required="" />Marietta<br> <input type="radio" name="empCampus" value="5" required="" />Douglasville<br> <input type="radio" name="empCampus" value="6" required="" />Heritage Hall<br> <br> <h3>Requestor's Name</h3> <input name="reqName" type="text" maxlength="45" placeholder="Requestor Name" class="form-control" required=""> <!-- Text input--> <h3>Requestor's Email Address</h3> <input name="reqEmail" type="email" maxlength="45" placeholder="Requestor Email" class="form-control" required=""> <h3>Budget Information</h3> <p> <input name="empFund" type="text" minlength="5" maxlength="5" size="10" placeholder="Fund" required=""> <input name="empDept" type="text" minlength="7" maxlength="7" size="10" placeholder="Dept" required=""> <input name="empProgram" type="text" minlength="5" maxlength="5" size="10" placeholder="Program" required=""> <input name="empClass" type="text" minlength="5"maxlength="5" size="10" placeholder="Class" required=""> <input name="empProject" type="text" maxlength="20" size="10" placeholder="Project" required=""> <p> <input type="submit" value="Continue" /> </div> </form> </body> </html> <file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order Report</h1> <p>Business Card Requests</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? $businessCard = new BusinessCard(); $sql= "select * from Orders, Campus where sentToPrinter <> '1' AND rejected <> '1' AND empCampus = idCampus ORDER BY dateReceived DESC" ; $stmt=$businessCard->rawSelect($sql); $row_count = $stmt->rowCount(); if($row_count < 1) { echo "<h3>There are no pending requests<h3>"; } else { ?> <h2 align='center'>Total Requests Pending : <? echo $row_count ?></h2> <button onclick="window.location.href='pending_print_form.php'">Print</button><p> <form action="verifytoprinter.php" method="post"> <div class="table-responsive"> <table class="table table-bordered table-striped"> <tr> <td><h4>Name</h4></td><td><h4>Title</h4></td><td><h4>Campus</h4></td><td><h4>Contact Info</h4></td><td><h4>Requestor Name</h4></td><td><h4>Req. Email</h4></td><td><h4>Accting</h4></td><td><h4>Date Req.</h4></td><td><h4>Submit</h4></td><td></td> </tr> <? foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { echo "<tr>"; echo "<td>"; echo $row['empName']; echo "</td>"; echo "<td>"; echo $row['empTitle1']. "<br>"; echo $row['empTitle2']; echo "</td>"; echo "<td>"; echo $row['nameCampus']; echo "</td>"; echo "<td>"; echo $row['empContact1'] . "<br>"; echo $row['empContact2']. "<br>"; echo $row['empContact3']. "<br>"; echo $row['empContact4']. "<br>"; echo "</td>"; echo "<td>"; echo $row['reqName']; echo "</td>"; echo "<td>"; echo $row['reqEmail']; echo "</td>"; echo "<td>"; echo $row['empFund'] . "<br>"; echo$row['empDept'] . "<br>"; echo$row['empProgram']. "<br>"; echo$row['empClass'] . "<br>"; echo $row['empProject']. "<br>"; echo "</td>"; echo "<td>"; echo $row['dateReceived']; echo "</td>"; ?> <td align='center'> <input type="checkbox" name="OrderID[]" value="<? echo $row['idOrders'] ?>" /> </td> <? echo "<td>"; ?> <a href="reject.php?idOrders=<? echo $row['idOrders'] ?>">Reject</a> <? echo "</td>"; echo "</tr>"; } ?> </table> </div> <p> <p> <input type="submit" /> </form> <? } ?> <h3><a href="admin.php">Go to Admin Page</a></h3> <h3><a href="http://highlands.edu">Exit</a></h3> </div> <file_sep><?php /* * Get Event Request ready for ajax jQuery call */ // Save new asessment to database function ViewOpenHouses() { include 'dbConn.php'; try { // PHP PDO SQL Statement $sql = "SELECT campus, eventdate, idopendates FROM opendates ORDER BY eventdate"; $stm = $dbhopenhouse->prepare($sql); $stm->execute(); // Fetch the results in a numbered array $getOpenHouse = $stm->fetchALL(PDO::FETCH_NUM); $tables = ""; foreach ($getOpenHouse as $row) { if ($row[1] > date("Y-m-d H:i:s")) { $tables .= "<div class='col-md-12'>"; $tables .= '<div class="radio"><label for="'.$row[2].'"><h4>'.$row[0].', <input type="radio" name="rsvp" id="'.$row[2].'" value="' . $row[1] .'">' . date("F j, Y, g:i a", strtotime($row[1])) . '</h4></label></div>'; $tables .= '</div>'; } } echo $tables; // Close the dbh connection $dbh = null; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } } ViewOpenHouses(); <file_sep><? include "inc/header.inc"; include "inc/init.php"; $businessCard = new BusinessCard(); $idOrders = $_GET['idOrders']; $sql= "Select * from Orders, Campus where empCampus=idCampus AND idOrders = $idOrders"; foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { $empName = $row['empName']; $empTitle1 = $row['empTitle1']; $empTitle2 = $row['empTitle2']; $nameCampus = $row['nameCampus']; $empContact1 = $row['empContact1']; $empContact2 = $row['empContact2']; $empContact3 = $row['empContact3']; $empContact4 = $row['empContact4']; $reqName = $row['reqName']; $reqEmail = $row['reqEmail']; $delComments = $row['delComments']; $dateReceived = $row['dateReceived']; $dateToPrinter = $row['dateToPrinter']; $dateFmPrinter = $row['dateFmPrinter']; $rejectDate = $row['dateRejected']; $dateDelivered = $row['dateDelivered']; } ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Online Business Cards</h1> <p>Order Details <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <fieldset> <h2 align="center">Business Card Details</h2><br> <h3><a href="edit.php?idOrders=<? echo $idOrders ?>">Edit Request</a></h3> <div class="table-responsive"> <table class="table table-bordered"><tr><td><h3>Request Date</h3></td><td><h3><? echo $dateReceived ?></h3></td> <td><h3>Reject Date</h3></td><td><h3><? echo $rejectDate ?></h3></td></tr> <tr><td><h3>Date to Printer</h3></td><td><h3><? echo $dateToPrinter ?></h3></td> <td><h3>Completion Date</h3></td><td><h3><? echo $dateFmPrinter ?></h3></td></tr> </table></div> <table class="table table-bordered table-condensed table-striped"> <tr><td><h3>Name</h3></td><td><? echo $empName ?></td></tr> <tr><td><h3>Title</h3></td><td><? echo $empTitle1 ?><br><? echo $empTitle2 ?></td></tr> <tr><td><h3>Contact Information</h3></td><td><? echo $empContact1 ?><br><? echo $empContact2 ?><br><? echo $empContact3 ?><br><? echo $empContact4 ?></td></tr> <tr><td><h3>Campus</h3></td><td><? echo $nameCampus ?></td></tr> <tr><td><h3>Requestor's Name</h3></td><td><? echo $reqName ?></td></tr> <tr><td><h3>Requestor's Email Address</h3></td><td><? echo $reqEmail ?></td></tr> </table> <br> <br> <h3><a href="javascript:history.go(-1)">Return to list</a></h3> </div> </div> </body> </html> <file_sep><?php include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order Report</h1> <p>Rejected Orders</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <? $businessCard = new BusinessCard(); $sql= "select * from Orders, Campus where empCampus=idCampus AND rejected = '1'"; //$sql= "select * from Orders, Campus where empCampus=idCampus AND sentToPrinter = '1'"; $stmt=$businessCard->rawSelect($sql); $row_count = $stmt->rowCount(); if($row_count < 1) { echo "<h3>There are no rejected orders<h3>"; } else { ?> <h2 align='center'>Rejected Orders</h2> <div class="table-responsive"> <table class="table table-condensed table-bordered"> <tr> <td><h4>Name</h4></td><td><h4>Title</h4></td><td><h4>Campus</h4></td><td><h4>Contact Info</h4></td><td><h4>Date <br>Requested</h4></td><td><h4>Rejected <br>Comments</h4></td><td><h4>Date <br>Rejected</h4></td> </tr> <? foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { echo "<tr>"; echo "<td>"; ?><a href="edit.php?idOrders=<? echo $row['idOrders'] ?>"><? echo $row['empName'];?></a><? echo "</td>"; echo "<td>"; echo $row['empTitle1'] . "<br>"; echo $row['empTitle2']; echo "</td>"; echo "<td>"; echo $row['nameCampus']; echo "</td>"; echo "<td>"; echo $row['empContact1'] . "<br>"; echo $row['empContact2'] . "<br>"; echo $row['empContact3'] . "<br>"; echo $row['empContact4']; echo "</td>"; echo "<td>"; echo $row['dateReceived']; echo "</td>"; echo "<td>"; echo $row['rejectComments']; echo "</td>"; echo "<td>"; echo $row['dateRejected']; echo "</td>"; } ?> </table> </div> <br> <? } ?> <h3><a href="admin.php">Go to Admin Page</a></h3> <h3><a href="http://highlands.edu">Exit</a></h3> </div> <file_sep><? include "inc/header.inc"; include "inc/init.php"; $businessCard = new BusinessCard(); $idOrders = $_GET['idOrders']; $sql = "SELECT * FROM Orders WHERE idOrders = '" . $idOrders . "'"; foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) {} ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order Form</h1> <p>Request Business Cards Online <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <form action="edit_request.php" method="get"> <fieldset> <!-- Form Name --> <h2> Business Card Details </h2> <div class="form-group col-md-8"> <!-- Text input--> <h3>Name</h3> <input name="empName" value= "<? echo $row['empName'] ?>" type="text" maxlength="45" placeholder="full name" class="form-control" required=""> <!-- Text input--> <h3>Title</h3> <input name="empTitle1" value= "<? echo $row['empTitle1'] ?>" type="text" maxlength="45" placeholder="Title Line 1 (required)" class="form-control" required=""> <br> <input name="empTitle2" value= "<? echo $row['empTitle2'] ?>"type="text" maxlength="45" placeholder="Title Line 2 (optional)" class="form-control" > <!-- Text input--> <h3>Contact Information</h3> <input name="empContact1" value= "<? echo $row['empContact1'] ?>" type="text" maxlength="45" placeholder="Contact Information Line 1 (required)" class="form-control" required=""> <br> <input name="empContact2" value= "<? echo $row['empContact2'] ?>" type="text" maxlength="45" placeholder="Contact Information Line 2 (optional)" class="form-control" > <br> <input name="empContact3" value= "<? echo $row['empContact3'] ?>" type="text" maxlength="45" placeholder="Contact Information Line 3 (optional)" class="form-control" > <br> <input name="empContact4" value= "<? echo $row['empContact4'] ?>" type="text" maxlength="45" placeholder="Contact Information Line 4 (optional)" class="form-control"> <h3>Requestor's Name</h3> <input name="reqName" value= "<? echo $row['reqName'] ?>" type="text" maxlength="45" placeholder="Requestor Name" class="form-control" required=""> <!-- Text input--> <h3>Requestor's Email Address</h3> <input name="reqEmail" value= "<? echo $row['reqEmail'] ?>" type="text" maxlength="45" placeholder="Requestor Email" class="form-control" required=""> <h3>Budget Information</h3> <p> <input name="empFund" value= "<? echo $row['empFund'] ?>" type="text" minlength="5" maxlength="5" size="10" placeholder="Fund" required=""> <input name="empDept" value= "<? echo $row['empDept'] ?>" type="text" minlength="7" maxlength="7" size="10" placeholder="Dept" required=""> <input name="empProgram" value= "<? echo $row['empProgram'] ?>" type="text" minlength="5" maxlength="5" size="10" placeholder="Program" required=""> <input name="empClass" value= "<? echo $row['empClass'] ?>" type="text" minlength="5"maxlength="5" size="10" placeholder="Class" required=""> <input name="empProject" value= "<? echo $row['empProject'] ?>" type="text" maxlength="20" size="10" placeholder="Project" required=""> <input type="hidden" name="idOrders" value="<? echo $idOrders ?>" /> <p> <input type="submit" value="submit" /> <h3><a href="javascript:history.go(-1)">Return to list</a></h3> </div> </form> </body> </html> <file_sep><? include "inc/init.php"; include "inc/header.inc"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Order System</h1> <p>Administration</p> <br> <br> </p> </div> <div class="messageSaved"></div> <div class="well" style="padding:20px 100px 10px 100px;"> <a href="requests.php"><h2> Pending Orders</h2></a> <a href="rejectedlist.php"><h2> Rejected Orders</h2></a> <a href="senttoprinter.php"><h2> Orders at the Printer</h2></a> <a href="completed.php "><h2>Completed Orders</h2></a> <a href="all.php "><h2>All Orders</h2></a> </div><file_sep><? include "inc/header.inc"; include "inc/init.php"; ?> <div class="container"> <div class="jumbotron"> <img style="float:left; margin-right: 20px;" src="images/logo.png" /> <h1 >Business Card Confirmation</h1> <p>Request Business Cards Online <br> <br> </p> </div> <?php $businessCard= new BusinessCard(); $campus = $_POST['empCampus']; $sql = "SELECT * from Campus where idCampus = $campus"; foreach($businessCard->rawSelect($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { $address = $row['addressCampus']; } //exit(0); $_SESSION['empName']=htmlspecialchars($_POST['empName']); $_SESSION['empTitle1']= htmlspecialchars($_POST['empTitle1']); $_SESSION['empTitle2']= htmlspecialchars($_POST['empTitle2']); $_SESSION['empContact1'] = htmlspecialchars($_POST['empContact1']); $_SESSION['empContact2'] = htmlspecialchars($_POST['empContact2']); $_SESSION['empContact3'] = htmlspecialchars($_POST['empContact3']); $_SESSION['empContact4'] = htmlspecialchars($_POST['empContact4']); $_SESSION['empCampus'] = htmlspecialchars($_POST['empCampus']); $_SESSION['empFund'] = htmlspecialchars($_POST['empFund']); $_SESSION['empDept'] = htmlspecialchars($_POST['empDept']); $_SESSION['empProgram'] = htmlspecialchars($_POST['empProgram']); $_SESSION['empClass'] = htmlspecialchars($_POST['empClass']); $_SESSION['empProject'] = htmlspecialchars($_POST['empProject']); $_SESSION['reqName'] = htmlspecialchars($_POST['reqName']); $_SESSION['reqEmail'] = htmlspecialchars($_POST['reqEmail']); ?> <h2 style="color: yellow; text-align:center">Please proof your information carefully before submitting.</h2> <h2 style="color: yellow; text-align:center">The information you provide will be copied directly to the business card template and no additional proof will be provided.</h2> <h2 style="color: yellow; text-align:center"> For questions, please contact <NAME> at x6784.</h2> <div class="well" style="padding:20px 100px 10px 100px;"> <h3>Name</h3> <h4><? echo $_SESSION['empName']; ?></h4> <p> <h3>Title</h3> <h4><? echo $_SESSION['empTitle1']; ?></h4> <h4><? echo $_SESSION['empTitle2']; ?></h4> <p> <h3>Contact</h3> <h4><? echo $_SESSION['empContact1']; ?></h4> <h4><? echo $_SESSION['empContact2']; ?></h4> <h4><? echo $_SESSION['empContact3']; ?></h4> <h4><? echo $_SESSION['empContact4']; ?></h4> <p> <h3>Campus Address</h3> <h4><? echo$address?></h4> <h4>highlands.edu</h4> <p> <h3>Requestor Name</h3> <h4><? echo $_SESSION['reqName']; ?></h4> <h3>Requestor Email</h3> <h4><? echo $_SESSION['reqEmail']; ?></h4> <h3>Accounting Information</h3> <h4><? echo $_SESSION['empDept'] . " " . $_SESSION['empProgram'] . " " . $_SESSION['empClass'] . " " . $_SESSION['empProject']; ?></h4> <input type="button" onclick="location.href='submitted.php';" value="Submit Business Card Request" /><p><p> <input type="button" onclick="window.history.back();" value="Return to Submission Form" /> </div>
2e905fd1d4ba727af6c8bdc507d58dce521e54df
[ "JavaScript", "PHP" ]
48
JavaScript
marcellushan/businesscards
ceeaecd6f5454aa774f727c6cfd29b16d6a70e89
a59e74d25eedf1606af4ddd5d30be849105fc055
refs/heads/main
<file_sep># Arraystats ArrayStats is a python module which shows brief, quick statistics of an array. This is a very lightweight module. (Needs numpy module as of version 1.0) [See wiki](https://github.com/nimbus2009/Arraystats/wiki) <a href="https://www.hitwebcounter.com" target="_blank"> <img src="https://hitwebcounter.com/counter/counter.php?page=7851457&style=0006&nbdigits=6&type=page&initCount=0" border="0" /></a> <file_sep>import numpy #Numpy module is needed as of version 1 def arrayStats(array): array.sort() length=len(array) mean=numpy.mean(array) median=numpy.median(array) standardDeviation=numpy.std(array) avg=numpy.average(array) print("ArrayStats of the array of integers ",array,"-") print("Mean=",mean) print("Median=",median) print("Standard deviation=",standardDeviation) print("Average=",avg) range=array[length-1]-array[0] print("Range=",range)
9513a61b2a5d69b043e03bbede7fb7df5c4add0b
[ "Markdown", "Python" ]
2
Markdown
usernamenotfound-404/Arraystats
83e8b274c5fe508d938d2f3885257b3acb1d3147
ea90cc1ba46e7741da3301d921eea083655a9904
refs/heads/master
<repo_name>handar/ThreadRacer<file_sep>/pthread_race.c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <time.h> #include <sys/time.h> /** * THESE DEFINE VALUES CANNOT BE CHANGED. * DOING SO WILL CAUSE POINTS TO BE DEDUCTED * FROM YOUR GRADE (15 points) */ /** BEGIN VALUES THAT CANNOT BE CHANGED */ #define MAX_THREADS 16 #define MAX_ITERATIONS 40 /** END VALUES THAT CANNOT BE CHANGED */ /** * use this struct as a parameter for the function * nanosleep. * For exmaple : nanosleep(&ts, NULL); */ struct ThreadArgs { pthread_t tid; int id; //int count; }; struct timespec ts = {0, 12}; int globalValue = 0; /*void* thread_func(void * arg) { struct ThreadArgs* args = (struct ThreadArgs*)arg; int i; for(i =0; i <= args->count;i++) { printf("Thread id: %-4d,Count Value: %-5d\n", args->id, i); } return NULL; }*/ void* adderThread (void * arg) { struct ThreadArgs* args = (struct ThreadArgs*)arg; int i ; nanosleep(&ts, NULL); for (i = 0; i <= MAX_ITERATIONS; i++){ //nanosleep(&ts, NULL); int temp = globalValue; nanosleep(&ts, NULL); temp = temp + 3; globalValue = temp; printf("Current Value written to Global Variables by ADDER thread id: %lu is %d\n", args -> tid, globalValue); } } void* subtractorThread (void * arg) { struct ThreadArgs* args = (struct ThreadArgs*)arg; int i ; nanosleep(&ts, NULL); for (i = 0; i <= MAX_ITERATIONS; i++){ //nanosleep(&ts, NULL); int temp = globalValue; nanosleep(&ts, NULL); temp = temp - 3; globalValue = temp; printf("Current Value written to Global Variables by SUBTRACTOR thread id: %lu is %d\n", args -> tid, globalValue); } } int main(int argc, char const *argv[]) { //declare an array of structs of size MAX_THREADS struct ThreadArgs thread_info[MAX_THREADS]; int i, ret_val; nanosleep(&ts, NULL); //create MAX_THREADS threads for(i=0; i < MAX_THREADS;i++) { nanosleep(&ts, NULL); //save thread-s info in next struct thread_info[i].id = i+1; //thread_info[i].count = 10-i; //ret_val = pthread_create(&thread_info[i].tid, NULL, thread_func, (void *)&thread_info[i]); if(ret_val < 0) { perror("Error creating thread.."); return -2; } //even numbered iterations if (i % 2 == 0){ ret_val = pthread_create(&thread_info[i].tid, NULL, adderThread, (void *)&thread_info[i]); //nanosleep(&ts, NULL); //adderThread(ret_val); } //odd numbered iterations else { ret_val = pthread_create(&thread_info[i].tid, NULL, subtractorThread, (void *)&thread_info[i]); //nanosleep(&ts, NULL); //subtractorThread(ret_val); } } for(i = 0; i < MAX_THREADS; i++) { ret_val = pthread_join(thread_info[i].tid, NULL); if(ret_val) { perror("Error joining thread: "); return -3; } } //printf("Main Has Joined All Threads\n"); printf("Final Value of Shared Var: %d\n", globalValue); return 0; } <file_sep>/README.md # Thread Racing ## Build Instructions make ## Run Instructions ./threadracer ## Explain why your program produces the wrong output The output is supposed to be far away from 0, because of nanosleep(). The adderThread is supposed to add 3 to the globalValue and the subtractorThread is supposed to take away 3 from the globalValue. So normally, that would just make the globalValue 0. But, placing nanosleep() strategically in specific places in the code affects the globalValue and throws the number of threads created out of sync so it does not end up equaling 0 at the end.
d4f104b94c4c8210ceecbb134ba16c4850f812a2
[ "Markdown", "C" ]
2
C
handar/ThreadRacer
91c1bc60a9766c0d1d04ec3045c5313af2a91629
148c978683ea681ad94cb303d0b70d67ec49e9c6
refs/heads/master
<repo_name>Map-Data/regiontileserver<file_sep>/reimport.sh #!/usr/bin/env bash for server in `cat server_list`; do ./import_data.sh ${server} done <file_sep>/install_deps.sh #! /bin/bash set -e . settings.sh if hash apt-get 2>/dev/null; then echo "Using apt-get to install" sudo apt-get install git python-virtualenv osm2pgsql python-pip python-dev gcc postgis unzip elif hash dfn 2>/dev/null; then echo "Using DFN to install" sudo dnf install osm2pgsql python2-virtualenv git python2-pip python2-devel postgis gcc unzip else echo "Unknown package manager" exit 1 fi sudo adduser tileserver --home ${homedir} --system sudo mkdir ${workdir} cd ${workdir} # todo: add postgress account # todo: add systemd unit file #todo: make port configurable, the first tileserver will use this port plus 1 echo "declare -A PORTS">port_mapping echo "PORTS[dummy]=8000">>port_mapping touch server_list chown -hR tileserver ~tileserver # initial nginx frontend confi + certs??? #### maybe via subdomain from map-data.de <file_sep>/import_data.sh #! /usr/bin/env bash set -e tile=$1 source settings.sh tileserverVersion="v2.2.0" vectorDatasourceVersion="v1.8.0" cd ${workdir} wget -N https://map-data.de/extract/${tile}.sql.gz if [ $? -eq 0 ]; then echo "using sql dump" gunzip "${tile}.sql.gz" sqldump=1 else md5f1="" if [[ -f ${tile}.pbf.md5 ]]; then md5f1=$(cat "${tile}.pbf.md5") fi wget -N https://map-data.de/extract/${tile}.pbf || exit 1 md5f2=$(md5sum "${tile}.pbf" | cut -d' ' -f1) echo ${md5f2} > ${tile}.pbf.md5 if [[ "$md5f2" == "$md5f1" ]]; then echo "No new data" exit 0 fi echo "CREATE DATABASE \"${database}\" OWNER ${database_user} TABLESPACE ${tablespace};"| psql -Xq -p ${database_port} -U ${database_user} -h ${dbhost} echo "CREATE EXTENSION postgis; CREATE EXTENSION hstore;"| psql -Xq -p ${database_port} -U ${database_user} -h ${dbhost} -d ${database} sqldump=0 fi if [[ ! -d vector-datasource-${vectorDatasourceVersion} ]]; then git clone https://github.com/mapzen/vector-datasource.git vector-datasource-${vectorDatasourceVersion} vector_cloned=1 fi if [[ ! -f port_mapping ]]; then echo "PORT_DUMMY=6743" > port_mapping fi if [[ ! -d "tileserver-${tileserverVersion}" ]]; then git clone https://github.com/tilezen/tileserver.git tileserver-${tileserverVersion} tileserver_cloned=1 fi if [[ ! -f .pyenv-${vectorDatasourceVersion}/bin/activate ]]; then virtualenv .pyenv-${vectorDatasourceVersion} --python python2.7 new_venv=1 fi source .pyenv-${vectorDatasourceVersion}/bin/activate cd tileserver-${tileserverVersion} git checkout ${tileserverVersion} if [[ ! -z ${new_venv+x} ]]; then pip install -U -r requirements.txt python setup.py develop fi cd ../vector-datasource-${vectorDatasourceVersion} git checkout ${vectorDatasourceVersion} if [[ ! -z ${new_venv+x} ]]; then pip install -r requirements.txt python setup.py develop fi # TODO: bei fehlern am anfang macht er das hier gerne nicht if [[ ! -z ${new_venv+x} ]]; then cd data python bootstrap.py make -f Makefile-import-data cd .. fi if [[ $sqldump -eq 0 ]]; then osm2pgsql --slim --hstore-all -C 3000 -S osm2pgsql.style -d ${database} -P ${database_port} -U ${database_user} -H ${dbhost} --number-processes 4 --flat-nodes ../flat-nodes-file ../${tile}.pbf || exit 1 rm ../flat-nodes-file # TODO: for dynamic updating this file is needet rm ../${tile}.pbf cd data ./import-shapefiles.sh | psql -Xq -d ${database} -p ${database_port} -U ${database_user} -h ${dbhost} ./perform-sql-updates.sh -d ${database} -p ${database_port} -h ${dbhost} -U ${database_user} cd ../.. echo "DROP DATABASE \"${database_orig}\"" | psql -Xq -p ${database_port} -U ${database_user} -h ${dbhost} echo "ALTER DATABASE \"${database}\" RENAME TO \"${database_orig}\"" | psql -Xq -p ${database_port} -U ${database_user} -h ${dbhost} else cd .. psql -p ${database_port} -U ${database_user} -h ${dbhost} -f ${tile}.sql rm "${tile}.sql" fi sed "s/dbnames: \[osm\]/dbnames: \[${database_orig}\]/" tileserver-${tileserverVersion}/config.yaml.sample > tileserver-${tileserverVersion}/config.${tile}.yaml sed -i "s/password:/password: ${PGPASSWORD}/" tileserver-${tileserverVersion}/config.${tile}.yaml sed -i "s/vector-datasource/vector-datasource-${vectorDatasourceVersion}/" tileserver-${tileserverVersion}/config.${tile}.yaml # The following two lines als effect the unused debugserver settings sed -i "s/host: localhost/host: ${dbhost}/" tileserver-${tileserverVersion}/config.${tile}.yaml sed -i "s/port: 5432/port: ${database_port}/" tileserver-${tileserverVersion}/config.${tile}.yaml sed -i "s/user: osm/user: ${database_user}/" tileserver-${tileserverVersion}/config.${tile}.yaml if ! grep "${tile}" server_list; then echo ${tile} >> server_list mv server_list server_list.1 cat server_list.1 | sort | uniq > server_list last_port=$(cut port_mapping -d '=' -s -f 2 | sort | tail -n 1) new_port=$((last_port+1)) echo "PORTS[${tile}]=${new_port}" >> port_mapping systemctl enable tileserver-gunicorn@${tile} systemctl start tileserver-gunicorn@${tile} else systemctl restart tileserver-gunicorn@${tile} fi if [[ ! -f version_mapping ]]; then echo "declare -A VERSIONS" > version_mapping echo "declare -A VERSIONS_TILESERVER" >> version_mapping fi mv version_mapping version_mapping.tmp cat version_mapping.tmp | grep -v "${tile}" > version_mapping echo "VERSIONS[${tile}]=${vectorDatasourceVersion}" >> version_mapping echo "VERSIONS_TILESERVER[${tile}]=${tileserverVersion}" >> version_mapping echo "DONE ${tile}" <file_sep>/start_gunicorn.sh #! /bin/bash DIR=`dirname "$(readlink -f "$0")"` . $DIR/settings.sh tile=$1 . ${workdir}/port_mapping PORT=${PORTS[${tile}]} . ${workdir}/version_mapping VERSION=${VERSIONS[${tile}]} VERSION_TILESERVER=${VERSIONS_TILESERVER[${tile}]} pyenv="${workdir}/.pyenv-${VERSION}" source ${pyenv}/bin/activate cd tileserver-${VERSION_TILESERVER} ${pyenv}/bin/gunicorn -w 2 -t 120 -b 0.0.0.0:${PORT} "tileserver:wsgi_server('config.${tile}.yaml')" <file_sep>/README.md # Regional Tileserver This repo contains install and import scripts to host a regional part of a vector tile server backed by Openstreetmap data, currently used by the StreetComplete App. # Warning currently only tested on a Debian Testing (Debian Buster) Server # Setup copy settings.sh.example to settings.sh and change if needed install dependencies, database user and some needed files: ./install_deps.sh Copy and modify systemd file: sudo cp tileserver-gunicorn@.service /etc/systemd/system/ sudo vim /etc/systemd/system/tileserver-gunicorn@.service sudo systemctl daemon-reload # Configure add a User to the Database: sudo -u postgres psql create user osm with encrypted password '<PASSWORD>'; CREATE DATABASE osm OWNER osm; (The osm database is used to connect to do rename the database for production, ) add the Postgress password to the settings.sh Tuning the Database configs: TODO (incrase memory in various places) # Import Database the default port used will be 8001. (see ../workdir/port_mapping) * Select a region the tileserver should serve (Ask @Akasch for infos) * start the import inside of a screen/temux session because it wil propably take a loong time * start import: ./import_data.sh <tile> for example: sudo ./import_data.sh 6_30_22 This will download the data and import it. This will need up to 3 days on a HDD if the region .pbf file is ~1,5 GB. After the import a configuration is written and the systemd unit is started and enabled. It will listen on the next port not defined in port_mapping. There will be some SQL errors in the middel about columns not found, this is normal and expected (migrations which are not needed). To integrate it into the global tileserver expose the port to the internet (best with nginx or apache as reverse proxy in front of it) and ping @Akasch. # Update Data Currently the used data is sliced at most once per week. To reimport the data just rerun the import command. This will import the data into a second Database (defaults to <tile>_b) and switch them at the end so the old data gets served until the import finishes. The reimport.sh script will import all installed regions. so you can add this script to the (root) crontab **Warning:** This will need the database size (of the biggest region) a second time during import!
b558f276f84bdc34168f125a130b059ea106d4a7
[ "Markdown", "Shell" ]
5
Shell
Map-Data/regiontileserver
b486a2feeb297bfa77620d5613ad7ee8c09db462
d1d71d5858dea736374f171e04343eb761206262
refs/heads/master
<repo_name>JakobHavtorn/nn<file_sep>/examples/mnist_rnn.py import os from context import nn, optim, utils, evaluators from utils.constants import SAVE_DIR from utils.utils import get_loaders class RNNClassifier(nn.Module): """Feedforward neural network classifier. Parameters ---------- in_features : int The number of input features. out_classes : int The number of output classes. hidden_dims : list List of the dimensions of the hidden layers. Also defines the depth of the network. activation : nn.Module The activation function to use. batchnorm : bool Whether or not to use batch normalization layers. dropout : bool or float Whether or not to include dropout and the dropout probability to use. """ def __init__(self, input_size, out_classes, hidden_dims=[256], activation=nn.ReLU, batchnorm=False, dropout=False): super(RNNClassifier, self).__init__() self.input_size = input_size self.add_module("RNN_0", nn.RNN(input_size, hidden_dims[0], bias=True)) # self.add_module("RNN_0", nn.LSTM(input_size, hidden_dims[0], bias=True)) # self.add_module("Linear0", nn.Linear(hidden_dims[0], hidden_dims[1], bias=True)) self.add_module("Linear_0", nn.Linear(hidden_dims[0], out_classes, bias=True)) self.add_module("Softmax_0", nn.Softmax()) # dims = [in_features, *hidden_dims, out_classes] # for i in range(len(dims) - 1): # is_output_layer = i == len(dims) - 2 # self.add_module("Linear" + str(i), nn.Linear(dims[i], dims[i+1])) # if batchnorm and not is_output_layer: # self.add_module("BatchNorm" + str(i), nn.BatchNorm1D(dims[i+1])) # if dropout and not is_output_layer: # self.add_module("Dropout" + str(i), nn.Dropout(p=dropout)) # if not is_output_layer: # self.add_module("Activation" + str(i), activation()) # else: # self.add_module("Activation" + str(i), nn.Softmax()) def forward(self, x): # Feed each row as a vector to RNN # assert x.shape[0] == 1, "Only supports batches of 1 example" x = x.reshape(self.input_size, x.shape[0], -1) x = self.RNN_0.forward(x)[-1] # import IPython # IPython.embed() x = self.Linear_0.forward(x) x = self.Softmax_0.forward(x) return x def backward(self, delta): for module in reversed(self._modules.values()): delta = module.backward(delta) if __name__ == '__main__': # Dataset dataset_name = 'MNIST' batch_size = 250 max_epochs = 20 max_epochs_no_improvement = 10 train_loader, val_loader = get_loaders(dataset_name, batch_size) # Checkpoint dir checkpoint_dir = os.path.join(SAVE_DIR, dataset_name) if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) # Model classifier = RNNClassifier(28, 10, activation=nn.ReLU, batchnorm=True, dropout=False) classifier.summarize() # Optimizer optimizer = optim.Adam(classifier.parameters, lr=0.001, l1_weight_decay=0, l2_weight_decay=0) # optimizer = optim.SGD(classifier.parameters, lr=0.001, momentum=0.9, nesterov=True, l1_weight_decay=0, l2_weight_decay=0) # Loss loss = nn.CrossEntropyLoss() # Learning rate schedule lr_scheduler = None # optim.CosineAnnealingLR(optimizer, T_max=5, decay_eta_max_half_time=1) # Evaluators train_evaluator = evaluators.MulticlassEvaluator(n_classes=10) val_evaluator = evaluators.MulticlassEvaluator(n_classes=10) # Trainer trainer = utils.trainers.ClassificationTrainer(classifier, optimizer, loss, train_loader, val_loader, train_evaluator, val_evaluator, lr_scheduler=lr_scheduler, max_epochs=max_epochs, max_epochs_no_improvement=max_epochs_no_improvement, checkpoint_dir=checkpoint_dir) trainer.train() <file_sep>/nn/module.py from collections import OrderedDict import IPython import numpy as np from .parameter import Parameter class Module(): """Base class for all neural network modules such as activations and transformations. """ def __init__(self, *args, **kwargs): self._modules = OrderedDict() self._parameters = OrderedDict() self._buffers = OrderedDict() self.training = True def reset_cache(self): """Reset the cache of the module """ self.cache = dict() def train(self, mode=True): """Recursively sets the traiing mode to `mode` for all submodules. """ self.training = mode for module in self.children(): module.train(mode) def eval(self): """Recursively sets the training mode to evaluation for all submodules. """ self.train(mode=False) def summarize(self): """Print a model summary including all submodules. """ name_col_width = max(len(n) for n, m in self.named_modules()) + 2 module_col_width = max(len(str(m)) for n, m in self.named_modules()) for n, m in self.named_modules(): if m is not self: print(n.ljust(name_col_width) + str(m).ljust(module_col_width)) n = 0 for p in self.parameters(): n += np.prod(p.shape) print("Total number of parameters: " + str(n)) def add_module(self, name, module): """Adds a child module to the current module. """ if not isinstance(module, Module) and module is not None: raise TypeError("{} is not a Module subclass".format( type(module))) elif hasattr(self, name) and name not in self._modules: raise KeyError("attribute '{}' already exists".format(name)) elif '.' in name: raise KeyError("module name can't contain \".\"") elif name == '': raise KeyError("module name can't be empty string \"\"") self._modules[name] = module def named_modules(self, memo=None, prefix=''): """Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself. """ if memo is None: memo = set() if self not in memo: memo.add(self) yield prefix, self for name, module in self._modules.items(): if module is None: continue submodule_prefix = prefix + ('.' if prefix else '') + name for m in module.named_modules(memo, submodule_prefix): yield m def modules(self): for _, module in self.named_modules(): yield module def named_children(self): """Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself. """ memo = set() for name, module in self._modules.items(): if module is not None and module not in memo: memo.add(module) yield name, module def children(self): """Returns an iterator over immediate children modules. """ for _, module in self.named_children(): yield module def named_parameters(self, memo=None, prefix=''): """Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself. """ if memo is None: memo = set() for name, p in self._parameters.items(): if p is not None and p not in memo: memo.add(p) yield prefix + ('.' if prefix else '') + name, p for mname, module in self.named_children(): submodule_prefix = prefix + ('.' if prefix else '') + mname for name, p in module.named_parameters(memo, submodule_prefix): yield name, p def parameters(self): """Returns an iterator over module parameters. """ for _, param in self.named_parameters(): yield param def _all_buffers(self, memo=None): """Returns an iterator over module buffers. """ if memo is None: memo = set() for _, b in self._buffers.items(): if b is not None and b not in memo: memo.add(b) yield b for module in self.children(): for b in module._all_buffers(memo): yield b def register_buffer(self, name, tensor): """Adds a persistent buffer to the module. """ if hasattr(self, name) and name not in self._buffers: raise KeyError("attribute '{}' already exists".format(name)) elif '.' in name: raise KeyError("buffer name can't contain \".\"") elif name == '': raise KeyError("buffer name can't be empty string \"\"") elif tensor is not None and not isinstance(tensor, np.ndarray): raise TypeError("cannot assign '{}' object to buffer '{}' " "(np.ndarray or None required)" .format(type(tensor), name)) else: self._buffers[name] = tensor def register_parameter(self, name, param): """Adds a parameter to the module. """ if '_parameters' not in self.__dict__: raise AttributeError("cannot assign parameter before Module.__init__() call") elif hasattr(self, name) and name not in self._parameters: raise KeyError("attribute '{}' already exists".format(name)) elif '.' in name: raise KeyError("parameter name can't contain \".\"") elif name == '': raise KeyError("parameter name can't be empty string \"\"") if param is None: self._parameters[name] = None elif not isinstance(param, Parameter): raise TypeError("cannot assign '{}' object to parameter '{}' " "(torch.nn.Parameter or None required)" .format(type(param), name)) else: self._parameters[name] = param def __getattr__(self, name): """Returns model parameter attributes by finding them in the _parameters dictionary attribute """ if '_parameters' in self.__dict__: _parameters = self.__dict__['_parameters'] if name in _parameters: return _parameters[name] if '_buffers' in self.__dict__: _buffers = self.__dict__['_buffers'] if name in _buffers: return _buffers[name] if '_modules' in self.__dict__: modules = self.__dict__['_modules'] if name in modules: return modules[name] raise AttributeError("'{}' object has no attribute '{}'".format( type(self).__name__, name)) def __setattr__(self, name, value): """Sets model parameter attributes by setting them in the _parameters dictionary attribute """ def remove_from(*dicts): for d in dicts: if name in d: del d[name] # Parameters parameters = self.__dict__.get('_parameters') if isinstance(value, Parameter): if parameters is None: raise AttributeError("cannot assign parameters before Module.__init__() call") remove_from(self.__dict__, self._buffers, self._modules) self.register_parameter(name, value) elif parameters is not None and name in parameters: if value is not None: raise TypeError("cannot assign '{}' as parameter '{}' " "(torch.nn.Parameter or None expected)" .format(type(value), name)) self.register_parameter(name, value) else: # Modules modules = self.__dict__.get('_modules') if isinstance(value, Module): if modules is None: raise AttributeError("cannot assign module before Module.__init__() call") remove_from(self.__dict__, self._parameters, self._buffers) modules[name] = value elif modules is not None and name in modules: if value is not None: raise TypeError("cannot assign '{}' as child module '{}' " "(nn.Module or None expected)" .format(type(value), name)) modules[name] = value else: # Buffers buffers = self.__dict__.get('_buffers') if buffers is not None and name in buffers: if value is not None and not isinstance(value, np.ndarray): raise TypeError("cannot assign '{}' as buffer '{}' " "(np.ndarray or None expected)" .format(type(value), name)) buffers[name] = value else: object.__setattr__(self, name, value) def __delattr__(self, name): """Deletes a model parameter attributes by deleting it in the _parameters dictionary attribute """ if name in self._parameters: del self._parameters[name] elif name in self._buffers: del self._buffers[name] elif name in self._modules: del self._modules[name] else: object.__delattr__(self, name) def reset_parameters(self): raise NotImplementedError() def forward(self, input): raise NotImplementedError() def backward(self, delta_in): raise NotImplementedError() <file_sep>/nn/pooling.py import IPython import numpy as np from .im2col import col2im_indices, im2col_indices from .module import Module try: from .im2col_cython import col2im_cython, im2col_cython from .im2col_cython import col2im_6d_cython except ImportError: print("Failed to import im2col and col2im Cython versions.") print('Run the following from the nn directory and try again:') print('python setup.py build_ext --inplace') class _Pooling(Module): def __init__(self, kernel_size, stride, padding): super(_Pooling, self).__init__() # assert type(kernel_size) is tuple, "Please specifiy kernel size in each dimension as a tuple." self.kernel_size = kernel_size self.stride = stride if stride is not None else kernel_size[0] self.padding = padding if stride is not None: self.stride = stride elif kernel_size[0] == kernel_size[1]: self.stride = kernel_size[0] else: raise ValueError("Stride can only default to kernel size if kernel is square. Had `kernel_size={}".format(kernel_size)) def forward(self, X): # Shape N, C, H, W = X.shape h_out = (H - self.kernel_size[0]) / self.stride + 1 w_out = (W - self.kernel_size[1]) / self.stride + 1 if not w_out.is_integer() or not h_out.is_integer(): raise Exception('Invalid output dimension!') h_out, w_out = int(h_out), int(w_out) # Reshape X_reshaped = X.reshape(N * C, 1, H, W) X_col = im2col_cython(X_reshaped, self.kernel_size[0], self.kernel_size[1], padding=self.padding, stride=self.stride) # X_col = im2col_indices(X_reshaped, self.kernel_size[0], self.kernel_size[1], padding=self.padding, stride=self.stride) # Pool out = self._pool(X_col) # Reshape out = out.reshape(h_out, w_out, N, C) out = out.transpose(2, 3, 0, 1) # Cache self.X_shape = X.shape self.X_col = X_col return out def backward(self, delta): # Shapes N, C, W, H = self.X_shape # Backwards pool delta_col = delta.transpose(2, 3, 0, 1).ravel() dX_col = np.zeros_like(self.X_col) dX_col = self._dpool(dX_col, delta_col) # Reshape dX = col2im_cython(dX_col, N * C, 1, H, W, self.kernel_size[0], self.kernel_size[1], padding=self.padding, stride=self.stride) # dX = col2im_indices(dX_col, (N * C, 1, H, W), self.kernel_size[0], self.kernel_size[1], padding=self.padding, stride=self.stride) dX = dX.reshape(self.X_shape) return dX class MaxPool2D(_Pooling): """Pooling module which performs the two-dimensional max pooling operation. The dimensions are as for the two-dimensional convolution. Parameters ---------- in_channels : tuple The number of input channels out_channels : tuple The number of kernels, or feature maps, to learn kernel_size : tuple The dimensions of the kernel stride : int The pooling stride padding : int The zero padding to be applied to the input bias : bool Whether or not to use bias """ def __init__(self, kernel_size, stride=None, padding=0): super(MaxPool2D, self).__init__(kernel_size, stride=stride, padding=padding) def __str__(self): return "MaxPool2D(kernel=({:d},{:d}), stride={:d}, padding={:d})".format(self.kernel_size[0], self.kernel_size[1], self.stride, self.padding) def _pool(self, X_col): self.max_idx = np.argmax(X_col, axis=0) out = X_col[self.max_idx, range(self.max_idx.size)] return out def _dpool(self, dX_col, delta_col): # dX_col[self.max_idx, range(delta_col.size)] = delta_col dX_col[self.max_idx, np.arange(dX_col.shape[1])] = delta_col return dX_col class AvgPool2D(_Pooling): """Pooling module which performs the two-dimensional average pooling operation. The dimensions are as for the two-dimensional convolution. Parameters ---------- in_channels : tuple The number of input channels out_channels : tuple The number of kernels, or feature maps, to learn kernel_size : tuple The dimensions of the kernel stride : int The pooling stride padding : int The zero padding to be applied to the input bias : bool Whether or not to use bias """ def __init__(self, kernel_size, stride=None, padding=0): super(AvgPool2D, self).__init__() def __str__(self): return "AvgPool2D(kernel=({:d},{:d}), stride={:d}, padding={:d})".format(self.kernel_size[0], self.kernel_size[1], self.stride, self.padding) def _pool(self, X_col): out = np.mean(X_col, axis=0) return out def _dpool(self, dX_col, delta_col): dX_col[:, range(delta_col.size)] = 1. / dX_col.shape[0] * delta_col return dX_col <file_sep>/setup.py from setuptools import setup, find_packages from setuptools.extension import Extension from Cython.Build import cythonize # NOTE THIS SETUP FILE DOES NOT WORK YET extensions = [ Extension( name='im2col_cython', sources=['nn/im2col_cython.pyx'], include_dirs=['nn/'], language='c', ), ] setup( name='nn', version='1.0.0', python_requires='>=3.8.0', packages=find_packages(), requires=['numpy', 'matplotlib'], setup_requires=['cython'], ext_modules=cythonize(extensions), ) <file_sep>/nn/linear.py import IPython import numpy as np from .module import Module from .parameter import Parameter class Linear(Module): """Linear module which performs an affine transformation. The forward transformation is Y = XW' + b with the following dimensions X: (N, *, I) W: (O, I) b: (O) Y: (N, *, O) where * means any number of additional dimensions. Parameters ---------- in_features : int The number of input features (I) out_features : int The number of output features (O) bias : bool, optional Whether or not to include a bias (the default is True) """ def __init__(self, in_features, out_features, bias=True): super().__init__() self.in_features = in_features self.out_features = out_features self.W = Parameter(np.zeros([out_features, in_features])) if bias: self.b = Parameter(np.zeros(out_features)) else: self.b = None self.cache = dict(x=None) self.reset_parameters() def __str__(self): return "Linear({:d}, {:d}, bias={})".format(self.in_features, self.out_features, self.b is not None) def reset_parameters(self): stdv = 1.0 / np.sqrt(self.in_features) self.W.data = np.random.uniform(-stdv, stdv, self.W.shape) if self.b is not None: self.b.data = np.random.uniform(-stdv, stdv, self.b.shape) def forward(self, x): z = np.dot(x, self.W.data.T) if self.b is not None: z += self.b.data self.cache = dict(x=x) return z def backward(self, delta): x = self.cache['x'] self.W.grad += np.dot(delta.T, x) dzdx = np.dot(delta, self.W.data) if self.b is not None: self.b.grad += delta.sum(axis=0) return dzdx class BiLinear(Module): """Bilinear module which performs a bilinear transformation. The transformation is y = x_1 * W * x_2 + b with the following dimensions x_1: (N, *, I_1) x_2: (N, *, I_2) W: (O, I_1, I_2) b: (O) y: (N, O) Parameters ---------- in_features_1 : int The number of first input features (I_1) in_features_2 : int The number of second input features (I_2) out_features : int The number of output features (O) bias : bool, optional Whether or not to include a bias (the default is True) """ def __init__(self, in_features_1, in_features_2, out_features, bias=True): super(BiLinear, self).__init__() self.in_features_1 = in_features_1 self.in_features_2 = in_features_2 self.out_features = out_features self.W = Parameter(np.zeros([out_features, in_features_1, in_features_2])) if bias: self.b = Parameter(np.zeros(out_features)) else: self.b = None self.cache = dict(x1=None, x2=None) self.reset_parameters() def __str__(self): return f'BiLinear(in_features_1={self.in_features_1:d}, in_features_2={self.in_features_2:d},' \ f'out_features={self.out_features:d} bias={self.b is not None})' def reset_parameters(self): stdv = 1.0 / np.sqrt(self.in_features_1 + self.in_features_2) self.W.data = np.random.uniform(-stdv, stdv, self.W.shape) if self.b is not None: self.b.data = np.random.uniform(-stdv, stdv, self.b.shape) def forward(self, x1, x2=None): x2 = x1 if x2 is None else x2 self.x1 = x1 self.x2 = x2 dzdx1 = np.einsum('oij,bj->boi', self.W.data, x2) z = np.einsum('bi,boi->bo', x1, dzdx1) if self.b is not None: z += self.b.data self.cache = dict(dzdx1=dzdx1, x1=x1, x2=None) return z def backward(self, delta): x1, x2, dzdx1 = self.cache['x1'], self.cache['x2'], self.cache['dzdx1'] if x2 is None: x2 = x1 print('Debuggin Bilinear') IPython.embed() self.W.grad += np.einsum('bi,bj->ij', x1, x2) if self.b is not None: self.b.grad += delta.sum(axis=0) if x2 is None: return dzdx1.sum(axis=0) dzdx2 = np.einsum('oij,bj->oi', self.W.data, x2) return dzdx1, dzdx2 # y = x_1 W x_2 + b\\ # \frac{dy}{dx_1} = Wx_2\\ # \frac{dy}{dx_2} = x_1 W <file_sep>/nn/parameter.py import numpy as np class Parameter(object): def __init__(self, data): self.data = data self.grad = np.zeros_like(data) @property def shape(self): return self.data.shape def copy(self): p = Parameter(self.data.copy()) p.grad = self.grad.copy() return p def __repr__(self): s = "Parameter containing:\n" s += self.data.__repr__() s += "\n" + '(' + ', '.join([str(s) for s in self.data.shape]) + ')' if self.grad is not None: s += "\n\nand gradient\n\n" s += self.grad.__repr__() s += "\n" + '(' + ', '.join([str(s) for s in self.data.shape]) + ')' s += "\n" return s @staticmethod def get_data_array(other): if isinstance(other, Parameter): return other.data elif isinstance(other, (np.ndarray, float, int)): return other raise TypeError(f'Unknown type of other {type(other)}') def __getitem__(self, *args, **kwargs): return np.ndarray.__getitem__(self.data, *args, **kwargs) def __setitem__(self, *args, **kwargs): return np.ndarray.__setitem__(self.data, *args, **kwargs) # def __add__(self, other): # data_array = self.get_data_array(other) # return np.add(self.data, data_array) # def __sub__(self, other): # data_array = self.get_data_array(other) # return np.subtract(self.data, data_array) # def __mul__(self, other): # data_array = self.get_data_array(other) # return np.multiply(self.data, data_array) # def __truediv__(self, other): # data_array = self.get_data_array(other) # return np.divide(self.data, data_array) # def __pow__(self, other): # data_array = self.get_data_array(other) # return np.power(self.data, data_array) # def __radd__(self, other): # data_array = self.get_data_array(other) # return self.__add__(data_array) # def __rsub__(self, other): # data_array = self.get_data_array(other) # return self.__sub__(data_array) # def __rmul__(self, other): # data_array = self.get_data_array(other) # return self.__mul__(data_array) # def __rdiv__(self, other): # data_array = self.get_data_array(other) # return np.divide(data_array, self.data) # def __rpow__(self, other): # data_array = self.get_data_array(other) # return np.power(data_array, self.data) # def __iadd__(self, other): # data_array = self.get_data_array(other) # return np.add(self.data, data_array, out=self.data) # def __isub__(self, other): # data_array = self.get_data_array(other) # return np.subtract(self.data, data_array, out=self.data) # def __imul__(self, other): # data_array = self.get_data_array(other) # return np.multiply(self.data, data_array, out=self.data) # def __idiv__(self, other): # data_array = self.get_data_array(other) # return np.divide(self.data, data_array, out=self.data) # def __ipow__(self, other): # data_array = self.get_data_array(other) # return np.power(self.data, data_array, out=self.data) """ Overview of Magic Methods Binary Operators Operator Method Implemented + __add__(self, other) [X] - __sub__(self, other) [X] * __mul__(self, other) [X] // __floordiv__(self, other) [ ] / __truediv__(self, other) [X] % __mod__(self, other) [ ] ** __pow__(self, other[, modulo]) [X] << __lshift__(self, other) [ ] >> __rshift__(self, other) [ ] & __and__(self, other) [ ] ^ __xor__(self, other) [ ] | __or__(self, other [ ] Extended Assignments Operator Method Implemented += __iadd__(self, other) [X] -= __isub__(self, other) [X] *= __imul__(self, other) [X] /= __idiv__(self, other) [X] //= __ifloordiv__(self, other) [ ] %= __imod__(self, other) [ ] **= __ipow__(self, other[, modulo]) [X] <<= __ilshift__(self, other) [ ] >>= __irshift__(self, other) [ ] &= __iand__(self, other) [ ] ^= __ixor__(self, other) [ ] |= __ior__(self, other) [ ] Unary Operators Operator Method Implemented - __neg__(self) [ ] + __pos__(self) [ ] abs() __abs__(self) [ ] ~ __invert__(self) [ ] complex() __complex__(self) [ ] int() __int__(self) [ ] long() __long__(self) [ ] float() __float__(self) [ ] oct() __oct__(self) [ ] hex() __hex__(self [ ] Comparison Operators Operator Method Implemented < __lt__(self, other) [ ] <= __le__(self, other) [ ] == __eq__(self, other) [ ] != __ne__(self, other) [ ] >= __ge__(self, other) [ ] > __gt__(self, other) [ ] """ class LazyArray(np.ndarray): def __new__(cls, input_array): # Input array is an already formed ndarray instance # We first cast to be our class type obj = input_array # Finally, we must return the newly created object: return obj def __add__(self, data): return self.data + data def __sub__(self, other): raise NotImplementedError() def __mul__(self, other): raise NotImplementedError() def __div__(self, other): raise NotImplementedError() def __pow__(self, other): raise NotImplementedError() def __radd__(self, data): raise NotImplementedError() def __rsub__(self, data): raise NotImplementedError() def __rmul__(self, data): raise NotImplementedError() def __rdiv__(self, data): raise NotImplementedError() def __rpow__(self, data): raise NotImplementedError() def __iadd__(self, data): raise NotImplementedError() def __isub__(self, data): raise NotImplementedError() def __imul__(self, data): raise NotImplementedError() def __idiv__(self, data): raise NotImplementedError() def __ipow__(self, data): raise NotImplementedError()<file_sep>/optim/optimizer.py import numpy as np class Optimizer(object): """Base class for all optimizers """ def __init__(self, parameters, **kwargs): self.parameters = parameters self.lr = kwargs.pop('lr', 0.001) self.l1_weight_decay = kwargs.pop('l1_weight_decay', 0.0) self.l2_weight_decay = kwargs.pop('l2_weight_decay', 0.0) self.gradient_clip = kwargs.pop('gradient_clip', 0.0) self.state = dict() for p in self.parameters(): self.state[p] = dict() def zero_grad(self): for p in self.parameters(): if p.grad is not None: p.grad = np.zeros(p.shape) def clip_grads(self): if self.gradient_clip != 0.0: for p in self.parameters(): p.grad = np.clip(p.grad, -self.gradient_clip, self.gradient_clip) def step(self): self.clip_grads() self._step() def _step(self): raise NotImplementedError() <file_sep>/nn/rnn.py import numpy as np import IPython from .module import Module from .parameter import Parameter from .activation import Sigmoid, Tanh, ReLU class RNN(Module): """Vanilla recurrent neural network layer. The single time step forward transformation is h[:,t+1] = tanh(Whh * h[:,t] + Whx * X[:,t] + bh) with the following dimensions X: (T, N, D) h: (N, H) Whx: (H, D) Whh: (H, H) b: (H) where D: input dimension T: input sequence length H: hidden dimension Parameters ---------- input_size : [type] [description] hidden_size : [type] [description] bias : [type] [description] nonlinearity : [type] [description] Returns ------- [type] [description] """ def __init__(self, input_size, hidden_size, output_size, bias=True, nonlinearity=Tanh(), time_first=True, bptt_truncate=0): super(RNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.nonlinearity = nonlinearity self.time_first = time_first self.bptt_truncate = bptt_truncate self.Wxh = Parameter(np.zeros((hidden_size, input_size))) self.Whh = Parameter(np.zeros((hidden_size, hidden_size))) self.Why = Parameter(np.zeros((output_size, hidden_size))) if bias: self.b = Parameter(np.zeros(hidden_size)) else: self.b = None if time_first: self.t_dim = 0 self.n_dim = 1 self.d_dim = 2 else: self.t_dim = 1 self.n_dim = 0 self.d_dim = 2 self.reset_parameters() def reset_parameters(self): stdhh = np.sqrt(1. / self.hidden_size) stdhx = np.sqrt(1. / self.input_size) self.Wxh.data = np.random.uniform(-stdhx, stdhx, size=(self.hidden_size, self.input_size)) self.Whh.data = np.random.uniform(-stdhh, stdhh, size=(self.hidden_size, self.hidden_size)) if self.b is not None: self.b.data = np.zeros(self.hidden_size) def forward_step(self, x, h): """Compute state k from the previous state (sk) and current input (xk), by use of the input weights (wx) and recursive weights (wRec). """ return self.nonlinearity.forward(h @ self.Whh.data.T + x @ self.Wxh.data.T + self.b.data) def forward(self, X, h0=None): """Unfold the network and compute all state activations given the input X, and input weights (wx) and recursive weights (wRec). Return the state activations in a matrix, the last column S[:,-1] contains the final activations. """ # Initialise the matrix that holds all states for all input sequences. # The initial state s0 is set to 0. if not self.time_first: X = X.transpose(self.n_dim, self.t_dim, self.n_dim) # [N, T, D] --> [T, N, D] h = np.zeros((X.shape[self.t_dim] + 1, X.shape[self.n_dim], self.hidden_size)) # (T, N, H) if h0: h[0] = h0 # Use the recurrence relation defined by forward_step to update the states trough time. for t in range(0, X.shape[self.t_dim]): h[t + 1] = self.nonlinearity.forward(np.dot(X[t], self.Wxh.data.T) + np.dot(h[t], self.Whh.data.T) + self.b.data) # h[t + 1] = self.forward_step(X[t, :], h[t]) # np.dot(self.Wxh.data, X[t][5]) # np.dot(X[t], self.Wxh.data.T) # Cache self.X = X self.h = h return h def backward_step_old_broken(self, dh, x_cache, h_cache): """Compute a single backwards time step. """ # https://gist.github.com/karpathy/d4dee566867f8291f086 # Activation dh = self.nonlinearity.backward(dh, h_cache) # Gradient of the linear layer parameters (accumulate) self.Whh.grad += dh.T @ h_cache # np.outer(dh, h_cache) self.Wxh.grad += dh.T @ x_cache # np.outer(dh, x_cache) if self.b is not None: self.b.grad += dh.sum(axis=0) # Gradient at the output of the previous layer dh_prev = dh @ self.Whh.data.T # self.Whh.data @ dh.T return dh_prev def backward_old_broken(self, delta): """Backpropagate the gradient computed at the output (delta) through the network. Accumulate the parameter gradients for `Whx` and `Whh` by for each layer by addition. Return the parameter gradients as a tuple, and the gradients at the output of each layer. """ # Initialise the array that stores the gradients of the cost with respect to the states. dh = np.zeros((self.X.shape[self.t_dim] + 1, self.X.shape[self.n_dim], self.hidden_size)) dh[-1] = delta for t in range(self.X.shape[self.t_dim], 0, -1): dh[t - 1, :] = self.backward_step_old_broken(dh[t, :], self.X[t - 1, :], self.h[t - 1, :]) return dh def backward(self, delta): """Backpropagate the gradient computed at the output (delta) through the network. Accumulate the parameter gradients for `Whx` and `Whh` by for each layer by addition. Return the parameter gradients as a tuple, and the gradients at the output of each layer. delta can be (N, H) (N, H, T) """ # http://www.wildml.com/2015/10/recurrent-neural-networks-tutorial-part-3-backpropagation-through-time-and-vanishing-gradients/ # Initialise the array that stores the gradients of the cost with respect to the states. # dh = np.zeros((self.X.shape[self.t_dim] + 1, self.X.shape[self.n_dim], self.hidden_size)) # dh[-1] = delta dh_t = delta for t in range(self.X.shape[self.t_dim], 0, -1): # IPython.embed() # Initial delta calculation: dL/dz (TODO Don't really care about this) # dLdz = self.V.T.dot(delta_o[t]) * (1 - (self.h[t] ** 2)) # (1 - (self.h[t] ** 2)) is Tanh() dh_t = self.nonlinearity.backward(dh_t, self.h[t]) # Backpropagation through time (for at most self.bptt_truncate steps) for bptt_step in np.arange(max(0, t - self.bptt_truncate), t + 1)[::-1]: # print &quot;Backpropagation step t=%d bptt step=%d &quot; % (t, bptt_step) # Add to gradients at each previous step self.Whh.grad += np.einsum('NH,iNH->NH', dh_t, self.h[bptt_step - 1]) # self.Whh.grad += np.outer(dh_t, self.h[bptt_step - 1]) self.Wxh.grad[:, self.X[bptt_step]] += dh_t # self.Wxh.grad[:, self.X[bptt_step]] += dLdz # TODO Really want dh/dU # Update delta for next step dL/dz at t-1 dh_t = self.nonlinearity.backward(self.Whh.data.T.dot(dh_t), self.h[bptt_step-1]) # (1 - self.h[bptt_step-1] ** 2) # dh[t - 1, :] = self.backward_step(dh[t, :], self.X[t - 1, :], self.h[t - 1, :]) return dh_t def backward_step(self, dh, x_cache, h_cache): pass # return [dLdU, dLdV, dLdW] def bptt(self, x, y): T = len(y) # Perform forward propagation o, s = self.forward_propagation(x) # We accumulate the gradients in these variables dLdU = np.zeros(self.Wxh.shape) dLdV = np.zeros(self.V.shape) dLdW = np.zeros(self.Whh.shape) delta_o = o delta_o[np.arange(len(y)), y] -= 1. # For each output backwards... for t in np.arange(T)[::-1]: dLdV += np.outer(delta_o[t], s[t].T) # Initial delta calculation: dL/dz delta_t = self.V.T.dot(delta_o[t]) * (1 - (s[t] ** 2)) # (1 - (s[t] ** 2)) is Tanh() # Backpropagation through time (for at most self.bptt_truncate steps) for bptt_step in np.arange(max(0, t - self.bptt_truncate), t + 1)[::-1]: # print &quot;Backpropagation step t=%d bptt step=%d &quot; % (t, bptt_step) # Add to gradients at each previous step dLdW += np.outer(delta_t, s[bptt_step - 1]) dLdU[:, x[bptt_step]] += delta_t # Update delta for next step dL/dz at t-1 delta_t = self.Whh.data.T.dot(delta_t) * (1 - s[bptt_step-1] ** 2) return [dLdU, dLdV, dLdW] # http://willwolf.io/2016/10/18/recurrent-neural-network-gradients-and-lessons-learned-therein/ # https://github.com/go2carter/nn-learn/blob/master/grad-deriv-tex/rnn-grad-deriv.pdf # https://peterroelants.github.io/posts/rnn-implementation-part01/ # http://www.wildml.com/2015/10/recurrent-neural-networks-tutorial-part-3-backpropagation-through-time-and-vanishing-gradients/ class GRU(Module): def __init__(self): pass class LSTM(Module): def __init__(self, input_size, hidden_size=128, bias=True, time_first=True): super(LSTM, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.time_first = time_first if time_first: self.t_dim = 0 self.n_dim = 1 self.d_dim = 2 else: self.t_dim = 1 self.n_dim = 0 self.d_dim = 2 D = self.input_size H = self.hidden_size Z = D + H # Concatenation self.Wf = Parameter(np.zeros((Z, H))) self.Wi = Parameter(np.zeros((Z, H))) self.Wc = Parameter(np.zeros((Z, H))) self.Wo = Parameter(np.zeros((Z, H))) self.Wy = Parameter(np.zeros((H, D))) if bias: self.bf = Parameter(np.zeros((1, H))) self.bi = Parameter(np.zeros((1, H))) self.bc = Parameter(np.zeros((1, H))) self.bo = Parameter(np.zeros((1, H))) self.by = Parameter(np.zeros((1, D))) else: self.bf = None self.bi = None self.bc = None self.bo = None self.by = None self.reset_parameters() def reset_parameters(self): # TODO Add orthogonal initialization D = self.input_size H = self.hidden_size Z = D + H # Concatenation self.Wf.data = np.random.randn(Z, H) / np.sqrt(Z / 2.) self.Wi.data = np.random.randn(Z, H) / np.sqrt(Z / 2.) self.Wc.data = np.random.randn(Z, H) / np.sqrt(Z / 2.) self.Wo.data = np.random.randn(Z, H) / np.sqrt(Z / 2.) self.Wy.data = np.random.randn(H, D) / np.sqrt(D / 2.) if self.bf is not None: self.bf.data = np.zeros((1, H)) self.bi.data = np.zeros((1, H)) self.bc.data = np.zeros((1, H)) self.bo.data = np.zeros((1, H)) self.by.data = np.zeros((1, D)) else: self.bf = None self.bi = None self.bc = None self.bo = None self.by = None self.sigmoidf = Sigmoid() self.sigmoidi = Sigmoid() self.sigmoido = Sigmoid() self.tanhc = Tanh() self.tanh = Tanh() def forward_step(self, x, state): h_old, c_old = state # # One-hot encode # X_one_hot = np.zeros(D) # X_one_hot[X] = 1. # X_one_hot = X_one_hot.reshape(1, -1) # Concatenate old state with current input hx = np.column_stack((h_old, x)) hf = self.sigmoidf.forward(hx @ self.Wf.data + self.bf.data) hi = self.sigmoidi.forward(hx @ self.Wi.data + self.bi.data) ho = self.sigmoido.forward(hx @ self.Wo.data + self.bo.data) hc = self.tanhc.forward(hx @ self.Wc.data + self.bc.data) c = hf * c_old + hi * hc h = ho * self.tanh.forward(c) # y = h @ Wy + by # prob = softmax(y) self.cache = dict(hx=[*self.cache['hx'], hx], hf=[*self.cache['hf'], hf], hi=[*self.cache['hi'], hi], ho=[*self.cache['ho'], ho], hc=[*self.cache['hc'], hc], c=[*self.cache['c'], c], c_old=[*self.cache['c_old'], c_old]) return (h, c) def forward(self, X): self.cache = dict(hx=[], hf=[], hi=[], ho=[], hc=[], c=[], c_old=[]) if not self.time_first: X = X.transpose(self.n_dim, self.t_dim, self.n_dim) # [N, T, D] --> [T, N, D] h = np.zeros((X.shape[self.t_dim] + 1, X.shape[self.n_dim], self.hidden_size)) # (T, N, H) c = np.zeros((X.shape[self.t_dim] + 1, X.shape[self.n_dim], self.hidden_size)) # (T, N, H) # Use the recurrence relation defined by forward_step to update the states trough time. for t in range(0, X.shape[self.t_dim]): h[t + 1], c[t + 1] = self.forward_step(X[t, :], (h[t], c[t])) return h[-1] def backward_step(self, dh_next, dc_next, t): # Unpack the cache variable to get the intermediate variables used in forward step hx = self.cache['hx'][t] hf = self.cache['hf'][t] hi = self.cache['hi'][t] ho = self.cache['ho'][t] hc = self.cache['hc'][t] c = self.cache['c'][t] c_old = self.cache['c_old'][t] IPython.embed() # # Softmax loss gradient # dy = prob.copy() # dy[1, y_train] -= 1. # # Hidden to output gradient # dWy = h.T @ dy # dby = dy # # Note we're adding dh_next here # dh = dy @ Wy.T + dh_next # Gradient for ho in h = ho * tanh(c) dho = self.tanh.forward(c) * dh_next dho = self.sigmoido.backward(ho) * dho # Gradient for c in h = ho * tanh(c), note we're adding dc_next here dc = ho * dh_next * self.tanh.backward(c) dc = dc + dc_next # Gradient for hf in c = hf * c_old + hi * hc dhf = c_old * dc dhf = self.sigmoidf.backward(hf) * dhf # Gradient for hi in c = hf * c_old + hi * hc dhi = hc * dc dhi = self.sigmoidi.backward(hi) * dhi # Gradient for hc in c = hf * c_old + hi * hc dhc = hi * dc dhc = self.tanhc.backward(hc) * dhc # Gate gradients, just a normal fully connected layer gradient self.Wf.grad += hx.T @ dhf self.bf.grad += dhf.sum(axis=0) dxf = dhf @ self.Wf.data.T self.Wi.grad += hx.T @ dhi self.bi.grad += dhi.sum(axis=0) dxi = dhi @ self.Wi.data.T self.Wo.grad += hx.T @ dho self.bo.grad += dho.sum(axis=0) dxo = dho @ self.Wo.data.T self.Wc.grad += hx.T @ dhc self.bc.grad += dhc.sum(axis=0) dxc = dhc @ self.Wc.data.T # As x was used in multiple gates, the gradient must be accumulated here dx = dxo + dxc + dxi + dxf # Split the concatenated X, so that we get our gradient of h_old dh_next = dx[:, :self.hidden_size] # Gradient for c_old in c = hf * c_old + hi * hc dc_next = hf * dc return dh_next, dc_next def backward(self, delta): # https://wiseodd.github.io/techblog/2016/08/12/lstm-backprop/ # https://gist.github.com/karpathy/d4dee566867f8291f086 dh_next = delta dc_next = np.zeros_like(dh_next) for t in range(len(self.cache['hx']) - 1, 0, -1): dh_next, dc_next = self.backward_step(dh_next, dc_next, t) def lstm_backward(prob, y_train, d_next, cache): # Unpack the cache variable to get the intermediate variables used in forward step # ... = cache dh_next, dc_next = d_next # Softmax loss gradient dy = prob.copy() dy[1, y_train] -= 1. # Hidden to output gradient dWy = h.T @ dy dby = dy # Note we're adding dh_next here dh = dy @ Wy.T + dh_next # Gradient for ho in h = ho * tanh(c) dho = tanh(c) * dh dho = dsigmoid(ho) * dho # Gradient for c in h = ho * tanh(c), note we're adding dc_next here dc = ho * dh * dtanh(c) dc = dc + dc_next # Gradient for hf in c = hf * c_old + hi * hc dhf = c_old * dc dhf = dsigmoid(hf) * dhf # Gradient for hi in c = hf * c_old + hi * hc dhi = hc * dc dhi = dsigmoid(hi) * dhi # Gradient for hc in c = hf * c_old + hi * hc dhc = hi * dc dhc = dtanh(hc) * dhc # Gate gradients, just a normal fully connected layer gradient dWf = X.T @ dhf dbf = dhf dXf = dhf @ Wf.T dWi = X.T @ dhi dbi = dhi dXi = dhi @ Wi.T dWo = X.T @ dho dbo = dho dXo = dho @ Wo.T dWc = X.T @ dhc dbc = dhc dXc = dhc @ Wc.T # As X was used in multiple gates, the gradient must be accumulated here dX = dXo + dXc + dXi + dXf # Split the concatenated X, so that we get our gradient of h_old dh_next = dX[:, :H] # Gradient for c_old in c = hf * c_old + hi * hc dc_next = hf * dc grad = dict(Wf=dWf, Wi=dWi, Wc=dWc, Wo=dWo, Wy=dWy, bf=dbf, bi=dbi, bc=dbc, bo=dbo, by=dby) state = (dh_next, dc_next) return grad, state import numpy as np import code class LSTM: # https://gist.github.com/karpathy/587454dc0146a6ae21fc @staticmethod def init(input_size, hidden_size, fancy_forget_bias_init = 3): """ Initialize parameters of the LSTM (both weights and biases in one matrix) One might way to have a positive fancy_forget_bias_init number (e.g. maybe even up to 5, in some papers) """ # +1 for the biases, which will be the first row of WLSTM WLSTM = np.random.randn(input_size + hidden_size + 1, 4 * hidden_size) / np.sqrt(input_size + hidden_size) WLSTM[0,:] = 0 # initialize biases to zero if fancy_forget_bias_init != 0: # forget gates get little bit negative bias initially to encourage them to be turned off # remember that due to Xavier initialization above, the raw output activations from gates before # nonlinearity are zero mean and on order of standard deviation ~1 WLSTM[0,hidden_size:2*hidden_size] = fancy_forget_bias_init return WLSTM @staticmethod def forward(X, WLSTM, c0 = None, h0 = None): """ X should be of shape (n,b,input_size), where n = length of sequence, b = batch size """ n,b,input_size = X.shape d = WLSTM.shape[1]/4 # hidden size if c0 is None: c0 = np.zeros((b,d)) if h0 is None: h0 = np.zeros((b,d)) # Perform the LSTM forward pass with X as the input xphpb = WLSTM.shape[0] # x plus h plus bias, lol Hin = np.zeros((n, b, xphpb)) # input [1, xt, ht-1] to each tick of the LSTM Hout = np.zeros((n, b, d)) # hidden representation of the LSTM (gated cell content) IFOG = np.zeros((n, b, d * 4)) # input, forget, output, gate (IFOG) IFOGf = np.zeros((n, b, d * 4)) # after nonlinearity C = np.zeros((n, b, d)) # cell content Ct = np.zeros((n, b, d)) # tanh of cell content for t in xrange(n): # concat [x,h] as input to the LSTM prevh = Hout[t-1] if t > 0 else h0 Hin[t,:,0] = 1 # bias Hin[t,:,1:input_size+1] = X[t] Hin[t,:,input_size+1:] = prevh # compute all gate activations. dots: (most work is this line) IFOG[t] = Hin[t].dot(WLSTM) # non-linearities IFOGf[t,:,:3*d] = 1.0/(1.0+np.exp(-IFOG[t,:,:3*d])) # sigmoids; these are the gates IFOGf[t,:,3*d:] = np.tanh(IFOG[t,:,3*d:]) # tanh # compute the cell activation prevc = C[t-1] if t > 0 else c0 C[t] = IFOGf[t,:,:d] * IFOGf[t,:,3*d:] + IFOGf[t,:,d:2*d] * prevc Ct[t] = np.tanh(C[t]) Hout[t] = IFOGf[t,:,2*d:3*d] * Ct[t] cache = {} cache['WLSTM'] = WLSTM cache['Hout'] = Hout cache['IFOGf'] = IFOGf cache['IFOG'] = IFOG cache['C'] = C cache['Ct'] = Ct cache['Hin'] = Hin cache['c0'] = c0 cache['h0'] = h0 # return C[t], as well so we can continue LSTM with prev state init if needed return Hout, C[t], Hout[t], cache @staticmethod def backward(dHout_in, cache, dcn = None, dhn = None): WLSTM = cache['WLSTM'] Hout = cache['Hout'] IFOGf = cache['IFOGf'] IFOG = cache['IFOG'] C = cache['C'] Ct = cache['Ct'] Hin = cache['Hin'] c0 = cache['c0'] h0 = cache['h0'] n,b,d = Hout.shape input_size = WLSTM.shape[0] - d - 1 # -1 due to bias # backprop the LSTM dIFOG = np.zeros(IFOG.shape) dIFOGf = np.zeros(IFOGf.shape) dWLSTM = np.zeros(WLSTM.shape) dHin = np.zeros(Hin.shape) dC = np.zeros(C.shape) dX = np.zeros((n,b,input_size)) dh0 = np.zeros((b, d)) dc0 = np.zeros((b, d)) dHout = dHout_in.copy() # make a copy so we don't have any funny side effects if dcn is not None: dC[n-1] += dcn.copy() # carry over gradients from later if dhn is not None: dHout[n-1] += dhn.copy() for t in reversed(xrange(n)): tanhCt = Ct[t] dIFOGf[t,:,2*d:3*d] = tanhCt * dHout[t] # backprop tanh non-linearity first then continue backprop dC[t] += (1-tanhCt**2) * (IFOGf[t,:,2*d:3*d] * dHout[t]) if t > 0: dIFOGf[t,:,d:2*d] = C[t-1] * dC[t] dC[t-1] += IFOGf[t,:,d:2*d] * dC[t] else: dIFOGf[t,:,d:2*d] = c0 * dC[t] dc0 = IFOGf[t,:,d:2*d] * dC[t] dIFOGf[t,:,:d] = IFOGf[t,:,3*d:] * dC[t] dIFOGf[t,:,3*d:] = IFOGf[t,:,:d] * dC[t] # backprop activation functions dIFOG[t,:,3*d:] = (1 - IFOGf[t,:,3*d:] ** 2) * dIFOGf[t,:,3*d:] y = IFOGf[t,:,:3*d] dIFOG[t,:,:3*d] = (y*(1.0-y)) * dIFOGf[t,:,:3*d] # backprop matrix multiply dWLSTM += np.dot(Hin[t].transpose(), dIFOG[t]) dHin[t] = dIFOG[t].dot(WLSTM.transpose()) # backprop the identity transforms into Hin dX[t] = dHin[t,:,1:input_size+1] if t > 0: dHout[t-1,:] += dHin[t,:,input_size+1:] else: dh0 += dHin[t,:,input_size+1:] return dX, dWLSTM, dc0, dh0 # ------------------- # TEST CASES # ------------------- def checkSequentialMatchesBatch(): """ check LSTM I/O forward/backward interactions """ n,b,d = (5, 3, 4) # sequence length, batch size, hidden size input_size = 10 WLSTM = LSTM.init(input_size, d) # input size, hidden size X = np.random.randn(n,b,input_size) h0 = np.random.randn(b,d) c0 = np.random.randn(b,d) # sequential forward cprev = c0 hprev = h0 caches = [{} for t in xrange(n)] Hcat = np.zeros((n,b,d)) for t in xrange(n): xt = X[t:t+1] _, cprev, hprev, cache = LSTM.forward(xt, WLSTM, cprev, hprev) caches[t] = cache Hcat[t] = hprev # sanity check: perform batch forward to check that we get the same thing H, _, _, batch_cache = LSTM.forward(X, WLSTM, c0, h0) assert np.allclose(H, Hcat), 'Sequential and Batch forward don''t match!' # eval loss wrand = np.random.randn(*Hcat.shape) loss = np.sum(Hcat * wrand) dH = wrand # get the batched version gradients BdX, BdWLSTM, Bdc0, Bdh0 = LSTM.backward(dH, batch_cache) # now perform sequential backward dX = np.zeros_like(X) dWLSTM = np.zeros_like(WLSTM) dc0 = np.zeros_like(c0) dh0 = np.zeros_like(h0) dcnext = None dhnext = None for t in reversed(xrange(n)): dht = dH[t].reshape(1, b, d) dx, dWLSTMt, dcprev, dhprev = LSTM.backward(dht, caches[t], dcnext, dhnext) dhnext = dhprev dcnext = dcprev dWLSTM += dWLSTMt # accumulate LSTM gradient dX[t] = dx[0] if t == 0: dc0 = dcprev dh0 = dhprev # and make sure the gradients match print('Making sure batched version agrees with sequential version: (should all be True)') print(np.allclose(BdX, dX)) print(np.allclose(BdWLSTM, dWLSTM)) print(np.allclose(Bdc0, dc0)) print(np.allclose(Bdh0, dh0)) def checkBatchGradient(): """ check that the batch gradient is correct """ # lets gradient check this beast n,b,d = (5, 3, 4) # sequence length, batch size, hidden size input_size = 10 WLSTM = LSTM.init(input_size, d) # input size, hidden size X = np.random.randn(n,b,input_size) h0 = np.random.randn(b,d) c0 = np.random.randn(b,d) # batch forward backward H, Ct, Ht, cache = LSTM.forward(X, WLSTM, c0, h0) wrand = np.random.randn(*H.shape) loss = np.sum(H * wrand) # weighted sum is a nice hash to use I think dH = wrand dX, dWLSTM, dc0, dh0 = LSTM.backward(dH, cache) def fwd(): h,_,_,_ = LSTM.forward(X, WLSTM, c0, h0) return np.sum(h * wrand) # now gradient check all delta = 1e-5 rel_error_thr_warning = 1e-2 rel_error_thr_error = 1 tocheck = [X, WLSTM, c0, h0] grads_analytic = [dX, dWLSTM, dc0, dh0] names = ['X', 'WLSTM', 'c0', 'h0'] for j in xrange(len(tocheck)): mat = tocheck[j] dmat = grads_analytic[j] name = names[j] # gradcheck for i in xrange(mat.size): old_val = mat.flat[i] mat.flat[i] = old_val + delta loss0 = fwd() mat.flat[i] = old_val - delta loss1 = fwd() mat.flat[i] = old_val grad_analytic = dmat.flat[i] grad_numerical = (loss0 - loss1) / (2 * delta) if grad_numerical == 0 and grad_analytic == 0: rel_error = 0 # both are zero, OK. status = 'OK' elif abs(grad_numerical) < 1e-7 and abs(grad_analytic) < 1e-7: rel_error = 0 # not enough precision to check this status = 'VAL SMALL WARNING' else: rel_error = abs(grad_analytic - grad_numerical) / abs(grad_numerical + grad_analytic) status = 'OK' if rel_error > rel_error_thr_warning: status = 'WARNING' if rel_error > rel_error_thr_error: status = '!!!!! NOTOK' # print stats print('%s checking param %s index %s (val = %+8f), analytic = %+8f, numerical = %+8f, relative error = %+8f'.format( status, name, np.unravel_index(i, mat.shape), old_val, grad_analytic, grad_numerical, rel_error)) if __name__ == "__main__": checkSequentialMatchesBatch() raw_input('check OK, press key to continue to gradient check') checkBatchGradient() print('every line should start with OK. Have a nice day!')<file_sep>/utils/utils.py import os from typing import List import numpy as np import torch from torchvision import datasets, transforms from utils.constants import DATA_DIR def compute_convolution_out_shape(input: int, kernel: int, padding: int, stride: int, dilation: int): return # TODO def onehot(targets: List[int], num_classes: int): out = np.zeros((targets.shape[0], num_classes), dtype=np.float32) for row, col in enumerate(targets): out[row, col] = 1 return out def get_loaders(dataset_name, batch_size): # Dataset dataset = getattr(datasets, dataset_name) transform = transforms.Compose([transforms.ToTensor()]) train_set_kwargs = {'train': True, 'download': True, 'transform': transform} val_set_kwargs = {'train': False, 'download': True, 'transform': transform} train_set = dataset(DATA_DIR, **train_set_kwargs) val_set = dataset(DATA_DIR, **val_set_kwargs) # Create dataset and DataLoader train_loader_kwargs = {'batch_size': batch_size, 'shuffle': True} val_loader_kwargs = {'batch_size': batch_size, 'shuffle': True} train_loader = torch.utils.data.DataLoader(train_set, **train_loader_kwargs) val_loader = torch.utils.data.DataLoader(val_set, **val_loader_kwargs) return train_loader, val_loader <file_sep>/nn/reshape.py from .module import Module import IPython class Flatten(Module): """Flattens the batch. During the forward pass, flattens an input with some dimensionality to a batch matrix, (N, d1, d2, ..., dM) --> (N, D) where D = d1 * d2 * ... * dM During the backwards pass, the inverse operation is applied (N, D) --> (N, d1, d2, ..., dM) where (N, d1, d2, ..., dM) is stored in cache. """ def __init__(self): super().__init__() def __str__(self): return 'Flatten()' def forward(self, x): self.forward_shape = x.shape[1:] return x.reshape(x.shape[0], -1) def backward(self, delta): return delta.reshape(delta.shape[0], *self.forward_shape) class Reshape(Module): """Flattens the batch. During the forward pass, reshapes an input to an any possible shape. During the backwards pass, the inverse operation is applied. """ def __init__(self, output_shape=(-1)): super().__init__() self.output_shape = output_shape def __str__(self): return f'Reshape(output_shape={self.output_shape})' def forward(self, x): self.forward_shape = x.shape[1:] return x.reshape(self.output_shape) def backward(self, delta): return delta.reshape(delta.shape[0], *self.forward_shape) <file_sep>/optim/__init__.py from .optimizer import Optimizer from .sgd import SGD from .adam import Adam from .lr_schedulers import *<file_sep>/utils/constants.py import os DATA_DIR = './data' SAVE_DIR = './results' <file_sep>/utils/__init__.py from .trainers import * from .utils import * from .progress import *<file_sep>/optim/adam.py import numpy as np from .optimizer import Optimizer class Adam(Optimizer): def __init__(self, parameters, lr=1e-3, betas=(0.9, 0.999), l1_weight_decay=0.0, l2_weight_decay=0.0, gradient_clip=0.0, amsgrad=False, eps=1e-8): kwargs = {'lr': lr, 'l1_weight_decay': l1_weight_decay, 'l2_weight_decay': l2_weight_decay, 'gradient_clip': gradient_clip} super().__init__(parameters, **kwargs) self.betas = betas self.amsgrad = amsgrad self.eps = eps def _step(self): beta1, beta2 = self.betas for p in self.parameters(): # Get gradient and state if p.grad is None: continue dp = p.grad # State initialization if len(self.state[p]) == 0: self.state[p]['step'] = 0 # Step self.state[p]['exp_avg'] = np.zeros_like(p.data) # Exponential moving average of gradient self.state[p]['exp_avg_sq'] = np.zeros_like(p.data) # Exponential moving average of squared gradient self.state[p]['max_exp_avg_sq'] = np.zeros_like(p.data) if self.amsgrad else None # Max of all ma # Retrieve self.state[p] variables exp_avg, exp_avg_sq = self.state[p]['exp_avg'], self.state[p]['exp_avg_sq'] max_exp_avg_sq = self.state[p]['max_exp_avg_sq'] if self.amsgrad else None self.state[p]['step'] += 1 # Weight decay if self.l1_weight_decay != 0: dp += self.l1_weight_decay if self.l2_weight_decay != 0: dp += self.l2_weight_decay * p.data # Decay the first and second moment running average coefficient exp_avg = beta1 * exp_avg + (1 - beta1) * dp exp_avg_sq = beta2 * exp_avg_sq + (1 - beta2) * (dp ** 2) if self.amsgrad: # Maintains the maximum of all 2nd moment running avg. till now np.maximum(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq) # Use the max for normalizing running avg of gradient max_exp_avg_sq = np.sqrt(max_exp_avg_sq + self.eps) denom = max_exp_avg_sq else: exp_avg_sq = np.sqrt(exp_avg_sq + self.eps) denom = exp_avg_sq # Compute step size bias_correction1 = 1 - beta1 ** self.state[p]['step'] bias_correction2 = 1 - beta2 ** self.state[p]['step'] step_size = self.lr * np.sqrt(bias_correction2) / bias_correction1 # Update parameters p.data -= step_size * exp_avg / denom <file_sep>/nn/loss.py import IPython import numpy as np from .module import Module # TODO Add reduction methods somehow class Loss(Module): def __init__(self, reduction=None): self.reduction = reduction class MeanSquaredLoss(Loss): """Mean Squared Loss function for multiple regression. Shapes ------ Input: (N, C) where N is batch size and C is number of classes. Target: (N, C) where each row is a one-hot encoded vector Output: float Scalar loss. """ def __init__(self, reduction=None): super().__init__(reduction) def __str__(self): return f'MeanSquaredLoss(reduction={self.reduction})' def forward(self, y, t): loss = 0.5 * ((y - t) ** 2) if self.reduction is not None: loss = self.reduction(loss) return loss def backward(self, y, t): N = y.shape[0] delta_out = np.sum(y-t, axis=0) / N return delta_out class CrossEntropyLoss(Loss): """Cross Entropy Loss function for C class classification. Shapes ------ Input: (N, C) where N is batch size and C is number of classes. Target: (N, C) where each row is a one-hot encoded vector Output: float Scalar loss. """ def __init__(self, reduction=None, eps=1e-8): super().__init__(reduction) self.eps = eps def __str__(self): return f'CrossEntropyLoss(reduction={self.reduction}, eps={self.eps})' def forward(self, y, t): loss = -np.log(y[t.astype(bool)] + self.eps) if self.reduction is not None: loss = self.reduction(loss) return loss def backward(self, y, t): delta_out = (1.0 / y.shape[0]) * (y - t) return delta_out <file_sep>/optim/sgd.py import numpy as np from .optimizer import Optimizer class SGD(Optimizer): def __init__(self, parameters, lr=0.001, momentum=0.0, nesterov=False, dampening=0.0, l1_weight_decay=0.0, l2_weight_decay=0.0, gradient_clip=0.0): kwargs = {'lr': lr, 'l1_weight_decay': l1_weight_decay, 'l2_weight_decay': l2_weight_decay, 'gradient_clip': gradient_clip} super(SGD, self).__init__(parameters, **kwargs) self.momentum = momentum self.nesterov = nesterov self.dampening = dampening def _step(self): for p in self.parameters(): if p.grad is None: continue dp = p.grad if self.l1_weight_decay != 0: dp += self.l1_weight_decay if self.l2_weight_decay != 0: dp += self.l2_weight_decay * p.data if self.momentum != 0: if 'momentum_buffer' not in self.state[p]: self.state[p]['momentum_buffer'] = np.zeros(p.shape) self.state[p]['momentum_buffer'] += dp else: self.state[p]['momentum_buffer'] *= self.momentum self.state[p]['momentum_buffer'] += (1-self.dampening) * dp if self.nesterov: dp += self.momentum * dp else: dp = self.state[p]['momentum_buffer'] p.data -= self.lr * dp <file_sep>/evaluators/multiclass_evaluator.py import numpy as np import pandas as pd from sklearn.metrics import confusion_matrix, precision_recall_fscore_support from .evaluator import Evaluator class MulticlassEvaluator(Evaluator): """ Evaluator for multiclass classification. The confusion matrix may be replaced by the PyCM version (https://github.com/sepandhaghighi/pycm). This e.g. supports class weights and activation thresholds for computing the confusion matrix from class probabilities rather than labels. The only issue is how we accumulate the confusion matrices in this case since the classes don't support addition. """ def __init__(self, n_classes=None, labels=None, evaluation_metric='accuracy'): """ Initialize the MulticlassEvaluator object Args: n_classes (int): Number of classes labels (list): The labels for each class evaluation_metric (str): The attribute to use as evaluation metric """ super().__init__(evaluation_metric) if n_classes is not None: self._n_classes = n_classes if labels is not None: assert self._n_classes == len(labels), 'Must have as many labels as classes' self._labels = labels else: self._labels = np.arange(0, n_classes, dtype=np.int) self.batch = 0 self._track_metrics = ('loss', 'accuracies', 'f1_scores', 'tprs', 'fprs', 'tnrs', 'fnrs', 'ppvs', 'fors', 'npvs', 'fdrs') self.history = pd.DataFrame(columns=('batch',) + self._track_metrics) self.reset() # Setting all tracked metrics of the evaluator to default values. def update(self, predictions, labels, loss): """ Update the tracked metrics: Confusion matrix, accuracy Args: predictions (list): List of predictions. labels (list): The labels corresponding to the predictions. loss (None or list): List of the loss for each example for each GPU. """ # Update loss related values; remember to filter out infs and nans. loss_filter = np.invert(np.logical_or(np.isinf(loss), np.isnan(loss))) loss = loss[loss_filter] self.loss_sum += loss.sum() self.num_examples += loss.size loss = loss.mean() # Update confusion matrix # Confusion matrix with model predictions in rows, true labels in columns # Batch statistics for history cm = confusion_matrix(labels.argmax(axis=1), predictions.argmax(axis=1), labels=self._labels) tps, fps, tns, fns = self.compute_tp_fp_tn_fn(cm) tprs, fprs, tnrs, fnrs = self.compute_tpr_fpr_tnr_fnr(tps, fps, tns, fns) ppvs, fors, npvs, fdrs = self.compute_ppv_for_npv_fdr(tps, fps, tns, fns) accuracies = self.compute_accuracies(tps, fps, tns, fns) f1_scores = self.compute_f1_scores(tps, fps, tns, fns) d = {'batch': self.batch} for v in self._track_metrics: d.update({v: eval(v).mean()}) self.history = self.history.append(d, ignore_index=True) # accumulated statistics self.cm += cm self.tps, self.fps, self.tns, self.fns = self.compute_tp_fp_tn_fn(self.cm) self.tprs, self.fprs, self.tnrs, self.fnrs = self.compute_tpr_fpr_tnr_fnr(self.tps, self.fps, self.tns, self.fns) self.ppvs, self.fors, self.npvs, self.fdrs = self.compute_ppv_for_npv_fdr(self.tps, self.fps, self.tns, self.fns) self.accuracies = self.compute_accuracies(self.tps, self.fps, self.tns, self.fns) self.f1_scores = self.compute_f1_scores(self.tps, self.fps, self.tns, self.fns) # Bump batch counter self.batch += 1 @staticmethod def compute_tp_fp_tn_fn(cm): tp = np.diag(cm) # TPs are diagonal elements fp = cm.sum(axis=0) - tp # FPs is sum of row minus true positives fn = cm.sum(axis=1) - tp # FNs is sum of column minus true positives tn = cm.sum() - np.array([cm[i, :].sum() + cm[:, i].sum() - cm[i, i] for i in range(cm.shape[0])]) # total count minus false positives and false negatives plus true positives (which are otherwise subtracted twice) return tp, fp, tn, fn @staticmethod def compute_tpr_fpr_tnr_fnr(tp, fp, tn, fn): TPRs = tp / np.maximum(tp + fn, 1) # True positive rate (recall) FPRs = fp / np.maximum(tn + fp, 1) # False positive rate TNRs = tn / np.maximum(tn + fp, 1) # True negative rate (specificity) FNRs = fn / np.maximum(tp + fn, 1) # False negative rate return TPRs, FPRs, TNRs, FNRs @staticmethod def compute_ppv_for_npv_fdr(tp, fp, tn, fn): PPVs = tp / np.maximum(tp + fp, 1) # Positive predictive value (precision) FORs = fn / np.maximum(tn + fn, 1) # False omission rate NPVs = tn / np.maximum(tn + fn, 1) # Negative predictive value FDRs = fp / np.maximum(tp + fp, 1) # False discovery rate return PPVs, FORs, NPVs, FDRs @staticmethod def compute_accuracies(tp, fp, tn, fn): return (tp + tn) / np.maximum(tp + fp + tn + fn, 1) @staticmethod def compute_f1_scores(tp, fp, tn, fn): return 2 * tp / np.maximum(2 * tp + fn + fp, 1) @property def loss(self): return self.loss_sum / self.num_examples @property def tpr(self): return self.tprs.mean() @property def ppv(self): return self.ppvs.mean() @property def f1_score(self): return self.f1_scores.mean() @property def accuracy(self): return self.accuracies.mean() def reset(self): """ Reset the tracked metrics. """ self.loss_sum = 0 self.num_examples = 0 self.tps = np.zeros(shape=self._n_classes) self.fps = np.zeros(shape=self._n_classes) self.fns = np.zeros(shape=self._n_classes) self.tns = np.zeros(shape=self._n_classes) self.cm = np.zeros((self._n_classes, self._n_classes)) <file_sep>/evaluators/binary_evaluator.py import numpy as np from sklearn.metrics import confusion_matrix, roc_curve, roc_auc_score, precision_recall_curve, auc from .evaluator import Evaluator class BinaryEvaluator(Evaluator): def __init__(self, evaluation_metric='recall'): """ Initialize a BinaryEvaluator. The BinaryEvaluator is an evaluator to be used for binary classification tasks which can be formulated in terms of a detection. For this purpose, the evaluator implements methods for finding an optimal decision boundary while keeping the TPR or the FPR fixed. Args: evaluation_metric (str): The attribute to use for evaluation. """ super().__init__(self, evaluation_metric) def update(self, probabilities, labels, loss): """ Update the tracked metrics: Recall/FPR and loss. Args: probabilities (list): List of predicted probabilities for the positive class for each example. labels (list): The labels corresponding to the predictions, as one-hot-encoded vectors. loss (list): List of the loss for each example for each GPU. """ # Update loss related values; remember to filter out infs and nans. # loss = np.array(loss) filter_naninf = np.invert(np.isinf(loss) + np.isnan(loss)) loss_clean = loss[filter_naninf] self.loss_sum += np.sum(loss_clean) self.num_examples += len(loss_clean) self.loss = self.loss_sum / self.num_examples # Decode predictions and sparse labels for WER computation. self.probabilities = np.append(self.probabilities, np.concatenate(probabilities, axis=0)) self.labels = np.append(self.labels, np.argmax(np.concatenate(labels, axis=0), axis=1)) @staticmethod def _compute_recall(predictions, targets): """ Computes tpr for given binary predictions and targets. Args: predictions (list of int): Binary predictions. targets (list of int): Binary targets. Returns: float: Recall. """ tn, fp, fn, tp = confusion_matrix(targets, predictions).ravel() tpr = tp / max(tp + fn, 1) return tpr @staticmethod def _compute_fpr(predictions, targets): """ Computes false positive rate. Args: predictions (list of int): The binary predictions. targets (list of int): The targets. Returns: float: False positive rate. """ tn, fp, fn, tp = confusion_matrix(targets, predictions).ravel() fpr = fp / max(fp + tn, 1) return fpr @staticmethod def _compute_metrics(predictions, targets): """ Computes key metrics for predictions and targets. Args: predictions (list of int): The binary predictions for the targets. targets (list of int): The targets for which predictions are provided. Returns: tuple: A tuple with some key metrics. """ tn, fp, fn, tp = confusion_matrix(targets, predictions).ravel() tpr = BinaryEvaluator._compute_recall(predictions, targets) fpr = BinaryEvaluator._compute_fpr(predictions, targets) ppv = tp / max(tp + fp, 1) tnr = tn / max(tn + fp, 1) fnr = fn / max(fn + tp, 1) npv = tn / max(tn + fn, 1) return tpr, fpr, ppv, tnr, fnr, npv, tp, tn, fp, fn def evaluate_area(self, metric): """ Evaluates area under the curve metrics. AUC or AUCPR Args: metric (str): Can be 'auc' or 'aucpr' to evaluate the respective metric. Returns: float: The metric for the currently recorded predictions. """ if metric == 'auc': return roc_auc_score(self.labels, self.probabilities) elif metric == 'aucpr': precision, recall, _ = precision_recall_curve(self.labels, self.probabilities) return auc(recall, precision) def evaluate_fixed_rate(self, fixed_tpr=None, fixed_fpr=None): """ Finds and evaluates a decision boundary at either fixed TPR or fixed FPR. One and only one of `fixed_tpr` and `fixed_fpr` must be given. Args: fixed_tpr (float): The fixed tpr to use when finding the decision boundary fixed_fpr (float): The fixed fpr to use when finding the decision boundary Returns: tuple of decision boundary and metrics at the fixed rate. """ decision_boundary, _, _ = self.find_decision_boundary(fixed_tpr, fixed_fpr) tpr, fpr, ppv, tnr, fnr, npv, tp, tn, fp, fn = self.evaluate_decision_boundary(decision_boundary) return decision_boundary, tpr, fpr, ppv, tnr, fnr, npv, tp, tn, fp, fn def find_decision_boundary(self, fixed_tpr=None, fixed_fpr=None): """ Finds a decision boundary at either fixed TPR or fixed FPR. One and only one of `fixed_tpr` and `fixed_fpr` must be given. Args: fixed_tpr (float): If specified, returns decision boundary at this true positive rate fixed_fpr (float): If specified, returns decision boundary at this false positive rate Returns: tuple: The decision boundary, the tpr, and the false positive rate at the specified rate. """ if (fixed_tpr is None) == (fixed_fpr is None): return ValueError('Either `fixed_tpr` or `fixed_fpr` have to be specified, but not both.') fpr, tpr, thresholds = roc_curve(self.labels, self.probabilities) if fixed_tpr is not None: index_best = np.argmax(tpr >= fixed_tpr) tpr = fixed_tpr fpr = fpr[index_best] decision_boundary = thresholds[index_best] else: index_best = max(0, np.argmin(fpr <= fixed_fpr) - 1) tpr = tpr[index_best] fpr = fixed_fpr decision_boundary = thresholds[index_best] return decision_boundary, tpr, fpr def evaluate_decision_boundary(self, decision_boundary): """ Evaluates metrics at the specified decision boundary. Args: decision_boundary (float): Decision boundary at which to evaluate the metrics. Returns: tuple: A tuple of metrics at the specified decision boundary. """ predictions = (self.probabilities >= decision_boundary).astype(int) tpr, fpr, ppv, tnr, fnr, npv, tp, tn, fp, fn = self._compute_metrics(predictions, self.labels) return tpr, fpr, ppv, tnr, fnr, npv, tp, tn, fp, fn def reset(self): """ Reset the tracked metrics. """ self.loss_sum = 0 self.num_examples = 0 self.loss = None self.probabilities = np.array(()) self.labels = np.array(()) <file_sep>/nn/batchnorm.py import IPython import numpy as np from .module import Module from .parameter import Parameter class BatchNorm1D(Module): def __init__(self, num_features, momentum=0.1, affine=True, eps=1e-5): """Batch normalization layer normalizes the activations of the predeciding layer. If `affine` is true, then an elementwise affine transformation is applied after the normalization. If `momentum` is larger than zero, then a moving average of batch statistics is maintained and used for normalization. If not, new statistics are recomputed for every batch. Arguments: num_features {int} -- The size of the 1D activation space. Keyword Arguments: momentum {float} -- The exponential moving average momentum to use for running statistics (default: {0.1}) affine {bool} -- Whether or to apply an elementwise affine transformation (default: {True}) eps {float} -- A small constant added to square root computations. (default: {1e-5}) """ super(BatchNorm1D, self).__init__() self.num_features = num_features self.eps = eps self.momentum = momentum self.affine = affine self.gamma = Parameter(np.zeros(num_features)) if self.affine else None self.beta = Parameter(np.zeros(num_features)) if self.affine else None self.running_mean = np.zeros(num_features) if self.momentum > 0 else None self.running_var = np.ones(num_features) if self.momentum > 0 else None self.num_batches_tracked = 0 self.cache = dict(x=None) self.reset_parameters() def __str__(self): return f'BatchNorm({self.num_features:d}, momentum={self.momentum:3.2f}, affine={self.affine})' def reset_running_stats(self): if self.momentum == 0.0: self.running_mean = np.zeros(self.running_mean.shape) self.running_var = np.ones(self.running_var.shape) self.num_batches_tracked = 0 def reset_parameters(self): if self.affine: self.gamma.data = np.random.uniform(size=self.gamma.shape) self.beta.data = np.zeros(self.beta.shape) self.reset_running_stats() def update_cache(self, x, x_norm, batch_mean, batch_var): # Cache self.cache = dict(x=x) if self.affine: self.cache.update(dict(x_norm=x_norm)) if self.training: self.cache.update(dict(batch_mean=batch_mean, batch_var=batch_var)) def forward(self, x): if self.training: # Compute batch mean and variance and normalize x batch_mean = np.mean(x, axis=0) batch_var = np.var(x, axis=0) x_norm = (x - batch_mean) / np.sqrt(batch_var + self.eps) # Update running mean and variance if self.momentum is None: self.num_batches_tracked += 1 # Cumulative moving average momentum = 1 - 1.0 / self.num_batches_tracked self.running_mean = momentum * self.running_mean + (1 - momentum) * batch_mean self.running_var = momentum * self.running_var + (1 - momentum) * batch_var else: # Exponential moving average self.running_mean = self.momentum * self.running_mean + (1 - self.momentum) * batch_mean self.running_var = self.momentum * self.running_var + (1 - self.momentum) * batch_var else: batch_mean, batch_var = None, None x_norm = (x - self.running_mean) / np.sqrt(self.running_var + self.eps) # Affine transformation x_out = x_norm * self.gamma.data + self.beta.data if self.affine else x_norm # Cache self.update_cache(x, x_norm, batch_mean, batch_var) return x_out def backward(self, delta): x, batch_mean, batch_var = self.cache['x'], self.cache['batch_mean'], self.cache['batch_var'] N, _ = delta.shape dx_norm = delta * self.gamma.data dsample_var = np.sum(dx_norm * (x - batch_mean) * (-0.5) * (batch_var + self.eps)**(-1.5), axis=0) dsample_mean = np.sum(dx_norm * (-1/np.sqrt(batch_var + self.eps)) , axis=0) + dsample_var * ((np.sum(-2*(x - batch_mean))) / N) dx = dx_norm * (1/np.sqrt(batch_var + self.eps)) + dsample_var * (2*(x - batch_mean)/N) + dsample_mean/N if self.affine: x_norm = self.cache['x_norm'] self.beta.grad = np.sum(delta, axis=0) self.gamma.grad = np.sum(delta * x_norm, axis=0) return dx <file_sep>/optim/lr_schedulers.py import numpy as np class LRScheduler: def __init__(self, optimizer, last_epoch=-1): self.optimizer = optimizer self.last_epoch = last_epoch def get_lr(self): raise NotImplementedError def state_dict(self): """Returns the state of the scheduler as a :class:`dict`. It contains an entry for every variable in self.__dict__ which is not the optimizer. """ return {key: value for key, value in self.__dict__.items() if key != 'optimizer'} def load_state_dict(self, state_dict): """Loads the schedulers state. Arguments: state_dict (dict): scheduler state. Should be an object returned from a call to :meth:`state_dict`. """ self.__dict__.update(state_dict) def step(self, epoch=None): if epoch is None: epoch = self.last_epoch + 1 self.last_epoch = epoch self.optimizer.lr = self.get_lr() # for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()): # param_group['lr'] = lr class ExponentialDecay(LRScheduler): def __init__(self, optimizer, rate=None, half_time=10, last_epoch=-1): """Exponential learning rate decay Set the learning rate of each parameter group to the initial lr decayed by gamma every epoch. When last_epoch=-1, sets initial lr as lr. Args: optimizer (Optimizer): Wrapped optimizer. rate (float): Multiplicative factor of learning rate decay. last_epoch (int): The index of last epoch. Default: -1. """ assert (half_time is not None) != (rate is not None), 'One and only one of half_time and rate must be set' if half_time is not None: self.rate = np.log(2) / half_time elif rate is not None: self.rate = rate super().__init__(optimizer, last_epoch) def get_lr(self): return self.optimizer.lr * self.rate ** self.last_epoch class CosineAnnealingLR(LRScheduler): """Cosine annealing of learning rate Set the learning rate of each parameter group using a cosine annealing schedule, where eta_max is set to the initial lr and T_cur is the number of epochs since the last restart in SGDR: eta_t = eta_min + 0.5 * (eta_max - eta_min) * (1 + cos(T_cur / {T_max} * π)) When last_epoch=-1, sets initial lr as lr. It has been proposed in `SGDR: Stochastic Gradient Descent with Warm Restarts` [1]. Args: optimizer (Optimizer): Wrapped optimizer. T_max (int): Maximum number of iterations. eta_min (float): Minimum learning rate. Default: 0. restarts (bool): If true, then restarts the schedule when learning rate becomes eta_min. T_mult (float): Factor by which to increase T_max on a restart. decay_eta_max_half_time (float): Exponential decay of eta_max on a restart. Defined in terms of half time in units of number of restarts last_epoch (int): The index of last epoch. Default: -1. [1] Stochastic Gradient Descent with Warm Restarts: https://arxiv.org/abs/1608.03983 """ def __init__(self, optimizer, T_max, eta_min=0, restart=True, T_mult=1, decay_eta_max_half_time=1, last_epoch=-1): super().__init__(optimizer, last_epoch) self.T_max = T_max self.eta_min = eta_min self.eta_max = optimizer.lr self.restart = restart self.T_mult = T_mult self._exp_decay_rate = np.log(2) / decay_eta_max_half_time self._n_restarts = 0 def get_lr(self): if self.restart and self.last_epoch == self.T_max: self._n_restarts += 1 # Bump counter self.T_max *= self.T_mult # Increase iterations until next restart by factor of T_mult self.eta_max *= self._exp_decay_rate ** self._n_restarts # Decay maximum learning rate exponentially self.last_epoch = 0 return self.eta_min + (self.eta_max - self.eta_min) * (1 + np.cos(np.pi * (self.last_epoch + 1) / self.T_max)) / 2 <file_sep>/nn/convolution.py import IPython import numpy as np from .im2col import col2im_indices, im2col_indices from .module import Module from .parameter import Parameter try: from .im2col_cython import col2im_cython, im2col_cython from .im2col_cython import col2im_6d_cython except ImportError: print("Failed to import im2col and col2im Cython versions.") print('Run the following from the nn directory and try again:') print('python setup.py build_ext --inplace') class Conv2D(Module): """Convolution module which performs the two-dimensional convolution. The forward transformation is S = X * K with the following dimensions X: (N, C, H, W) K: (NK, C, HK, WK) b: (NK) where N: batch size C: number of image channels H: height of image W: width of the image NK: number of kernels in the feature map K HK: height of the kernel WK: width of the kernel Parameters ---------- in_channels : tuple The number of input channels out_channels : tuple The number of kernels, or feature maps, to learn kernel_size : tuple The dimensions of the kernel stride : int The convolution stride padding : int The zero padding to be applied to the input bias : bool Whether or not to use bias """ def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, bias=True): super().__init__() assert isinstance(kernel_size, tuple), 'Please specifiy kernel size in each dimension as a tuple.' self.in_channels = int(in_channels) self.out_channels = int(out_channels) self.stride = int(stride) self.padding = int(padding) self.kernel_size = kernel_size self.K = Parameter(np.zeros((out_channels, in_channels, *self.kernel_size))) if bias: self.b = Parameter(np.zeros((self.out_channels, 1))) else: self.b = None self.reset_parameters() self.reset_cache() def __str__(self): return f'Conv2D(in_channels={self.in_channels:d}, out_channels={self.out_channels:d}, ' \ f'kernel=({self.kernel_size[0]:d},{self.kernel_size[1]:d}), stride={self.stride:d}, ' \ f'padding={self.padding:d}, bias={self.b is not None})' def reset_parameters(self): n = self.in_channels for k in self.kernel_size: n *= k stdv = 1. / np.sqrt(n) self.K.data = np.random.uniform(-stdv, stdv, self.K.shape) if self.b is not None: self.b.data = np.random.uniform(-stdv, stdv, self.b.shape) def forward(self, X): # Compute output dimensions N, C, H, W = X.shape h_out = (H - self.kernel_size[0] + 2 * self.padding) / self.stride + 1 w_out = (W - self.kernel_size[1] + 2 * self.padding) / self.stride + 1 if not h_out.is_integer() or not w_out.is_integer(): raise Exception('Invalid output dimension!') h_out, w_out = int(h_out), int(w_out) # Reshape X_col = im2col_cython(X, self.kernel_size[0], self.kernel_size[1], padding=self.padding, stride=self.stride) # X_col = im2col_indices(X, self.kernel_size[0], self.kernel_size[1], padding=self.padding, stride=self.stride) K_col = self.K.data.reshape(self.out_channels, -1) # Convolve S = K_col @ X_col if self.b is not None: S += self.b.data # Reshape S = S.reshape(self.out_channels, h_out, w_out, N) S = S.transpose(3, 0, 1, 2) # Cache self.cache = dict(X_shape=X.shape, X_col=X_col) return S def backward(self, delta): X_shape, X_col = self.cache['X_shape'], self.cache['X_col'] N, C, H, W = X_shape # Bias gradient if self.b is not None: self.b.grad += np.sum(delta, axis=(0, 2, 3)).reshape(self.out_channels, -1) # Kernel gradient delta_reshaped = delta.transpose(1, 2, 3, 0).reshape(self.out_channels, -1) self.K.grad += (delta_reshaped @ X_col.T).reshape(self.K.shape) # Input gradient K_col = self.K.data.reshape(self.out_channels, -1) dX_col = K_col.T @ delta_reshaped dX = col2im_cython(dX_col, N, C, H, W, self.kernel_size[0], self.kernel_size[1], padding=self.padding, stride=self.stride) # dX = col2im_indices(dX_col, X_shape, self.kernel_size[0], self.kernel_size[1], padding=self.padding, stride=self.stride) self.reset_cache() return dX <file_sep>/utils/progress.py import os import sys import time class ProgressBar(object): def __init__(self, bar_width=None, title='', initial_progress=0, end_value=None, done_symbol='#', wait_symbol='-', keep_after_done=True): title += ": " if title != '' else '' self.title = title self._c = 7 # Lenth of the "[] xxx%" part of printed string if bar_width is None: if "DISPLAY" in os.environ: try: _, bar_width = os.popen('stty size', 'r').read().split() except: bar_width = 10 + len(title) + self._c else: bar_width = 10 + len(title) + self._c self._w = int(bar_width) - len(self.title) - self._c # Subtract constant parts of string length assert self._w >= 0, 'Title too long, bar width too narrow or terminal window not wide enough' self._b = self._w + len(self.title) + self._c # Number of left shifts to apply at end to reset to head of line self.end_value = end_value self.ds = done_symbol self.ws = wait_symbol self.initial_x = initial_progress self.keep_after_done = keep_after_done def start(self): """Creates a progress bar `width` chars long on the console and moves cursor back to beginning with BS character""" self.progress(self.initial_x) def progress(self, x): """Sets progress bar to a certain percentage x if `end_value` is `None`, otherwise, computes `x` as percentage of `end_value`.""" assert x <= 1 or self.end_value is not None and self.end_value >= x if self.end_value is not None: x = x / self.end_value y = int(x * self._w) sys.stdelta.write(self.title + "[" + self.ds * y + self.ws * (self._w - y) + "] {:3d}%".format(int(round(x * 100))) + chr(8) * self._b) sys.stdelta.flush() def end(self): """End of progress bar. Write full bar, then move to next line except if `keep_after_done` is false in which case the bar is replaced by spaces and the cursor reset.""" if self.keep_after_done: s = self.title + "[" + self.ds * self._w + "] {:3d}%".format(100) + "\n" else: s = ' ' * self._b + chr(8) * self._b sys.stdelta.write(s) sys.stdelta.flush() class PoolProgress(object): def __init__(self, pool, update_interval=3, **kwargs): """Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of workers **kwargs (dict): Additional arguments to ProgressBar update_interval (int, optional): Defaults to 3. Interval in seconds """ self.pb = ProgressBar(**kwargs) self.pool = pool self.update_interval = update_interval def track(self, job): """Track a job Args: job (multiprocessing.Pool.MapResult): The result object of the job to monitor """ task = self.pool._cache[job._job] n_tasks = task._number_left*task._chunksize self.pb.end_value = n_tasks self.pb.start() while task._number_left>0: self.pb.progress(n_tasks - task._number_left*task._chunksize) time.sleep(self.update_interval) self.pb.end() # Testing if __name__ == '__main__': sleep = 0.05 pb = ProgressBar(title='Test: 20s with 4s elapsed and some other stuff', initial_progress=4, end_value=100) pb.start() time.sleep(sleep) for i in range(5, 100): pb.progress(i) time.sleep(sleep) pb.end() pb = ProgressBar(title='Test: Removing bar after done', end_value=100, keep_after_done=False) pb.start() time.sleep(sleep) for i in range(100): pb.progress(i) time.sleep(sleep) pb.end() print("Here is some new information while we wait for a new bar to appear...") time.sleep(1) pb = ProgressBar(title='Test: Removing bar after done', end_value=100, keep_after_done=False) pb.start() time.sleep(sleep) for i in range(100): pb.progress(i) time.sleep(sleep) pb.end() print("Now we are done!") <file_sep>/nn/containers.py import operator from collections import OrderedDict from itertools import islice from .module import Module class Sequential(Module): """A sequential container. Modules will be added to it in the order they are passed in the constructor. Alternatively, an ordered dict of modules can also be passed in. """ def __init__(self, *args): super(Sequential, self).__init__() if len(args) == 1 and isinstance(args[0], OrderedDict): for key, module in args[0].items(): self.add_module(key, module) else: for idx, module in enumerate(args): self.add_module(str(idx), module) def _get_item_by_idx(self, iterator, idx): """Get the idx-th item of the iterator""" size = len(self) idx = operator.index(idx) if not -size <= idx < size: raise IndexError('index {} is out of range'.format(idx)) idx %= size return next(islice(iterator, idx, None)) def __getitem__(self, idx): if isinstance(idx, slice): return Sequential(OrderedDict(list(self._modules.items())[idx])) else: return self._get_item_by_idx(self._modules.values(), idx) def __setitem__(self, idx, module): key = self._get_item_by_idx(self._modules.keys(), idx) return setattr(self, key, module) def __delitem__(self, idx): if isinstance(idx, slice): for key in list(self._modules.keys())[idx]: delattr(self, key) else: key = self._get_item_by_idx(self._modules.keys(), idx) delattr(self, key) def __len__(self): return len(self._modules) def __dir__(self): keys = super(Sequential, self).__dir__() keys = [key for key in keys if not key.isdigit()] return keys def forward(self, x): for module in self._modules.values(): x = module.forward(x) return x def backward(self, delta): for module in reversed(self._modules.values()): delta = module.backward(delta) <file_sep>/grad_deriv.md # Derivation of layer gradients ## General notation * $\mathbf{z}$ | Symbol | Meaning | | ---------------- | ------------------------------------------------------------ | | $\mathbf{z}^{l}$ | Hidden pre-activation at layer $l$. | | $\mathbf{a}$^{l} | Activation at layer $l$, i.e. $\mathbf{a}^l = \varphi(\mathbf{z}^l)​$, typically element-wise. | | $\mathbf{y}$ | Network output. | | $\mathbf{x}$ | Network input. | ## Linear layer Forward propagation $$ \mathbf{z} = \mathbf{Wx} + \mathbf{b} $$ where $\mathbf{x}\in \mathbb{R}^D$, $\mathbf{z}\in\mathbb{R}^{H}$, $\mathbf{W}\in\mathbb{R}^{H\times D}$ and $\mathbf{b}\in\mathbb{R}^{H}$. Gradients $$ \begin{align} \frac{\partial\mathbf{z}}{\partial\mathbf{x}} &= \mathbf{W}^T\\ \frac{\partial\mathbf{z}}{\partial\mathbf{W}} &= \mathbf{x}\\ \frac{\partial\mathbf{z}}{\partial\mathbf{b}} &= \mathbf{I} \end{align} $$ Given $\delta_{out}=\frac{\partial L}{\partial\mathbf{z}}\in\mathbb{R}^{H}$ then $$ \frac{\partial L}{\partial\mathbf{x}} = \delta_{out} \mathbf{W} \in\mathbb{R}^{D} $$ ## Bilinear layer Forward propagation $$ \mathbf{z} = \mathbf{x}_1^T\mathbf{Wx}_2 + \mathbf{b} $$ where $\mathbf{x}_1\in \mathbb{R}^{D_1}$, $\mathbf{x}_2\in \mathbb{R}^{D_2}$, $\mathbf{z}\in\mathbb{R}^{H}$, $\mathbf{W}\in\mathbb{R}^{H \times D_1 \times D_2}$ and $\mathbf{b}\in\mathbb{R}^{H}$. Gradients $$ \begin{align} \frac{\partial\mathbf{z}}{\partial\mathbf{x}_1} &= \mathbf{Wx}_2 \in\mathbb{R}^{H\times D_1}\\ \frac{\partial\mathbf{z}}{\partial\mathbf{x}_2} &= \mathbf{W}^T\mathbf{x}_1\in\mathbb{R}^{H\times D_2}\\ \frac{\partial\mathbf{z}}{\partial\mathbf{W}} &= \mathbf{x}_1\mathbf{x}_2^T\in\mathbb{R}^{D_1\times D_2}\\ \frac{\partial\mathbf{z}}{\partial\mathbf{b}} &= \mathbf{I} \end{align} $$ Given $\delta_{out}=\frac{\partial L}{\partial\mathbf{z}}\in\mathbb{R}^{H}$ then $$ \frac{\partial L}{\partial\mathbf{x}_1} = \delta_{out} \mathbf{Wx}_2 \in\mathbb{R}^{H \times (H \times D_1 \times D_2) \times D_2} = \mathbb{R}^{D_2}\\ \frac{\partial L}{\partial\mathbf{x}_2} = \delta_{out} \mathbf{W}^T\mathbf{x}_1 \in\mathbb{R}^{H \times (H \times D_2 \times D_1) \times D_1} = \mathbb{R}^{D_1}\\ $$ https://github.com/pytorch/pytorch/blob/5bb13485b8484a37f9afad67582512cf53ed13cb/torch/nn/_functions/linear.py ## Recurrent layer Vanilla forward propagation $$ \mathbf{h}^{\langle t \rangle} = \text{tanh}\left(\mathbf{W}_{hx}\mathbf{x}^{\langle t \rangle} + \mathbf{W}_{hh}\mathbf{h}^{\langle t-1 \rangle}\right), \quad \text{for } t\in[0,T]\\ $$ Gradients $$ \begin{align} \frac{\partial\mathbf{h}^{\langle t \rangle}}{\partial\mathbf{x}} &= \mathbf{W}^T\\ \frac{\partial\mathbf{z}}{\partial\mathbf{W}} &= \mathbf{x}\\ \frac{\partial\mathbf{z}}{\partial\mathbf{b}} &= \mathbf{I} \end{align} $$ <file_sep>/nn/dropout.py import IPython import numpy as np from .module import Module class Dropout(Module): """Dropout layer which randomly sets activations to zero. Parameters ---------- p : float The probability of zeroing any activation. Must be smaller than 1 and larger than 0 """ def __init__(self, p=0.5): super(Dropout, self).__init__() self.p = p self.cache = dict(a=None) def __str__(self): return "Dropout({:.2f})".format(self.p) def forward(self, x): if self.training: mask = np.random.random(x.shape) > self.p scale = 1.0 / (1-self.p) a = x * mask * scale self.cache = dict(a=a) return a return x def backward(self, delta_in): delta_out = delta_in * self.cache['a'] return delta_out <file_sep>/evaluators/regression_evaluator.py import numpy as np from sklearn.metrics import confusion_matrix, roc_curve, roc_auc_score, precision_recall_curve, auc from .evaluator import Evaluator class RegressionEvaluator(Evaluator): def __init__(self, evaluation_metric='pearson'): """ Initialize a RegressionEvaluator. The RegressionEvaluator is an evaluator to be used for regression tasks. """ super().__init__(self, evaluation_metric) def update(self, probs=None, labels=None, loss=None): """ Update the tracked metrics: Recall/FPR and loss. Args: probs (list): List of predicted probabilities for the positive class for each example. labels (list): The labels corresponding to the predictions, as one-hot-encoded vectors. loss (list): List of the loss for each example for each GPU. """ # Update loss related values; remember to filter out infs and nans. loss = np.array(loss) filter_naninf = np.invert(np.isinf(loss) + np.isnan(loss)) example_loss_clean = loss[filter_naninf] self.loss_sum += np.sum(example_loss_clean) self.num_examples += len(example_loss_clean) self.loss = self.loss_sum / self.num_examples # # Decode predictions and sparse labels for WER computation. # self.probs = np.append(self.probs, np.concatenate(probs, axis=0)) # self.labels = np.append(self.labels, np.argmax(np.concatenate(labels, axis=0), axis=1)) def reset(self): """ Reset the tracked metrics. """ self.loss_sum = 0 self.num_examples = 0 self.loss = None self.probs = np.array(()) self.labels = np.array(())<file_sep>/evaluators/evaluator.py class Evaluator: def __init__(self, evaluation_metric): """Initialize the evaluator """ self.evaluation_metric_name = evaluation_metric @property def evaluation_metric(self): return getattr(self, self.evaluation_metric_name) def update(self, predictions=None, labels=None, loss=None): raise NotImplementedError def reset(self): raise NotImplementedError <file_sep>/utils/trainers.py import os import pickle import numpy as np import matplotlib.pyplot as plt import progressbar import IPython from .utils import onehot class Trainer(): """A Trainer encapsulates all the logic necessary for training classification models. The Solver performs stochastic gradient descent using different update rules defined in optim.py. The solver accepts both training and validataion data and labels so it can periodically check classification accuracy on both training and validation data to watch out for overfitting. To train a model, first construct a Solver instance, passing the model, dataset, optimizer, loss and various options (number of epochs, checkpoints, etc.) to the constructor. Then call the train() method to run the optimization procedure and train the model. After the train() method returns, the model will contain the parameters that performed best on the validation set over the course of training. In addition, the instance variable solver.train_loss_history will contain a list of all losses encountered during training and solver.train_acc_history will contain the associated classification accuracies. """ def __init__(self, model, optimizer, loss, train_loader, val_loader, train_evaluator, val_evaluator, **kwargs): """Construct a new Solver instance. Parameters ---------- model: nn.Module The model to train optimizer: optim.Optimizer The optimizer from optim.py to use. loss: nn.Module The loss criterion to optimize. train_loader: torch.utils.data.DataLoader torch DataLoader constructed on the wanted training set. val_loader: torch.utils.data.DataLoader torch DataLoader constructed on the corresponding validation set. train_evaluator: eval.Evaluator val_evaluator: eval.Evaluator lr_scheduler: optim.LRScheduler A scheduler for learning rate decay. max_epochs: int The number of epochs to run for during training. max_epochs_no_improvement: int The number of epochs without improvement on the validation set to tolerate before ending training. Defaults to None. print_every: int Training losses will be printed every print_every iterations. verbose: bool If set to false then no output will be printed during training. checkpoint_dir: str If not None, then save model checkpoints here every epoch. """ self.model = model self.train_loader = train_loader self.val_loader = val_loader self.optimizer = optimizer self.loss = loss self.train_evaluator = train_evaluator self.val_evaluator = val_evaluator # Unpack keyword arguments self.epoch = kwargs.pop('epoch', 0) self.epochs_no_improvement = kwargs.pop('epochs_no_improvement', 0) self.best_val_metric = kwargs.pop('epochs_no_improvement', -np.inf) self.lr_scheduler = kwargs.pop('lr_scheduler', None) self.max_epochs = kwargs.pop('max_epochs', 10) self.max_epochs_no_improvement = kwargs.pop('max_epochs_no_improvement', self.max_epochs) self.checkpoint_dir = kwargs.pop('checkpoint_dir', None) self.num_classes = np.unique(self.train_loader.dataset.train_labels).shape[0] # Throw an error if there are extra keyword arguments if kwargs: extra = ', '.join('"%s"' % k for k in list(kwargs.keys())) raise ValueError('Unrecognized arguments %s' % extra) def reset(self): self.epoch = 0 self.epochs_no_improvement = 0 self.best_val_metric = -np.inf def step(self, pbar): raise NotImplementedError def validate(self, pbar): raise NotImplementedError def train(self): """Run optimization to train the model. """ while self.epoch < self.max_epochs and self.epochs_no_improvement < self.max_epochs_no_improvement: print(f'Epoch {self.epoch:3d} | lr={self.optimizer.lr:4.5f}') # Progressbar widgets = [progressbar.FormatLabel(f'Epoch {self.epoch:3d} | Batch '), progressbar.SimpleProgress(), ' | ', progressbar.Percentage(), ' | ', progressbar.FormatLabel(f'Loss N/A'), ' | ', progressbar.Timer(), ' | ', progressbar.ETA()] pbar_train = progressbar.ProgressBar(widgets=widgets) pbar_val = progressbar.ProgressBar(widgets=widgets) # Execute training on training set self.step(pbar_train) # Validate model on validation set self.validate(pbar_val) # Learning rate scheduler if self.lr_scheduler is not None: self.lr_scheduler.step() print(f'Epoch {self.epoch:3d} | Loss (T/V) {self.train_evaluator.loss:5.4f} / {self.val_evaluator.loss:5.4f} | ' \ f'{self.train_evaluator.evaluation_metric_name.capitalize()} (T/V) {self.train_evaluator.evaluation_metric:5.4f} / {self.val_evaluator.evaluation_metric:5.4f}') # Keep track of the best model if self.val_evaluator.evaluation_metric > self.best_val_metric: self.best_val_metric = self.val_evaluator.evaluation_metric self._save_checkpoint() self.epochs_no_improvement = 0 else: self.epochs_no_improvement += 1 # Update plots self._update_plots() self.epoch += 1 def _update_plots(self): for name, evaluator in zip(['train', 'val'], [self.train_evaluator, self.val_evaluator]): # Batch level for k in evaluator.history.keys(): fig, ax = plt.subplots(figsize=(16, 9)) evaluator.history[k].plot(ax=ax) ax.set_xlabel('Batch') ax.set_ylabel(k) fig.savefig(os.path.join(self.checkpoint_dir, name + '_' + k + '.pdf'), bbox_inches='tight') plt.close(fig) # # Epoch level # for k in evaluator.history.keys(): # fig, ax = plt.subplots(figsize=(16, 9)) # evaluator.history[k].plot(ax=ax) # ax.set_xlabel('Batch') # ax.set_ylabel(k) # fig.savefig(os.path.join(self.checkpoint_dir, name + '_' + k + '.pdf'), bbox_inches='tight') # plt.close(fig) def _save_checkpoint(self): if self.checkpoint_dir is None: return checkpoint = { 'model': self.model, 'train_loader': self.train_loader, 'val_loader': self.val_loader, 'optimizer': self.optimizer, 'lr_scheduler': self.lr_scheduler, 'train_evaluator': self.train_evaluator, 'val_evaluator': self.val_evaluator, 'epoch': self.epoch, 'epochs_no_improvement': self.epochs_no_improvement, 'num_classes': self.num_classes, } filename = os.path.join(self.checkpoint_dir, f'checkpoint_{id(self)}.pkl') print('Saving checkpoint to "{:s}"'.format(filename)) with open(filename, 'wb') as f: pickle.dump(checkpoint, f) class ClassificationTrainer(Trainer): """A Trainer encapsulates all the logic necessary for training classification models. The Solver performs stochastic gradient descent using different update rules defined in optim.py. The solver accepts both training and validataion data and labels so it can periodically check classification accuracy on both training and validation data to watch out for overfitting. To train a model, first construct a Solver instance, passing the model, dataset, optimizer, loss and various options (number of epochs, checkpoints, etc.) to the constructor. Then call the train() method to run the optimization procedure and train the model. After the train() method returns, the model will contain the parameters that performed best on the validation set over the course of training. In addition, the instance variable solver.train_loss_history will contain a list of all losses encountered during training and solver.train_acc_history will contain the associated classification accuracies. """ def __init__(self, model, optimizer, loss, train_loader, val_loader, train_evaluator, val_evaluator, **kwargs): super().__init__(model, optimizer, loss, train_loader, val_loader, train_evaluator, val_evaluator, **kwargs) def step(self, pbar): """Make a single gradient update. This is called by train() """ self.model.train() self.train_evaluator.reset() for data, targets in pbar(self.train_loader): data, targets = data.numpy(), targets.numpy() targets = onehot(targets, self.num_classes) # Forward pass, compute loss scores = self.model.forward(data) loss = self.loss.forward(scores, targets) # Backward pass, compute gradient self.optimizer.zero_grad() delta = self.loss.backward(scores, targets) self.model.backward(delta) # Take step with optimizer self.optimizer.step() # Update evaluator self.train_evaluator.update(scores, targets, loss) pbar.widgets[5] = progressbar.FormatLabel(f'Loss (E/B) {self.train_evaluator.loss:4.2f} / {loss.mean():4.2f}') def validate(self, pbar): """Validates the model on the validation set. Returns ------- accuracy: float Scalar giving the fraction of instances that were correctly classified by the model. loss: float Computed average loss on the validation set. """ self.model.eval() self.val_evaluator.reset() for data, targets in pbar(self.val_loader): data, targets = data.numpy(), targets.numpy() targets = onehot(targets, self.num_classes) scores = self.model.forward(data) loss = self.loss.forward(scores, targets) self.val_evaluator.update(scores, targets, loss) pbar.widgets[5] = progressbar.FormatLabel(f'Loss (E/B) {self.val_evaluator.loss:4.2f} / {loss.mean():4.2f}') <file_sep>/nn/activation.py import numpy as np from .module import Module class Activation(Module): def update_cache(self, value): self.cache['value'] = value class Sigmoid(Activation): def __init__(self): """Sigmoid """ super().__init__() self.reset_cache() def __str__(self): return "Sigmoid()" def forward(self, x): a = 1.0 / (1 + np.exp(-x)) self.update_cache(a) return a def backward(self, din, cache=None): a = self.cache['value'] if cache is None else cache return a * (1 - a) * din class Tanh(Activation): def __init__(self): """Tanh """ super().__init__() self.reset_cache() def __str__(self): return "Tanh()" def forward(self, x): a = np.tanh(x) self.update_cache(a) return a def backward(self, din, cache=None): a = self.cache['value'] if cache is None else cache return (1 - a ** 2) * din class ReLU(Activation): def __init__(self): """ReLU """ super().__init__() self.reset_cache() def __str__(self): return "ReLU()" def forward(self, x): a = np.maximum(0, x) self.update_cache(a) return a def backward(self, din, cache=None): a = self.cache['value'] if cache is None else cache return din * (a > 0).astype(a.dtype) class Softplus(Activation): def __init__(self): """Softplus """ super().__init__() self.reset_cache() def __str__(self): return "Softplus()" def forward(self, x): g = np.exp(x) + 1 self.update_cache(g) return np.log(g) def backward(self, din, cache=None): g = self.cache['value'] if cache is None else cache return din * 1 - g ** (-1) class Softmax(Activation): def __init__(self): """Softmax """ super().__init__() self.reset_cache() def __str__(self): return "Softmax()" def forward(self, x): x_shifted = x - np.max(x) x_exp = np.exp(x_shifted) a = x_exp / x_exp.sum(axis=-1, keepdims=True) return a def backward(self, din, cache=None): return din <file_sep>/nn/__init__.py from .activation import * from .batchnorm import * from .dropout import * from .linear import * from .convolution import * from .pooling import * from .rnn import * from .reshape import * from .loss import * from .containers import Sequential from .module import Module from .parameter import Parameter <file_sep>/evaluators/__init__.py from .binary_evaluator import BinaryEvaluator from .multiclass_evaluator import MulticlassEvaluator from .regression_evaluator import RegressionEvaluator <file_sep>/examples/mnist_fnn.py import os from context import nn, optim, utils, evaluators from utils.constants import SAVE_DIR from utils.utils import get_loaders class FNNClassifier(nn.Module): """Feedforward neural network classifier. Parameters ---------- in_features : int The number of input features. out_classes : int The number of output classes. hidden_dims : list List of the dimensions of the hidden layers. Also defines the depth of the network. activation : nn.Module The activation function to use. batchnorm : bool Whether or not to use batch normalization layers. dropout : bool or float Whether or not to include dropout and the dropout probability to use. """ def __init__(self, in_features, out_classes, hidden_dims=[256, 128, 64], activation=nn.ReLU, batchnorm=False, dropout=False): super(FNNClassifier, self).__init__() dims = [in_features, *hidden_dims, out_classes] for i in range(len(dims) - 1): if batchnorm: self.add_module('batchnorm_' + str(i), nn.BatchNorm1D(dims[i])) if dropout: self.add_module('dropout_' + str(i), nn.Dropout(p=dropout)) if i > 0: self.add_module('activation_' + str(i), activation()) self.add_module('linear_' + str(i), nn.Linear(dims[i], dims[i+1], bias=True)) self.add_module('activation_' + str(i+1), nn.Softmax()) def forward(self, x): x = x.reshape(x.shape[0], -1) for module in self._modules.values(): x = module.forward(x) return x def backward(self, delta): for module in reversed(self._modules.values()): delta = module.backward(delta) if __name__ == '__main__': # Dataset dataset_name = 'MNIST' batch_size = 250 max_epochs = 20 max_epochs_no_improvement = 10 train_loader, val_loader = get_loaders(dataset_name, batch_size) # Checkpoint dir checkpoint_dir = os.path.join(SAVE_DIR, dataset_name) if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) # Model classifier = FNNClassifier(28 * 28, 10, hidden_dims=[128, 64, 32, 16], activation=nn.ReLU, batchnorm=True, dropout=0.2) classifier.summarize() # Optimizer optimizer = optim.Adam(classifier.parameters, lr=0.001, l1_weight_decay=0, l2_weight_decay=0) # optimizer = optim.SGD(classifier.parameters, lr=0.001, momentum=0.9, nesterov=True, l1_weight_decay=0, l2_weight_decay=0) # Loss loss = nn.CrossEntropyLoss() # Learning rate schedule lr_scheduler = None # optim.CosineAnnealingLR(optimizer, T_max=5, decay_eta_max_half_time=1) # Evaluators train_evaluator = evaluators.MulticlassEvaluator(n_classes=10) val_evaluator = evaluators.MulticlassEvaluator(n_classes=10) # Trainer trainer = utils.trainers.ClassificationTrainer(classifier, optimizer, loss, train_loader, val_loader, train_evaluator, val_evaluator, lr_scheduler=lr_scheduler, max_epochs=max_epochs, max_epochs_no_improvement=max_epochs_no_improvement, checkpoint_dir=checkpoint_dir) trainer.train()
fa43b60d39eb283fbd63b7cff9cff9c8a4f4fa73
[ "Markdown", "Python" ]
32
Python
JakobHavtorn/nn
30d37a8dd0fca0a7d9a1ed0553b2a3346dfc53e3
c990398d0c426d0382aa1e73df539674d972cebe
refs/heads/master
<repo_name>sahuvicky1993/cpp_practice<file_sep>/recur_str_last_ocur.c #include<stdio.h> static int count; char* find_ocur(char*p,char ch){ static char*q=NULL; if(*p) { if(*p==ch){ count++; q=p; } return find_ocur(p+1,ch); } else return q; } main(){ char s[]="VivekKumarSahu"; /* Find last ocurrance of 'a' in the given string*/ /* Also prnt no of time 'a' present in the string */ char*ret=find_ocur(s,'a'); printf("last occurance:%s and no of times %c is present is:%d\n",ret==NULL?"NULL":ret,'a',count); } <file_sep>/replaceChar_find_first_of.cpp // C++ program to demonstrate // the use of std::find_first_of #include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { // Defining first container std::string str ("I am a good boy"); std::size_t found = str.find_first_of("axy"); while (found!=std::string::npos) { std::cout<<found<<" "<<str<<'\n'; str[found]='*'; found=str.find_first_of("axy",found+1); } std::cout << str << '\n'; return 0; } /* 2 I am a good boy 5 I *m a good boy 14 I *m * good boy I *m * good bo* */ <file_sep>/array.c #include<stdio.h> main(){ int a[32],b[32]; int i,j=0,k=16; for(i=0;i<=31;i++) printf("%d ",a[i]); printf("\n"); for(i=0;i<=31;i++) { if(i%2) b[j++]=a[i]; else b[k++]=a[i]; } for(i=0;i<=31;i++) printf("%d ",b[i]); printf("\n"); } <file_sep>/transpose1D.c #include<stdio.h> main(){ int a[]={1,2,3,4,5,6,7,8,9}; int i,j,temp; for(i=0;i<3;i++) for(j=0;j<3;j++){ if(i<j){ temp=*(a+3*i+j); *(a+3*i+j)=*(a+3*j+i); *(a+3*j+i)=temp; } } for(i=0;i<9;i++) printf("%d ",a[i]); printf("\n"); } <file_sep>/3rdMax.c #include<stdio.h> #include<limits.h> main(){ int a[32],b[32]; int i,j=0,k=16; for(i=0;i<=31;i++) printf("%d ",a[i]); printf("\n"); int f=a[0],s=INT_MIN,t=INT_MIN; for(i=1;i<=31;i++){ if(a[i]>f) { t=s; s=f; f=a[i]; } else if(a[i]>s) { t=s; s=a[i]; } else if(a[i]>t) { t=a[i]; } } printf("%d %d %d \n",f,s,t); } <file_sep>/QuickSort.c #include <stdio.h> int partition(int arr[],int l, int h); void swap(int*,int*); void quickSort(int arr[],int l,int h); void PRINT(int arr[]){ for(int i=0;i<(sizeof(arr)/sizeof(int));i++) printf("%d ",arr[i]); printf("\n"); } void quickSort(int arr[],int l,int h){ PRINT(arr); if(l<h){ int part = partition(arr,l,h); quickSort(arr,l,part); quickSort(arr,part+1,h); } } int partition(int arr[],int l, int h){ int pivot=arr[l]; int j=h,i=l; while(i<j){ do{ i++; }while(arr[i]<=pivot); do{ j--; }while(arr[i]>=pivot); if(i<j) swap(&arr[i],&arr[j]); } return j; } void swap(int *p1,int*p2){ int temp; temp =*p1; *p1=*p2; *p2 = temp; } int main() { int arr[]={10,16,2,1,55,6,7,3,98,45,9}; PRINT(arr); quickSort(arr,0,(sizeof(arr)/sizeof(int))-1); PRINT(arr); return 0; } <file_sep>/maxRecur.c #include<stdio.h> int maxValue(int*p,int i){ if(i){ } } main(){ int a[32],b[32]; int i,j=0,k=16; for(i=0;i<=31;i++) printf("%d ",a[i]); printf("\n"); printf("%d\n",maxValue(a,32)); } <file_sep>/pack.c #include<stdio.h> typedef unsigned char U8; typedef unsigned short int U16; typedef unsigned int U32; U32 pack(U16 id,U8 age,U8 gen,U8 ms,U8 it) { U8 temp=0; if(gen) temp|=1; if(ms) temp|=1<<1; temp|=1<<(it+2); return (U32)((U32)id<<16 | (U32) age<<8 | temp); } void unpack(U32 data){ U16 id=0;U8 age=0;U8 gen=0;U8 ms=0;U8 it=0; //U8 c=0; id=(data>>16)& 0xffff; age=(data>>8)& 0x00ff; gen=data&1; if(data&(1<<1)) ms=1; U8 temp=(data)&0x000000ff; temp=temp>>2; while(temp){ temp>>=1; it++; } printf("%u %hu %hu %hu %hu\n",id,age,gen,ms,it); } main(){ U32 data; printf("%u\n",data=pack(6545,24,1,1,3)); //printf("%d\n",pack(id,age,gen,ms,it)); unpack(data); } <file_sep>/README.md + google.c is a google interview Qn: Given a string we have to find first ocuurance of duplicate char eg: "ABCAB" return A "ACBBCA" return B + <file_sep>/2d_vector.cpp #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n,q,x; cin>>n>>q; vector<vector<int>>a(n); for(int i=0;i<n;i++){ //x is no of elemnt in the arr cin>>x; a[i].resize(x); for(int j=0;j<x;j++){ cin>>a[i][j]; } } //get the quiries int r,c; for(int i=0;i<q;i++){ cin>>r>>c; cout<<a[r][c]<<endl; } return 0; } /* i/p 2 2 -> n(no of arrays),q(no of quries) 3 1 5 4 (1st arrays of size 3, followed by elemnet) 5 1 2 8 9 3 0 1 (0th array print element at index 1) 1 3 o/p 5 9 */ <file_sep>/even_odd.c #include<stdio.h> main(){ int num=2863311530;//Binay representation is 101010....10 /* after arrangement num should be like 11111.....00000 */ /* which represent integer 4294901760 */ int temp=0,j=16,k=0,i; for(i=0;i<32;i++) { if(i%2 && (num&(1<<i))){ temp |=1<<j; j++; } else { if(num&(1<<i)) temp |=1<<k; k++; } } printf("%u\n",temp); } <file_sep>/trans1D.c #include<stdio.h> #include<limits.h> main(){ char a[9],b[9]; int i,j=3,k,l=0; for(i=0;i<=9;i++) printf("%d ",a[i]); printf("\n"); for(k=0;k<3;k++) { i=k; while(j--){ b[l++]=a[i];i+=3; } j=3; } for(i=0;i<=9;i++) printf("%d ",b[i]); printf("\n"); } <file_sep>/google.c #include<stdio.h> char firstOcurrance(char*p) { int i; char *a=calloc(sizeof(char),255); for(i=0;p[i];i++){ a[p[i]]++; if(a[p[i]]>=2) return p[i]; }//for } main() { printf("%c\n",firstOcurrance("AD,,DBCBA")); }
e3adefe18331dd42a30747f60fe8c9272257d60a
[ "Markdown", "C", "C++" ]
13
C
sahuvicky1993/cpp_practice
0004af5daaeef3ece6b2ba7b6e54ad1ab9d47efe
ec98f9687852e38c86866f2a119048dd88f22dc2
refs/heads/main
<file_sep>import styled from 'styled-components'; export const Container = styled.form` h2 { color: var(--text-title); font-size: 1.5rem; margin-bottom: 2rem; } `; <file_sep>using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; using TrendContext.Domain.Data.Interfaces; namespace TrendContext.Domain.Data { public class UnitOfWork : IUnitOfWork { private readonly InMemoryAppContext appContext; public UnitOfWork(InMemoryAppContext appContext) { this.appContext = appContext; } public void BeginTransaction() { // Method intentionally left empty. } public async Task Commit() { await appContext.SaveChangesAsync(); } public void Rollback() { // Method intentionally left empty. } } } <file_sep>import styled from 'styled-components'; export const Container = styled.button` width: 100%; padding: 0 1.5rem; height: 4rem; background: var(--blue-button); color: #fff; border-radius: 0.25rem; border: 0; font-size: 1rem; margin-top: 1.5rem; font-weight: 600; transition: filter 0.2s; &:hover { filter: brightness(0.9); } `; <file_sep>using System; using System.Threading.Tasks; using TrendContext.Domain.Entities; using TrendContext.Shared.Repository; namespace TrendContext.Domain.Repositories.Interfaces { public interface IUserRepository : IRepository<User> { Task<bool> CheckCpfAlreadyExistsAsync(string cpf); Task<User> GetByCPFAsync(string cpf); } } <file_sep>export const numberMask = (value: string) => { return value .replace(/\D/g, '') // substitui qualquer caracter que nao seja numero por nada .replace(/(\d{7})\d+?$/, '$1'); }; <file_sep>using MediatR; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Rewrite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using System; using System.IO; using System.Reflection; using System.Text; using TrendContext.Domain.Data; using TrendContext.Domain.Data.Interfaces; using TrendContext.Domain.Entities; using TrendContext.Domain.Repositories.Implementations; using TrendContext.Domain.Repositories.Interfaces; using TrendContext.Domain.Services; using TrendContext.Shared.Config; using TrendContext.Shared.Repository; namespace TrendContext.WebApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<InMemoryAppContext>(opt => opt.UseInMemoryDatabase(databaseName: "TrendContextTest")); services.AddTransient(typeof(IRepository<>), typeof(Repository<>)); services.AddTransient<ITrendRepository, TrendRepository>(); services.AddTransient<IOrderRepository, OrderRepository>(); services.AddTransient<IUserRepository, UserRepository>(); services.AddTransient<IUnitOfWork, UnitOfWork>(); services.AddTransient<ITokenService, TokenService>(); services.AddMediatR(AppDomain.CurrentDomain.Load("TrendContext.Domain")); services.AddCors(); var key = Encoding.ASCII.GetBytes(Settings.Secret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, }; }); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Trends API v1", Version = "v1", Description = "API to manager trends", Contact = new OpenApiContact { Name = "<NAME>", Url = new Uri("https://github.com/jefferson-luis-nascimento"), } }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { In = ParameterLocation.Header, Description = "Please insert JWT with Bearer into field", Name = "Authorization", Type = SecuritySchemeType.ApiKey }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, Array.Empty<string>() } }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } var options = new DbContextOptionsBuilder<InMemoryAppContext>() .UseInMemoryDatabase(databaseName: "TrendContextTest") .Options; using (var context = new InMemoryAppContext(options)) { InitialData.AddDefaultData(context); } app.UseHttpsRedirection(); app.UseRouting(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Trends API v1"); }); var option = new RewriteOptions(); option.AddRedirect("^$", "swagger"); app.UseRewriter(option); app.UseCors(builder => { builder.WithOrigins("http://localhost:3000"); builder.AllowAnyHeader(); builder.WithExposedHeaders("Token-Expired"); builder.AllowAnyMethod(); builder.AllowCredentials(); builder.Build(); }); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } } <file_sep>using Flunt.Notifications; using MediatR; using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; using TrendContext.Domain.Data.Interfaces; using TrendContext.Domain.Entities; using TrendContext.Domain.Repositories.Interfaces; namespace TrendContext.Domain.Handlers { public class CreateTrendHandler : Notifiable<Notification>, IRequestHandler<CreateTrendRequest, CommandResponse<CreateTrendResponse>> { private readonly ITrendRepository repository; private readonly IUnitOfWork unitOfWork; private readonly ILogger<CreateTrendHandler> logger; public CreateTrendHandler(ITrendRepository repository, IUnitOfWork unitOfWork, ILogger<CreateTrendHandler> logger) { this.repository = repository; this.unitOfWork = unitOfWork; this.logger = logger; } public async Task<CommandResponse<CreateTrendResponse>> Handle(CreateTrendRequest request, CancellationToken cancellationToken) { try { request.Validate(); if(!request.IsValid) { return new CommandResponse<CreateTrendResponse>(false, 400, string.Join(Environment.NewLine, request.Notifications.Select(x => x.Message)), null); } var existTrend = await repository.GetBySymbol(request.Symbol); if (existTrend != null) { return new CommandResponse<CreateTrendResponse>(false, 400, "Already exists this Trend.", null); } var trend = new Trend { Symbol = request.Symbol, CurrentPrice = request.CurrentPrice, }; unitOfWork.BeginTransaction(); repository.Create(trend); await unitOfWork.Commit(); return new CommandResponse<CreateTrendResponse>(true, 201, string.Empty, new CreateTrendResponse { Id = trend.Id, Symbol = trend.Symbol, CurrentPrice = trend.CurrentPrice, }); } catch (Exception ex) { logger.LogError(ex, ex.Message); unitOfWork.Rollback(); return new CommandResponse<CreateTrendResponse>(false, 500, "Internal Server Error", null); } } } } <file_sep>using System.Threading.Tasks; namespace TrendContext.Domain.Data.Interfaces { public interface IUnitOfWork { void BeginTransaction(); Task Commit(); void Rollback(); } } <file_sep>using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Data; using TrendContext.Domain.Data.Interfaces; using TrendContext.Domain.Entities; using TrendContext.Domain.Handlers; using TrendContext.Domain.Repositories.Implementations; using TrendContext.Domain.Repositories.Interfaces; using TrendContext.Domain.Services; using TrendContext.Shared.Repository; namespace TrendContext.Tests.Handlers { [TestClass] public class CreateSessionHandlerTest { private InMemoryAppContext appContext; private ITokenService tokenService; private IUserRepository userRepository; private ILogger<CreateSessionHandler> logger; private void InitialDependencies(string nomeBanco) { var options = new DbContextOptionsBuilder<InMemoryAppContext>() .UseInMemoryDatabase(databaseName: nomeBanco) .Options; appContext = new InMemoryAppContext(options); userRepository = new UserRepository(appContext); tokenService = new TokenService(); logger = new Logger<CreateSessionHandler>(new LoggerFactory()); InitialData.AddDefaultData(appContext); } [TestMethod] public async Task ShouldBeAbleToCreateSession() { InitialDependencies("ShouldBeAbleToCreateSession"); var command = new CreateSessionRequest { CPF = "69686332804", }; var handler = new CreateSessionHandler(userRepository, tokenService, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(result.Success); Assert.IsTrue(result.StatusCode == 201); Assert.IsTrue(string.IsNullOrWhiteSpace(result.Message)); Assert.IsTrue(result.Payload != null); Assert.IsTrue(!string.IsNullOrWhiteSpace(result.Payload.Token)); } [TestMethod] public async Task ShouldNotBeAbleToCreateSessionCpfInvalid() { InitialDependencies("ShouldNotBeAbleToCreateSessionCpfInvalid"); var command = new CreateSessionRequest { CPF = "69686332804987", }; var handler = new CreateSessionHandler(userRepository, tokenService, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 400); Assert.IsTrue(result.Message.Contains("CPF invalid.")); Assert.IsTrue(result.Payload == null); } [TestMethod] public async Task ShouldNotBeAbleToCreateSessionUserNotFound() { InitialDependencies("ShouldNotBeAbleToCreateSessionUserNotFound"); var command = new CreateSessionRequest { CPF = "00000000191", }; var handler = new CreateSessionHandler(userRepository, tokenService, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 400); Assert.IsTrue(result.Message.Contains("User not found.")); Assert.IsTrue(result.Payload == null); } } } <file_sep>using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; using TrendContext.Domain.Data; using TrendContext.Domain.Entities; using TrendContext.Domain.Repositories.Interfaces; namespace TrendContext.Domain.Repositories.Implementations { public class UserRepository : Repository<User>, IUserRepository { public UserRepository(InMemoryAppContext appContext) : base (appContext) { } public async Task<bool> CheckCpfAlreadyExistsAsync(string cpf) { return await entities.AnyAsync(user => user.CPF == cpf); } public async Task<User> GetByCPFAsync(string cpf) { return await entities.FirstOrDefaultAsync(user => user.CPF == cpf); } } } <file_sep>using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Data; using TrendContext.Domain.Data.Interfaces; using TrendContext.Domain.Entities; using TrendContext.Domain.Handlers; using TrendContext.Domain.Repositories.Implementations; using TrendContext.Domain.Repositories.Interfaces; using TrendContext.Shared.Repository; namespace TrendContext.Tests.Handlers { [TestClass] public class CreateTrendHandlerTest { private InMemoryAppContext appContext; private ITrendRepository trendRepository; private IUnitOfWork unitOfWork; private ILogger<CreateTrendHandler> logger; private void InitialDependencies(string nomeBanco) { var options = new DbContextOptionsBuilder<InMemoryAppContext>() .UseInMemoryDatabase(databaseName: nomeBanco) .Options; appContext = new InMemoryAppContext(options); trendRepository = new TrendRepository(appContext); unitOfWork = new UnitOfWork(appContext); logger = new Logger<CreateTrendHandler>(new LoggerFactory()); InitialData.AddDefaultData(appContext); } [TestMethod] public async Task ShouldBeAbleToCreateTrend() { InitialDependencies("ShouldBeAbleToCreateTrend"); var command = new CreateTrendRequest { Symbol = "PETR3", CurrentPrice = 36.15M, }; var handler = new CreateTrendHandler(trendRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(result.Success); Assert.IsTrue(result.StatusCode == 201); Assert.IsTrue(string.IsNullOrWhiteSpace(result.Message)); Assert.IsTrue(result.Payload != null); } [TestMethod] public async Task ShouldNotBeAbleToCreateTrendEmpty() { InitialDependencies("ShouldNotBeAbleToCreateTrendEmpty"); var command = new CreateTrendRequest { Symbol = string.Empty, CurrentPrice = 36.15M, }; var handler = new CreateTrendHandler(trendRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 400); Assert.IsTrue(result.Message.Contains("Symbol is required.")); Assert.IsTrue(result.Payload == null); } [TestMethod] public async Task ShouldNotBeAbleToCreateTrendInvalid() { InitialDependencies("ShouldNotBeAbleToCreateTrendInvalid"); var command = new CreateTrendRequest { Symbol = "PETR378978789", CurrentPrice = 36.15M, }; var handler = new CreateTrendHandler(trendRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 400); Assert.IsTrue(result.Message.Contains("Symbol is invalid.")); Assert.IsTrue(result.Payload == null); } [TestMethod] public async Task ShouldNotBeAbleToCreateTrendExists() { InitialDependencies("ShouldNotBeAbleToCreateTrendExists"); var command = new CreateTrendRequest { Symbol = "PETR4", CurrentPrice = 36.15M, }; var handler = new CreateTrendHandler(trendRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 400); Assert.IsTrue(result.Message.Contains("Already exists this Trend.")); Assert.IsTrue(result.Payload == null); } [TestMethod] public async Task ShouldNotBeAbleToCreateCurrentPriceZero() { InitialDependencies("ShouldNotBeAbleToCreateCurrentPriceZero"); var command = new CreateTrendRequest { Symbol = "PETR3", CurrentPrice = 0M, }; var handler = new CreateTrendHandler(trendRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 400); Assert.IsTrue(result.Message.Contains("CurrentPrice is invalid.")); Assert.IsTrue(result.Payload == null); } } } <file_sep>using MediatR; using System; using System.Collections.Generic; using TrendContext.Domain.Commands.Responses; namespace TrendContext.Domain.Commands.Requests { public class GetByIdUserRequest : IRequest<CommandResponse<GetByIdUserResponse>> { public Guid Id { get; set; } } } <file_sep>using Newtonsoft.Json; namespace TrendContext.Domain.Commands.Responses { public class GetAllTrendsResponse { [JsonProperty("symbol")] public string Symbol { get; set; } [JsonProperty("currentPrice")] public decimal CurrentPrice { get; set; } } } <file_sep>using System; using TrendContext.Shared.Entities; namespace TrendContext.Domain.Entities { public class Order : Entity { public Guid UserId { get; set; } public Guid TrendId { get; set; } public int Amount { get; set; } public decimal Total { get; set; } public virtual User User { get; set; } public virtual Trend Trend { get; set; } public static decimal CalculateTotalOrder(decimal currentPrice, decimal amount) { return Math.Round(currentPrice * amount, 2, MidpointRounding.AwayFromZero); } } } <file_sep>using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Data; using TrendContext.Domain.Data.Interfaces; using TrendContext.Domain.Entities; using TrendContext.Domain.Handlers; using TrendContext.Domain.Repositories.Implementations; using TrendContext.Domain.Repositories.Interfaces; using TrendContext.Shared.Repository; namespace TrendContext.Tests.Handlers { [TestClass] public class CreateOrderHandlerTest { private InMemoryAppContext appContext; private IRepository<Order> orderRepository; private ITrendRepository trendRepository; private IUserRepository userRepository; private IUnitOfWork unitOfWork; private ILogger<CreateOrderHandler> logger; private void InitialDependencies(string nomeBanco) { var options = new DbContextOptionsBuilder<InMemoryAppContext>() .UseInMemoryDatabase(databaseName: nomeBanco) .Options; appContext = new InMemoryAppContext(options); orderRepository = new Repository<Order>(appContext); trendRepository = new TrendRepository(appContext); userRepository = new UserRepository(appContext); unitOfWork = new UnitOfWork(appContext); logger = new Logger<CreateOrderHandler>(new LoggerFactory()); InitialData.AddDefaultData(appContext); } [TestMethod] public void ShouldBeAbleToCalculateTotalOrder() { var expect = 100M; var result = Order.CalculateTotalOrder(50, 2); Assert.IsTrue(expect == result); expect = 45.39M; result = Order.CalculateTotalOrder(15.13M, 3); Assert.IsTrue(expect == result); } [TestMethod] public async Task ShouldBeAbleToCreateOrder() { InitialDependencies("ShouldBeAbleToCreateOrder"); var command = new CreateOrderRequest { CPF = "69686332804", Symbol = "PETR4", Amount = 4, }; var handler = new CreateOrderHandler(orderRepository, trendRepository, userRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(result.Success); Assert.IsTrue(result.StatusCode == 201); Assert.IsTrue(string.IsNullOrWhiteSpace(result.Message)); Assert.IsTrue(result.Payload != null); } [TestMethod] public async Task ShouldBeAbleNotCreateOrderCpfInvalid() { InitialDependencies("ShouldBeAbleNotCreateOrderCpfInvalid"); var command = new CreateOrderRequest { CPF = "69686332804321548", Symbol = "PETR4", Amount = 4, }; var handler = new CreateOrderHandler(orderRepository, trendRepository, userRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 400); Assert.IsTrue(!string.IsNullOrWhiteSpace(result.Message)); Assert.IsTrue(result.Message.Contains("CPF invalid.")); Assert.IsTrue(result.Payload == null); } [TestMethod] public async Task ShouldBeAbleNotCreateOrderTrendInvalid() { InitialDependencies("ShouldBeAbleNotCreateOrderTrendInvalid"); var command = new CreateOrderRequest { CPF = "69686332804", Symbol = "PETR4123", Amount = 4, }; var handler = new CreateOrderHandler(orderRepository, trendRepository, userRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 404); Assert.IsTrue(!string.IsNullOrWhiteSpace(result.Message)); Assert.IsTrue(result.Message.Contains("Trend not found.")); Assert.IsTrue(result.Payload == null); } [TestMethod] public async Task ShouldBeAbleNotCreateOrderUserNotFound() { InitialDependencies("ShouldBeAbleNotCreateOrderUserNotFound"); var command = new CreateOrderRequest { CPF = "00000000191", Symbol = "PETR4", Amount = 4, }; var handler = new CreateOrderHandler(orderRepository, trendRepository, userRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 404); Assert.IsTrue(!string.IsNullOrWhiteSpace(result.Message)); Assert.IsTrue(result.Message.Contains("User not found.")); Assert.IsTrue(result.Payload == null); } [TestMethod] public async Task ShouldBeAbleNotCreateOrderAmountZero() { InitialDependencies("ShouldBeAbleNotCreateOrderAmountZero"); var command = new CreateOrderRequest { CPF = "69686332804", Symbol = "PETR4", Amount = 0, }; var handler = new CreateOrderHandler(orderRepository, trendRepository, userRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 400); Assert.IsTrue(!string.IsNullOrWhiteSpace(result.Message)); Assert.IsTrue(result.Message.Contains("Amount is invalid.")); Assert.IsTrue(result.Payload == null); } } } <file_sep>import styled from 'styled-components'; export const Container = styled.main` max-width: 1220px; padding: 1.5rem 1rem; margin-left: 0 auto; `; export const Card = styled.div` display: flex; align-items: center; justify-content: space-between; margin: 20px 100px; `; export const SideCard = styled.div` display: flex; align-items: center; justify-content: center; flex-direction: column; `; export const Type = styled.h3` color: var(--blue); display: block; `; export const Value = styled.h2` color: var(--light-blue); display: block; `; <file_sep>using Flunt.Extensions.Br.Validations; using Flunt.Notifications; using Flunt.Validations; using MediatR; using Newtonsoft.Json; using TrendContext.Domain.Commands.Responses; using TrendContext.Shared.Commands; namespace TrendContext.Domain.Commands.Requests { public class CreateSessionRequest : Notifiable<Notification>, IRequest<CommandResponse<CreateSessionResponse>>, ICommand { [JsonProperty("cpf")] public string CPF { get; set; } public void Validate() { AddNotifications(new Contract<Notification>() .Requires() .IsNotNullOrEmpty(CPF, "CPF", "CPF is required.") .IsCpf(CPF, "CPF", "CPF invalid.") ); } } } <file_sep>using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; namespace TrendContext.WebApi.Controllers { [ApiController] [Route("api/v1/users")] public class UserController : ControllerBase { private readonly ILogger<UserController> _logger; public UserController(ILogger<UserController> logger) { _logger = logger; } /// <summary> /// List of users /// </summary> /// <param name="mediator"></param> /// <returns>List of trends</returns> /// <response code="200">Returns the list of users</response> /// <response code="500">If has error on server</response> [HttpGet] [Authorize] [ProducesResponseType((200), Type = typeof(IEnumerable<GetAllUsersResponse>))] [ProducesResponseType((500), Type = typeof(object))] public async Task<IActionResult> Get([FromServices] IMediator mediator) { var result = await mediator.Send(new GetAllUsersRequest()); return StatusCode(result.StatusCode, result.Success ? result.Payload : new { message = result.Message }); } /// <summary> /// Get one user by id /// </summary> /// <param name="mediator"></param> /// <param name="id"></param> /// <returns>Single user</returns> /// <response code="200">Single User</response> /// <response code="500">If has error on server</response> [HttpGet] [Route("{id}")] [Authorize] [ProducesResponseType((200), Type = typeof(GetAllUsersResponse))] [ProducesResponseType((500), Type = typeof(object))] public async Task<IActionResult> Get([FromServices] IMediator mediator, [FromRoute] Guid id) { var result = await mediator.Send(new GetByIdUserRequest { Id = id}); return StatusCode(result.StatusCode, result.Success ? result.Payload : new { message = result.Message }); } /// <summary> /// Creates a new User. /// </summary> /// <remarks> /// Sample request: /// /// POST /api/v1/users /// { /// "name": "<NAME>", /// "cpf": "99999999999" /// } /// /// </remarks> /// <param name="mediator"></param> /// <param name="command"></param> /// <returns>A newly created user</returns> /// <response code="201">Returns the newly created user</response> /// <response code="400">If the item is null</response> /// <response code="500">If has error on server</response> [HttpPost] [AllowAnonymous] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task<IActionResult> Create([FromServices] IMediator mediator, [FromBody] CreateUserRequest command) { var result = await mediator.Send(command); return StatusCode(result.StatusCode, result.Success ? result.Payload : new { message = result.Message }); } } } <file_sep>import styled from 'styled-components'; export const Container = styled.main` max-width: 1220px; padding: 1.5rem 1rem; margin-left: 0 auto; `; export const Title = styled.h1` font-size: 1.5rem; color: var(--blue); font-weight: 500; text-align: center; `; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrendContext.Domain.Commands.Responses { public class CommandResponse<T> { public bool Success { get; set; } public int StatusCode { get; set; } public string Message { get; set; } public T Payload { get; set; } public CommandResponse(bool success, int statusCode, string message, T payload) { Success = success; StatusCode = statusCode; Message = message; Payload = payload; } } } <file_sep>using Newtonsoft.Json; using System; namespace TrendContext.Domain.Commands.Responses { public class GetAllUsersResponse : GetByIdUserResponse { } } <file_sep># Trend Manager ## Sistema para realizar compras de ação <p align="center"> <img alt="GitHub language count" src="https://img.shields.io/github/languages/count/jefferson-luis-nascimento/toro?color=%2304D361"> <img alt="License" src="https://img.shields.io/badge/license-MIT-%2304D361"> <a href="https://github.com/jefferson-luis-nascimento/toro/stargazers"> <img alt="Stargazers" src="https://img.shields.io/github/stars/jefferson-luis-nascimento/toro?style=social"> </a> </p> # Funcionalidades: <p><b>Backend:</b> Todas as regras de negócio e persitência</p> <p><b>Frontend-web:</b> Interface do usuário onde o mesmo pode se cadastrar, logar, consultar saldo e realizar compras de ações</p> ## Começando Abaixo seguem as intruções para baixar e executar o projeto em ambiente de desenvolvimento. ## Pre-requisitos - [Windows 10](https://www.microsoft.com/pt-br/windows/get-windows-10) - Sistema operacional usado para desenvolvimento. - [NodeJS](https://nodejs.org/en/) - Ambiente de execução do projeto React.JS. - [Yarn](https://yarnpkg.com/en/docs/install) - Gerenciador de pacotes. - [Asp.Net Core 5](https://docs.microsoft.com/pt-br/dotnet/core/dotnet-five) - SDK para desenvolvimento do backend. - [Visual Studio 2019](https://visualstudio.microsoft.com/pt-br/downloads/) - IDE usado para desenvolvimento ### Caminho para download do projeto ``` $> git clone https://github.com/jefferson-luis-nascimento/toro.git ``` ou ``` $> git clone <EMAIL>:jefferson-luis-nascimento/toro.git ``` ## Instalação Passo passo de instalação do ambiente de desenvolvimento após feito download: ## Databases ### Utilizando o InMemoryEntityFramework ## Backend ### Instalar as dependências do backend Executar via Visual Studio 2019 o projeto TrendContext.WebApi ## Frontend-web ### Instalar as dependências do frontend-web ``` $> cd ./toro/frontend/ && yarn ``` ### Executando o aplicativo ``` $> yarn start ``` #### Feito com - [Asp.Net Core 5](https://docs.microsoft.com/pt-br/dotnet/core/dotnet-five) - O .NET é uma plataforma de desenvolvimento gratuita e de software livre para a criação de muitos tipos de aplicativos. - [ReactJS](https://pt-br.reactjs.org/) - Uma biblioteca JavaScript para criar interfaces de usuário. ### Desenvolvedor - **<NAME>** - *Full-stack developer* - [GitHub profile](https://github.com/jefferson-luis-nascimento) ## Conhecimentos usados - Asp.Net Core 5 - MVC design pattern - CQRS design pattern - MediatR - InMemoryEntityFrameworkCore - Flunt - MS Tests - JWT - React ecossystem - React Hooks - ReactJS - Reactotron - React Router DOM - React Toastify - Context API - ESLint - Prettier - Styled Components - Axios - History <file_sep>import axios from 'axios'; import https from 'https'; export const api = axios.create({ baseURL: 'http://localhost:5000/api/v1/', httpsAgent: new https.Agent({ rejectUnauthorized: false, }), }); <file_sep>using System.Collections.Generic; using TrendContext.Shared.Entities; namespace TrendContext.Domain.Entities { public class User : Entity { public string Name { get; set; } public string CPF { get; set; } public decimal CheckingAccountAmount { get; set; } } } <file_sep>using Flunt.Extensions.Br.Validations; using Flunt.Notifications; using Flunt.Validations; using MediatR; using Newtonsoft.Json; using TrendContext.Domain.Commands.Responses; using TrendContext.Shared.Commands; namespace TrendContext.Domain.Commands.Requests { public class CreateUserRequest : Notifiable<Notification>, IRequest<CommandResponse<CreateUserResponse>>, ICommand { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("cpf")] public string CPF { get; set; } public void Validate() { AddNotifications(new Contract<Notification>() .Requires() .IsNotNullOrEmpty(Name, "Name", "Name is required.") .IsNotNullOrEmpty(CPF, "CPF", "CPF is required.") .IsCpf(CPF, "CPF", "CPF invalid.") ); } } } <file_sep>using MediatR; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; using TrendContext.Domain.Entities; using TrendContext.Shared.Repository; namespace TrendContext.Domain.Handlers { public class GetAllUsersHandler : IRequestHandler<GetAllUsersRequest, CommandResponse<IEnumerable<GetAllUsersResponse>>> { private readonly IRepository<User> repository; private readonly ILogger<GetAllUsersHandler> logger; public GetAllUsersHandler(IRepository<User> repository, ILogger<GetAllUsersHandler> logger) { this.repository = repository; this.logger = logger; } public async Task<CommandResponse<IEnumerable<GetAllUsersResponse>>> Handle(GetAllUsersRequest request, CancellationToken cancellationToken) { try { var result = await repository.GetAllAsync(); return new CommandResponse<IEnumerable<GetAllUsersResponse>>(true, 200, string.Empty, result.Select(user => new GetAllUsersResponse { Id = user.Id, Name = user.Name, CPF = user.CPF, CheckingAccountAmount = user.CheckingAccountAmount, }).AsEnumerable()); } catch (Exception ex) { logger.LogError(ex, ex.Message); return new CommandResponse<IEnumerable<GetAllUsersResponse>>(false, 500, "Internal Server Error", null); } } } } <file_sep>using Flunt.Notifications; using MediatR; using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; using TrendContext.Domain.Data.Interfaces; using TrendContext.Domain.Entities; using TrendContext.Domain.Repositories.Interfaces; using TrendContext.Domain.Services; namespace TrendContext.Domain.Handlers { public class CreateSessionHandler : Notifiable<Notification>, IRequestHandler<CreateSessionRequest, CommandResponse<CreateSessionResponse>> { private readonly IUserRepository repository; private readonly ITokenService tokenService; private readonly ILogger<CreateSessionHandler> logger; public CreateSessionHandler(IUserRepository repository, ITokenService tokenService, ILogger<CreateSessionHandler> logger) { this.repository = repository; this.tokenService = tokenService; this.logger = logger; } public async Task<CommandResponse<CreateSessionResponse>> Handle(CreateSessionRequest request, CancellationToken cancellationToken) { try { request.Validate(); if(!request.IsValid) { return new CommandResponse<CreateSessionResponse>(false, 400, string.Join(Environment.NewLine, request.Notifications.Select(x => x.Message)), null); } var existsUser = await repository.GetByCPFAsync(request.CPF); if (existsUser == null) { return new CommandResponse<CreateSessionResponse>(false, 400, "User not found.", null); } var token = tokenService.GenerateToken(existsUser); return new CommandResponse<CreateSessionResponse>(true, 201, string.Empty, new CreateSessionResponse { Id = existsUser.Id, Name = existsUser.Name, CPF = existsUser.CPF, Token = token, }); } catch (Exception ex) { logger.LogError(ex, ex.Message); return new CommandResponse<CreateSessionResponse>(false, 500, "Internal Server Error", null); } } } } <file_sep>using MediatR; using System; using System.Collections.Generic; using TrendContext.Domain.Commands.Responses; namespace TrendContext.Domain.Commands.Requests { public class GetAllUsersRequest : IRequest<CommandResponse<IEnumerable<GetAllUsersResponse>>> { } } <file_sep>using MediatR; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; using TrendContext.Domain.Entities; using TrendContext.Domain.Repositories.Interfaces; using TrendContext.Shared.Repository; namespace TrendContext.Domain.Handlers { public class GetByIdUserPositionHandler : IRequestHandler<GetByIdUserPositionRequest, CommandResponse<GetByIdUserPositionResponse>> { private readonly IUserRepository userRepository; private readonly IOrderRepository orderRepository; private readonly ILogger<GetByIdUserPositionHandler> logger; public GetByIdUserPositionHandler(IUserRepository userRepository, IOrderRepository orderRepository, ILogger<GetByIdUserPositionHandler> logger) { this.userRepository = userRepository; this.orderRepository = orderRepository; this.logger = logger; } public async Task<CommandResponse<GetByIdUserPositionResponse>> Handle(GetByIdUserPositionRequest request, CancellationToken cancellationToken) { try { var result = await userRepository.GetByIdAsync(request.Id); if (result == null) { return new CommandResponse<GetByIdUserPositionResponse>(false, 404, "User not found.", null); } var orders = await orderRepository.GetByUserIdAsync(request.Id); return new CommandResponse<GetByIdUserPositionResponse>(true, 200, string.Empty, new GetByIdUserPositionResponse { Id = result.Id, Name = result.Name, CPF = result.CPF, CheckingAccountAmount = result.CheckingAccountAmount, Positions = orders?.Select(order => new CreateOrderResponse { Id = order.Id, Symbol = order.Trend.Symbol, Amount = order.Amount, CurrentPrice = order.Trend.CurrentPrice, Total = order.Total, OrderDate = order.CreatedIn, }).ToList(), Consolidated = result.CheckingAccountAmount + (orders.Sum(x => x.Total )), }); } catch (Exception ex) { logger.LogError(ex, ex.Message); return new CommandResponse<GetByIdUserPositionResponse>(false, 500, "Internal Server Error", null); } } } } <file_sep>using MediatR; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; using TrendContext.Domain.Entities; using TrendContext.Shared.Repository; namespace TrendContext.Domain.Handlers { public class GetAllTrendHandler : IRequestHandler<GetAllTrendsRequest, CommandResponse<IEnumerable<GetAllTrendsResponse>>> { private readonly IRepository<Trend> repository; private readonly ILogger<GetAllTrendHandler> logger; public GetAllTrendHandler(IRepository<Trend> repository, ILogger<GetAllTrendHandler> logger) { this.repository = repository; this.logger = logger; } public async Task<CommandResponse<IEnumerable<GetAllTrendsResponse>>> Handle(GetAllTrendsRequest request, CancellationToken cancellationToken) { try { var result = await repository.GetAllAsync(); return new CommandResponse<IEnumerable<GetAllTrendsResponse>>(true, 200, string.Empty, result.Select(trend => new GetAllTrendsResponse { Symbol = trend.Symbol, CurrentPrice = trend.CurrentPrice }).AsEnumerable()); } catch (Exception ex) { logger.LogError(ex, ex.Message); return new CommandResponse<IEnumerable<GetAllTrendsResponse>>(false, 500, "Internal Server Error", null); } } } } <file_sep>using MediatR; using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; using TrendContext.Domain.Repositories.Interfaces; namespace TrendContext.Domain.Handlers { public class GetByIdUserHandler : IRequestHandler<GetByIdUserRequest, CommandResponse<GetByIdUserResponse>> { private readonly IUserRepository repository; private readonly ILogger<GetByIdUserHandler> logger; public GetByIdUserHandler(IUserRepository repository, ILogger<GetByIdUserHandler> logger) { this.repository = repository; this.logger = logger; } public async Task<CommandResponse<GetByIdUserResponse>> Handle(GetByIdUserRequest request, CancellationToken cancellationToken) { try { var result = await repository.GetByIdAsync(request.Id); if(result == null) { return new CommandResponse<GetByIdUserResponse>(false, 404, "User not found.", null); } return new CommandResponse<GetByIdUserResponse>(true, 200, string.Empty, new GetByIdUserResponse { Id = result.Id, Name = result.Name, CPF = result.CPF, CheckingAccountAmount = result.CheckingAccountAmount, }); } catch (Exception ex) { logger.LogError(ex, ex.Message); return new CommandResponse<GetByIdUserResponse>(false, 500, "Internal Server Error", null); } } } } <file_sep>using Flunt.Notifications; using MediatR; using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; using TrendContext.Domain.Data.Interfaces; using TrendContext.Domain.Entities; using TrendContext.Domain.Repositories.Interfaces; using TrendContext.Shared.Repository; namespace TrendContext.Domain.Handlers { public class CreateOrderHandler : Notifiable<Notification>, IRequestHandler<CreateOrderRequest, CommandResponse<CreateOrderResponse>> { private readonly IRepository<Order> orderRepository; private readonly ITrendRepository trendRepository; private readonly IUserRepository userRepository; private readonly IUnitOfWork unitOfWork; private readonly ILogger<CreateOrderHandler> logger; public CreateOrderHandler(IRepository<Order> orderRepository, ITrendRepository trendRepository, IUserRepository userRepository, IUnitOfWork unitOfWork, ILogger<CreateOrderHandler> logger) { this.orderRepository = orderRepository; this.trendRepository = trendRepository; this.userRepository = userRepository; this.unitOfWork = unitOfWork; this.logger = logger; } public async Task<CommandResponse<CreateOrderResponse>> Handle(CreateOrderRequest request, CancellationToken cancellationToken) { try { request.Validate(); if (!request.IsValid) { return new CommandResponse<CreateOrderResponse>(false, 400, string.Join(Environment.NewLine, request.Notifications.Select(x => x.Message)), null); } var existingTrend = await trendRepository.GetBySymbol(request.Symbol); if (existingTrend == null) { return new CommandResponse<CreateOrderResponse>(false, 404, "Trend not found.", null); } var existingUser = await userRepository.GetByCPFAsync(request.CPF); if (existingUser == null) { return new CommandResponse<CreateOrderResponse>(false, 404, "User not found.", null); } var order = new Order { TrendId = existingTrend.Id, UserId = existingUser.Id, Amount = request.Amount, Total = Order.CalculateTotalOrder(existingTrend.CurrentPrice , request.Amount), }; if (order.Total > existingUser.CheckingAccountAmount) { return new CommandResponse<CreateOrderResponse>(false, 400, "Insufficient funds.", null); } unitOfWork.BeginTransaction(); orderRepository.Create(order); existingUser.CheckingAccountAmount -= order.Total; await userRepository.UpdateAsync(existingUser); await unitOfWork.Commit(); return new CommandResponse<CreateOrderResponse>(true, 201, string.Empty, new CreateOrderResponse { Id = order.Id, Symbol = existingTrend.Symbol, Amount = order.Amount, CurrentPrice = existingTrend.CurrentPrice, Total = order.Total, OrderDate = order.CreatedIn, }); } catch (Exception ex) { logger.LogError(ex, ex.Message); unitOfWork.Rollback(); return new CommandResponse<CreateOrderResponse>(false, 500, "Internal Server Error", null); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrendContext.Shared.Config { public static class Settings { public static string Secret { get; set; } = "<KEY>"; } } <file_sep>import styled from 'styled-components'; export const Wrapper = styled.div` height: 100vh; background: var(--white); `; <file_sep>import styled from 'styled-components'; export const Container = styled.div` margin: auto; max-width: 500px; display: flex; flex-direction: column; align-items: center; justify-content: center; h2 { color: var(--text-title); font-size: 1.5rem; margin: 50px; } `; export const Form = styled.form` margin: auto; max-width: 500px; display: flex; flex-direction: column; align-items: center; justify-content: center; `; <file_sep>using Newtonsoft.Json; using System; namespace TrendContext.Domain.Commands.Responses { public class CreateSessionResponse : CreateUserResponse { [JsonProperty("token")] public string Token { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using TrendContext.Domain.Entities; using TrendContext.Shared.Repository; namespace TrendContext.Domain.Repositories.Interfaces { public interface IOrderRepository : IRepository<Order> { Task<List<Order>> GetByUserIdAsync(Guid id); } } <file_sep>using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Threading.Tasks; using TrendContext.Domain.Data; using TrendContext.Shared.Entities; using TrendContext.Shared.Repository; namespace TrendContext.Domain.Repositories.Implementations { public class Repository<TEntity> : IRepository<TEntity> where TEntity : Entity { protected readonly InMemoryAppContext appContext; protected DbSet<TEntity> entities; public Repository(InMemoryAppContext appContext) { this.appContext = appContext; entities = appContext.Set<TEntity>(); } public async Task<TEntity> GetByIdAsync(Guid id) { var existsEntity = await entities.SingleOrDefaultAsync(entity => entity.Id == id); return existsEntity; } public async Task<IEnumerable<TEntity>> GetAllAsync() { return await entities.ToListAsync(); } public void Create(TEntity entity) { entities.Add(entity); } public async Task UpdateAsync(TEntity entity) { var existsEntity = await GetByIdAsync(entity.Id); appContext.Entry(existsEntity).CurrentValues.SetValues(entity); } public async Task DeleteAsync(Guid id) { var existsEntity = await GetByIdAsync(id); entities.Remove(existsEntity); } public async Task Save() { await appContext.SaveChangesAsync(); } } } <file_sep>using TrendContext.Domain.Entities; namespace TrendContext.Domain.Services { public interface ITokenService { string GenerateToken(User user); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TrendContext.Domain.Entities; namespace TrendContext.Domain.Data { public class InitialData { protected InitialData() { } public static void AddDefaultData(InMemoryAppContext context) { var rebeca = new User { Id = Guid.Parse("4786FC4D-1B0C-4959-8459-0E871B104D3C"), CheckingAccountAmount = 234M, CPF = "69686332804", Name = "<NAME>", }; var priscila = new User { Id = Guid.Parse("08211958-1DB0-48B4-886E-125079D98836"), CheckingAccountAmount = 451, CPF = "73060084122", Name = "<NAME>", }; context.Users.Add(rebeca); context.Users.Add(priscila); var petr4 = new Trend { Id = Guid.Parse("08211958-1DB0-48B4-886E-125079D98836"), Symbol = "PETR4", CurrentPrice = 28.44M, }; var mglu3 = new Trend { Id = Guid.Parse("CB1F9520-9DEE-41B4-849F-FACD6D046BF3"), Symbol = "MGLU3", CurrentPrice = 25.91M, }; var vvar3 = new Trend { Id = Guid.Parse("3D97A2F8-1D6B-4CA8-96E8-969DA6B64E38"), Symbol = "VVAR3", CurrentPrice = 25.91M, }; var sanb11 = new Trend { Id = Guid.Parse("0A490622-F0BC-41B4-9EDB-1F638B76AD11"), Symbol = "SANB11", CurrentPrice = 40.77M, }; var toro4 = new Trend { Id = Guid.Parse("D8912C3A-5780-4EF8-A15D-6A2E291B92E7"), Symbol = "TORO4", CurrentPrice = 115.98M, }; context.Trends.Add(petr4); context.Trends.Add(mglu3); context.Trends.Add(vvar3); context.Trends.Add(sanb11); context.Trends.Add(toro4); var order1 = new Order { Id = Guid.Parse("C16D2DB5-A50A-40F0-BD77-F9FBB77D819B"), UserId = rebeca.Id, TrendId = petr4.Id, Amount = 2, Total = Order.CalculateTotalOrder(petr4.CurrentPrice, 2), }; var order2 = new Order { Id = Guid.Parse("DAEC7DD6-E4B2-4034-A297-95D4C5D2A87C"), UserId = rebeca.Id, TrendId = sanb11.Id, Amount = 3, Total = Order.CalculateTotalOrder(sanb11.CurrentPrice, 3), }; context.Orders.Add(order1); context.Orders.Add(order2); context.SaveChanges(); } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; namespace TrendContext.Domain.Commands.Responses { public class GetByIdUserPositionResponse { [JsonProperty("id")] public Guid Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("cpf")] public string CPF { get; set; } [JsonProperty("checkingAccountAmount")] public decimal CheckingAccountAmount { get; set; } [JsonProperty("positions")] public List<CreateOrderResponse> Positions { get; set; } [JsonProperty("consolidated")] public decimal Consolidated { get; set; } } } <file_sep>using System.Threading.Tasks; using TrendContext.Domain.Entities; using TrendContext.Shared.Repository; namespace TrendContext.Domain.Repositories.Interfaces { public interface ITrendRepository : IRepository<Trend> { Task<Trend> GetBySymbol(string symbol); } } <file_sep>using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; namespace TrendContext.WebApi.Controllers { [ApiController] [Route("api/v1/order")] public class OrderController : ControllerBase { private readonly ILogger<TrendController> _logger; public OrderController(ILogger<TrendController> logger) { _logger = logger; } /// <summary> /// Creates a new Order. /// </summary> /// <remarks> /// Sample request: /// /// POST /api/v1/order /// { /// "cpf": "99999999999", /// "symbol": "PETR4", /// "amount": 3 /// } /// /// </remarks> /// <param name="mediator"></param> /// <param name="command"></param> /// <returns>A newly created trend</returns> /// <response code="201">Returns the newly created order</response> /// <response code="400">If the item is null</response> /// <response code="500">If has error on server</response> [HttpPost] [Authorize] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task<IActionResult> Create([FromServices] IMediator mediator, [FromBody] CreateOrderRequest command) { var result = await mediator.Send(command); return StatusCode(result.StatusCode, result.Success ? result.Payload : new { message = result.Message }); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TrendContext.Shared.Entities; namespace TrendContext.Shared.Repository { public interface IRepository<T> where T : Entity { Task<T> GetByIdAsync(Guid id); Task<IEnumerable<T>> GetAllAsync(); void Create(T entity); Task UpdateAsync(T entity); Task DeleteAsync(Guid id); Task Save(); } } <file_sep>using System; using System.ComponentModel.DataAnnotations; namespace TrendContext.Shared.Entities { public abstract class Entity { [Key] public Guid Id { get; set; } public DateTime CreatedIn { get; set; } public DateTime? UpdatedIn { get; set; } public DateTime? DeletedIn { get; set; } public bool Deleted { get; set; } public Entity() { Id = Guid.NewGuid(); CreatedIn = DateTime.Now; } } } <file_sep>export const cpfMask = (value: string) => { return value .replace(/\D/g, '') // substitui qualquer caracter que nao seja numero por nada .replace(/(\d{3})(\d)/, '$1.$2') // captura 2 grupos de numero o primeiro de 3 e o segundo de 1, apos capturar o primeiro grupo ele adiciona um ponto antes do segundo grupo de numero .replace(/(\d{3})(\d)/, '$1.$2') .replace(/(\d{3})(\d{1,2})/, '$1-$2') .replace(/(-\d{2})\d+?$/, '$1'); // captura 2 numeros seguidos de um traço e não deixa ser digitado mais nada }; <file_sep>using Flunt.Notifications; using MediatR; using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; using TrendContext.Domain.Data.Interfaces; using TrendContext.Domain.Entities; using TrendContext.Domain.Repositories.Interfaces; namespace TrendContext.Domain.Handlers { public class CreateUserHandler : Notifiable<Notification>, IRequestHandler<CreateUserRequest, CommandResponse<CreateUserResponse>> { private readonly IUserRepository repository; private readonly IUnitOfWork unitOfWork; private readonly ILogger<CreateUserHandler> logger; public CreateUserHandler(IUserRepository repository, IUnitOfWork unitOfWork, ILogger<CreateUserHandler> logger) { this.repository = repository; this.unitOfWork = unitOfWork; this.logger = logger; } public async Task<CommandResponse<CreateUserResponse>> Handle(CreateUserRequest request, CancellationToken cancellationToken) { try { request.Validate(); if(!request.IsValid) { return new CommandResponse<CreateUserResponse>(false, 400, string.Join(Environment.NewLine, request.Notifications.Select(x => x.Message)), null); } if (await repository.CheckCpfAlreadyExistsAsync(request.CPF)) { return new CommandResponse<CreateUserResponse>(false, 400, "Already exists this CPF.", null); } var user = new User { Name = request.Name, CPF = request.CPF, CheckingAccountAmount = 100M, }; unitOfWork.BeginTransaction(); repository.Create(user); await unitOfWork.Commit(); return new CommandResponse<CreateUserResponse>(true, 201, string.Empty, new CreateUserResponse { Id = user.Id, Name = user.Name, CPF = user.CPF, }); } catch (Exception ex) { logger.LogError(ex, ex.Message); unitOfWork.Rollback(); return new CommandResponse<CreateUserResponse>(false, 500, "Internal Server Error", null); } } } } <file_sep>using Flunt.Notifications; using Flunt.Validations; using MediatR; using Newtonsoft.Json; using TrendContext.Domain.Commands.Responses; using TrendContext.Shared.Commands; namespace TrendContext.Domain.Commands.Requests { public class CreateTrendRequest : Notifiable<Notification>, IRequest<CommandResponse<CreateTrendResponse>>, ICommand { [JsonProperty("symbol")] public string Symbol { get; set; } [JsonProperty("currentPrice")] public decimal CurrentPrice { get; set; } public void Validate() { AddNotifications(new Contract<Notification>() .Requires() .IsNotNullOrWhiteSpace(Symbol, "Symbol", "Symbol is required.") .IsGreaterThan(CurrentPrice, decimal.Zero, "CurrentPrice", "CurrentPrice is invalid.") .IsFalse(Symbol.Length < 5 || Symbol.Length > 8, Symbol, "Symbol is invalid.") ); } } } <file_sep>using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TrendContext.Domain.Entities; namespace TrendContext.Domain.Data { public class InMemoryAppContext : DbContext { public InMemoryAppContext(DbContextOptions<InMemoryAppContext> options) : base(options) { } public DbSet<User> Users { get; set; } public DbSet<Trend> Trends { get; set; } public DbSet<Order> Orders { get; set; } } } <file_sep>using Flunt.Extensions.Br.Validations; using Flunt.Notifications; using Flunt.Validations; using MediatR; using Newtonsoft.Json; using System; using TrendContext.Domain.Commands.Responses; using TrendContext.Shared.Commands; namespace TrendContext.Domain.Commands.Requests { public class CreateOrderRequest : Notifiable<Notification>, IRequest<CommandResponse<CreateOrderResponse>>, ICommand { [JsonProperty("cpf")] public string CPF { get; set; } [JsonProperty("symbol")] public string Symbol { get; set; } [JsonProperty("amount")] public int Amount { get; set; } public void Validate() { AddNotifications(new Contract<Notification>() .Requires() .IsNotNullOrEmpty(CPF, "CPF", "CPF is required.") .IsCpf(CPF, "CPF", "CPF invalid.") .IsNotNullOrEmpty(Symbol, "Symbol", "Symbol is required.") .IsGreaterThan(Amount, 0, "Amount", "Amount is invalid.") .IsFalse(Symbol.Length < 5 || Symbol.Length > 8, Symbol, "Symbol is invalid.") ); } } } <file_sep>import { darken } from 'polished'; import { NavLink } from 'react-router-dom'; import styled from 'styled-components'; export const Container = styled.header` background: var(--blue); padding: 0 50px; `; export const Content = styled.div` max-width: 1220px; margin: 0 auto; height: 72px; padding: 2rem 1rem; display: flex; align-items: center; justify-content: space-between; `; export const LeftContent = styled.div` display: flex; align-items: center; justify-content: center; svg { height: 40px; width: 115px; } > div { margin-left: 80px; width: 300px; display: flex; align-items: center; justify-content: space-between; } `; export const LinkElem = styled(NavLink)` text-decoration: none; color: var(--white); padding-bottom: 5px; transition: color 0.2s; &.active { color: var(--light-gray); font-weight: bold; border-bottom-width: 3px; border-bottom-style: solid; border-color: var(--white); } &:hover { color: ${darken(0.2, '#d7d7d7')}; } `; export const RightContent = styled.div` display: flex; align-items: center; justify-content: center; > span { font-size: 0.875rem; color: var(--white); margin-right: 20px; padding-bottom: 5px; } button { font-size: 0.875rem; color: var(--white); background: var(--blue); border: 2px solid var(--white); padding: 1.1rem 1rem; border-radius: 0.25rem; height: 2rem; margin-right: 10px; display: flex; align-items: center; justify-content: center; transition: filter 0.2s; &:hover { background: var(--white); color: var(--blue); } } `; <file_sep>using Newtonsoft.Json; using System; namespace TrendContext.Domain.Commands.Responses { public class CreateTrendResponse { [JsonProperty("id")] public Guid Id { get; set; } [JsonProperty("symbol")] public string Symbol { get; set; } [JsonProperty("currentPrice")] public decimal CurrentPrice { get; set; } } } <file_sep>using Newtonsoft.Json; using System; namespace TrendContext.Domain.Commands.Responses { public class CreateOrderResponse { [JsonProperty("id")] public Guid Id { get; set; } [JsonProperty("symbol")] public string Symbol { get; set; } [JsonProperty("amount")] public decimal Amount { get; set; } [JsonProperty("currentPrice")] public decimal CurrentPrice { get; set; } [JsonProperty("total")] public decimal Total { get; set; } [JsonProperty("orderDate")] public DateTime OrderDate { get; set; } } } <file_sep>using Newtonsoft.Json; using System; namespace TrendContext.Domain.Commands.Responses { public class GetByIdUserResponse { [JsonProperty("id")] public Guid Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("cpf")] public string CPF { get; set; } [JsonProperty("checkingAccountAmount")] public decimal CheckingAccountAmount { get; set; } } } <file_sep>using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Data; using TrendContext.Domain.Data.Interfaces; using TrendContext.Domain.Entities; using TrendContext.Domain.Handlers; using TrendContext.Domain.Repositories.Implementations; using TrendContext.Domain.Repositories.Interfaces; using TrendContext.Shared.Repository; namespace TrendContext.Tests.Handlers { [TestClass] public class CreateUserHandlerTest { private InMemoryAppContext appContext; private IUserRepository userRepository; private IUnitOfWork unitOfWork; private ILogger<CreateUserHandler> logger; private void InitialDependencies(string nomeBanco) { var options = new DbContextOptionsBuilder<InMemoryAppContext>() .UseInMemoryDatabase(databaseName: nomeBanco) .Options; appContext = new InMemoryAppContext(options); userRepository = new UserRepository(appContext); unitOfWork = new UnitOfWork(appContext); logger = new Logger<CreateUserHandler>(new LoggerFactory()); InitialData.AddDefaultData(appContext); } [TestMethod] public async Task ShouldBeAbleToCreateUser() { InitialDependencies("ShouldBeAbleToCreateUser"); var command = new CreateUserRequest { Name = "<NAME>", CPF = "00000000191", }; var handler = new CreateUserHandler(userRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(result.Success); Assert.IsTrue(result.StatusCode == 201); Assert.IsTrue(string.IsNullOrWhiteSpace(result.Message)); Assert.IsTrue(result.Payload != null); } [TestMethod] public async Task ShouldNotBeAbleToCreateUserCpfInvalid() { InitialDependencies("ShouldNotBeAbleToCreateUserCpfInvalid"); var command = new CreateUserRequest { Name = "<NAME>", CPF = "00000000191987", }; var handler = new CreateUserHandler(userRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 400); Assert.IsTrue(result.Message.Contains("CPF invalid.")); Assert.IsTrue(result.Payload == null); } [TestMethod] public async Task ShouldNotBeAbleToCreateSessionUserAlreadyExists() { InitialDependencies("ShouldNotBeAbleToCreateSessionUserAlreadyExists"); var command = new CreateUserRequest { Name = "User Test", CPF = "69686332804", }; var handler = new CreateUserHandler(userRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 400); Assert.IsTrue(result.Message.Contains("Already exists this CPF.")); Assert.IsTrue(result.Payload == null); } [TestMethod] public async Task ShouldNotBeAbleToCreateSessionUserNameEmpty() { InitialDependencies("ShouldNotBeAbleToCreateSessionUserNameEmpty"); var command = new CreateUserRequest { Name = "", CPF = "69686332804", }; var handler = new CreateUserHandler(userRepository, unitOfWork, logger); var result = await handler.Handle(command, new System.Threading.CancellationToken()); Assert.IsTrue(result != null); Assert.IsTrue(!result.Success); Assert.IsTrue(result.StatusCode == 400); Assert.IsTrue(result.Message.Contains("Name is required.")); Assert.IsTrue(result.Payload == null); } } } <file_sep>using System.Collections.Generic; using TrendContext.Shared.Entities; namespace TrendContext.Domain.Entities { public class Trend : Entity { public string Symbol { get; set; } public decimal CurrentPrice { get; set; } } } <file_sep>using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; namespace TrendContext.WebApi.Controllers { [ApiController] [Route("api/v1/userPosition")] public class UserPositionController : ControllerBase { private readonly ILogger<UserPositionController> _logger; public UserPositionController(ILogger<UserPositionController> logger) { _logger = logger; } /// <summary> /// Get one user by id /// </summary> /// <param name="mediator"></param> /// <param name="id"></param> /// <returns>Single user</returns> /// <response code="200">Single User</response> /// <response code="500">If has error on server</response> [HttpGet] [Route("{id}")] [Authorize] [ProducesResponseType((200), Type = typeof(GetAllUsersResponse))] [ProducesResponseType((500), Type = typeof(object))] public async Task<IActionResult> Get([FromServices] IMediator mediator, [FromRoute] Guid id) { var result = await mediator.Send(new GetByIdUserPositionRequest { Id = id}); return StatusCode(result.StatusCode, result.Success ? result.Payload : new { message = result.Message }); } } } <file_sep>using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; using TrendContext.Domain.Data; using TrendContext.Domain.Entities; using TrendContext.Domain.Repositories.Interfaces; namespace TrendContext.Domain.Repositories.Implementations { public class TrendRepository : Repository<Trend>, ITrendRepository { public TrendRepository(InMemoryAppContext appContext) : base (appContext) { } public async Task<Trend> GetBySymbol(string symbol) { return await entities.FirstOrDefaultAsync(trend => trend.Symbol == symbol); } } } <file_sep>using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; namespace TrendContext.WebApi.Controllers { [ApiController] [Route("api/v1/trends")] public class TrendController : ControllerBase { private readonly ILogger<TrendController> _logger; public TrendController(ILogger<TrendController> logger) { _logger = logger; } /// <summary> /// List of trends /// </summary> /// <param name="mediator"></param> /// <returns>List of trends</returns> /// <response code="200">Returns the newly created item</response> /// <response code="500">If has error on server</response> [HttpGet] [Authorize] [ProducesResponseType((200), Type = typeof(IEnumerable<GetAllTrendsResponse>))] public async Task<IActionResult> Get([FromServices] IMediator mediator) { var result = await mediator.Send(new GetAllTrendsRequest()); return StatusCode(result.StatusCode, result.Success ? result.Payload : new { message = result.Message }); } /// <summary> /// Creates a new Trend. /// </summary> /// <remarks> /// Sample request: /// /// POST /api/v1/trends /// { /// "symbol": "PETR3", /// "currentPrice": 31.28 /// } /// /// </remarks> /// <param name="mediator"></param> /// <param name="command"></param> /// <returns>A newly created trend</returns> /// <response code="201">Returns the newly created item</response> /// <response code="400">If the item is null</response> /// <response code="500">If has error on server</response> [HttpPost] [Authorize] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task<IActionResult> Create([FromServices] IMediator mediator, [FromBody] CreateTrendRequest command) { var result = await mediator.Send(command); return StatusCode(result.StatusCode, result.Success ? result.Payload : new { message = result.Message }); } } } <file_sep>using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TrendContext.Domain.Data; using TrendContext.Domain.Entities; using TrendContext.Domain.Repositories.Interfaces; namespace TrendContext.Domain.Repositories.Implementations { public class OrderRepository : Repository<Order>, IOrderRepository { public OrderRepository(InMemoryAppContext appContext) : base (appContext) { } public async Task<List<Order>> GetByUserIdAsync(Guid id) { return await entities.Include(x => x.Trend).Where(order => order.UserId == id).ToListAsync(); } } } <file_sep>using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading.Tasks; using TrendContext.Domain.Commands.Requests; using TrendContext.Domain.Commands.Responses; namespace TrendContext.WebApi.Controllers { [ApiController] [Route("api/v1/session")] public class SessionController : ControllerBase { private readonly ILogger<SessionController> _logger; public SessionController(ILogger<SessionController> logger) { _logger = logger; } /// <summary> /// Creates a new Session. /// </summary> /// <remarks> /// Sample request: /// /// POST /api/v1/session /// { /// "cpf": "99999999999" /// } /// /// </remarks> /// <param name="mediator"></param> /// <param name="command"></param> /// <returns>A newly user session</returns> /// <response code="201">Returns the newly user session</response> /// <response code="400">If the item is null</response> /// <response code="500">If has error on server</response> [HttpPost] [AllowAnonymous] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task<IActionResult> Create([FromServices] IMediator mediator, [FromBody] CreateSessionRequest command) { var result = await mediator.Send(command); return StatusCode(result.StatusCode, result.Success ? result.Payload : new { message = result.Message }); } } } <file_sep>import styled from 'styled-components'; export const Container = styled.div` label { display: block; color: var(--blue); font-size: 1rem; padding-bottom: 10px; } input { width: 100%; padding: 1.25rem; border-radius: 0.25rem; height: 2rem; border: 1px solid #d7d7d7; background: #e7e9ee; font-weight: 400; font-size: 1rem; margin-bottom: 1rem; &::placeholder { color: var(--text-title); } } `;
cbebcaf32c2eeef727d5b40c4819417305592c0a
[ "Markdown", "C#", "TypeScript" ]
62
TypeScript
leschar/toro
36b885dd1bcafc0638bd34cca332d2d3508e9462
435fe44c8063479b062911e689386bf9385c53b7
refs/heads/master
<file_sep>#!/usr/bin/env ruby class Tile attr_reader :value, :value_mask, :x, :y def initialize # initialize puzzle data structure # all values are 0x1 f f -> the potential values they can be # 1-9 each represented by a bit @value_mask = 0x1ff end def valid? neighbors do |neighbor| if neighbor.value == @value return false end end return true end def set(puzzle,x,y) @puzzle=puzzle @x=x @y=y end def value=(value) # propogate the value if @value&value == 0 puts "ERROR INVALID PUZZLE: #{value} being set at (#{@x},#{@y}) which is #{@value} with mask #{@value_mask}" raise end if value != @value puts "placing value #{value} at #{@x},#{@y}" @value=value self.mask(0x0) neighbors do |neighbor| neighbor.mask(~(1 << (@value-1))) end # mask_constraints(~(1 << (@value-1))) end end def neighbors yield_row {|tile| yield(tile)} yield_col {|tile| yield(tile)} yield_section {|tile| yield(tile)} end def mask(mask) if @value_mask == 0 return end if mask == 0 # our value was found, we are icing our old mask @value_mask = 0 else new_mask = @value_mask & mask if @value_mask == 0 puts "ERROR INVALID PUZZLE: 0x#{mask.to_s(16)} being applied at (#{@x},#{@y}) which is #{@value_mask}" raise end if new_mask != @value_mask @value_mask = new_mask if Math.log2(@value_mask).floor == Math.log2(@value_mask) # if only one value is set puts "new value found through mask #{Math.log2(@value_mask).to_i+1} at #{@x},#{@y}" self.value = Math.log2(@value_mask).to_i+1 end end end end def cost_to_place(val) cost = 0 cur_mask = @value_mask while cur_mask > 0 # count my options cur_mask = cur_mask >> 1 cost = cost+1 end neighbors do |neighbor| # count the options my neighbors would lose if I become this if (1 << (val-1)) & neighbor.value_mask > 0 cost = cost + 1 end end return cost end # this value is illegal for all other items in this row def yield_row (0..8).each do |cur_x| if cur_x != @x cur_tile = @puzzle[@y][cur_x] yield(cur_tile) end end end # this value is illegal for all other items in this (super group?) 3x3 grid-area def yield_section top_left_x = @x-(@x%3) top_left_y = @y-(@y%3) (0..2).each do |offset_x| (0..2).each do |offset_y| cur_x = top_left_x + offset_x cur_y = top_left_y + offset_y if cur_x != @x && cur_y != @y # already got row/col/self cur_tile = @puzzle[cur_y][cur_x] yield(cur_tile) end end end end # this value is illegal for all other items in this col def yield_col (0..8).each do |cur_y| if cur_y != @y cur_tile = @puzzle[cur_y][@x] yield(cur_tile) end end end def copy(new_puzzle) t = Tile.new t.set(new_puzzle,@x,@y) t.set_value(@value) t.set_mask(@value_mask) t end # create some methods for copy which don't do propogation/etc def set_value(v) @value = v end def set_mask(mask) @value_mask = mask end end def panic(p) puts "panic!" print_puzz(p) success = true p.each do |row| row.each do |tile| success = success && tile.valid? end end if success puts "success!!!!" else puts "error!!!!!" end exit end def success(p) puts "success" print_puzz(p) exit end # copy all values of "from" to "to" def copy_puzz(from) to = [] from.each do |row| new_row = [] to << new_row row.each do |tile| new_row << tile.copy(to) end end to end # print the puzzle's status stuff def print_puzz(puzz) puzz.each do |row| row.each do |tile| print "#{(!tile.value.nil? && tile.value > 0) ? tile.value : '.'} " end puts "" end end # we need to choose a value to "set" - we need to remember it and DFS our way through t puzzle # We prefer placing values which: # 1. Get us closer to the solution # solved bt doing DFS # 2. Have the most constraints on them # prefer to place numbers in tiles with very few potential values # 3. Prefer to choose values which constrain others least # # on preference, we'll count the number of constraints placing a particular value would cause and choose lowest value def solve(puzz) candidate_values = [] # pairs: [tile,value,cost] # examine candidates puzz.each_index do |y| row = puzz[y] row.each_index do |x| tile = puzz[y][x] cur_mask = tile.value_mask cur_val = 1 while cur_mask > 0 do if cur_val & 1 > 0 cur_cost = tile.cost_to_place(cur_val) candidate_values << [tile,cur_val,cur_cost] # puts "cost of #{cur_val} => (#{tile.x},#{tile.y}) is #{cur_cost}" end cur_val = cur_val+1 cur_mask = cur_mask >> 1 end end end # puts candidate_values.inspect if candidate_values.length == 0 success(puzz) else while candidate_values.length > 0 do # puts "choose a good candidate to set the value on" candidate_values.sort! {|one,two| one[2] <=> two[2] } # puts candidate_values.inspect next_puz = copy_puzz(puzz) chosen = candidate_values.shift begin next_puz[chosen.y][chosen.x].value = chosen[1] solve(next_puzz) rescue puts "learned that #{chosen[1]} does NOT go at #{chosen[0].x},#{chosen[0].y}" puzz[chosen[0].y][chosen[0].x].mask(~(1<<(chosen[1]-1))) end end end panic(puzz) end #Array.new(9,Array.new(9,Tile.new)) puzzle = [] (0..8).each do |y| row = [] puzzle << row (0..8).each do |x| row << Tile.new end end (0..8).each do |y| (0..8).each do |x| puzzle[y][x].set(puzzle,x,y) # set this tile's location in the grand scheme of things end puts "row of length #{puzzle[y].length}" end puts "total of #{puzzle.length} rows" print_puzz(puzzle) y = 0 puts "starting puzzle:" File.open('puzzle.sudoku').each_line do |s| puts s x = 0 s.split(" ").each do |c| t=puzzle[y][x] n = c.to_i puts "#{n} at #{x},#{y}" if n > 0 && n < 10 puts "#{n} at (#{x},#{y}) => #{n}" begin puzzle[y][x].value = n rescue panic(puzzle) end end x = x + 1 end y = y + 1 end solve(puzzle)
03248f6cd40d9fefcc99a264378cafc0fdb3cbcb
[ "Ruby" ]
1
Ruby
pjschlic/rubydoku
a02b07286a769d017e309b2b635f92bf630906cc
dc22ee4597dcf84f0b533943f38d862cb6897488
refs/heads/master
<repo_name>tmotoole/redcap-admin-dashboard<file_sep>/AdminDash.php <?php namespace UIOWA\AdminDash; use ExternalModules\AbstractExternalModule; use ExternalModules\ExternalModules; require_once 'vendor/autoload.php'; class AdminDash extends AbstractExternalModule { private static $smarty; private static $purposeMaster = array( "Basic or Bench Research", "Clinical Research Study or Trial", "Translational Research 1", "Translational Research 2", "Behavioral or Psychosocial Research Study", "Epidemiology", "Repository", "Other" ); private static $configSettings = array( array( "key" => "use-api-urls", "name" => "Use versionless URLs for easier bookmarking (refresh page to take effect)", "data-on" => "On", "data-off" => "Off", "type" => "checkbox", "default" => true ), array( "key" => "show-suspended-tags", "name" => "Include [suspended] tag next to suspended usernames", "type" => "checkbox", "default" => true ), array( "name" => "<b>NOTE: The following visibility settings will only affect built-in reports.</b>", ), array( "key" =>"show-practice-projects", "name" => "\"Practice / Just for Fun\" projects", "type" => "checkbox", "default" => true ), array( "key" => "show-archived-projects", "name" => "Archived projects", "type" => "checkbox", "default" => true ), array( "key" => "show-deleted-projects", "name" => "Deleted projects", "type" => "checkbox", "default" => true ) ); private $sqlError; public function redcap_module_system_change_version($version, $old_version) { // update db for compatibility with v3.2 $oldVisibilityJson = $this->getSystemSetting("report-visibility"); if ($oldVisibilityJson) { $oldVisibilityArray = json_decode($oldVisibilityJson, true); $executiveUsers = $this->getSystemSetting("executive-users"); $visibilityArrayAdmin = array(); $visibilityArrayExecutive = array(); foreach ($oldVisibilityArray as $key => $oldVisibilityInfo) { $visibilityArrayAdmin[$key] = $oldVisibilityArray[$key][0]; $visibilityArrayExecutive[$key] = array(); foreach ($executiveUsers as $user) { if ($oldVisibilityArray[$key][1]) { array_push($visibilityArrayExecutive[$key], $user); } } } $this->setSystemSetting("report-visibility-admin", $visibilityArrayAdmin); $this->setSystemSetting("report-visibility-executive", $visibilityArrayExecutive); $this->removeSystemSetting("report-visibility"); } // update db for compatibility with v3.3 $oldNameData = $this->getSystemSetting("custom-report-name"); $oldDescData = $this->getSystemSetting("custom-report-desc"); $oldIconData = $this->getSystemSetting("custom-report-icon"); $oldSqlData = $this->getSystemSetting("custom-report-sql"); if ($oldNameData) { $newCustomReportData = array(); $untitledCount = 1; foreach ($oldNameData as $index => $oldName) { if (empty($oldNameData[$index])) { $newName = 'Untitled ' . $untitledCount; $untitledCount += 1; } else { $newName = $oldNameData[$index]; } array_push($newCustomReportData, array( 'reportName' => $newName, 'description' => empty($oldDescData[$index]) ? 'No description defined.' : $oldDescData[$index], 'tabIcon' => empty($oldIconData[$index]) ? 'fas fa-question-circle' : str_replace('fas fa', '', $oldIconData[$index]), 'sql' => $oldSqlData[$index], 'type' => 'table', "customID" => "", )); } $this->setSystemSetting("custom-reports", $newCustomReportData); $this->removeSystemSetting("custom-report"); $this->removeSystemSetting("custom-report-name"); $this->removeSystemSetting("custom-report-desc"); $this->removeSystemSetting("custom-report-icon"); $this->removeSystemSetting("custom-report-sql"); } // downgrade Credentials Check reports to "custom" status so they can be deleted (v4.0) if(version_compare('4.0', $old_version)) { $pwordSearchTerms = array( 'p%word', 'p%wd', 'user%name', 'usr%name', 'user%id', 'usr%id' ); $userDefinedTerms = self::getSystemSetting('additional-search-terms'); foreach($userDefinedTerms as $term) { $pwordSearchTerms[] = db_real_escape_string($term); } $pwordProjectSql = array(); $pwordInstrumentSql = array(); $pwordFieldSql = array(); foreach($pwordSearchTerms as $term) { $pwordProjectSql[] = '(app_title LIKE \'%' . $term . '%\')'; $pwordInstrumentSql[] = '(form_name LIKE \'%' . $term . '%\')'; $pwordFieldSql[] = '(field_name LIKE \'%' . $term . '%\')'; $pwordFieldSql[] = '(element_label LIKE \'%' . $term . '%\')'; $pwordFieldSql[] = '(element_note LIKE \'%' . $term . '%\')'; } $pwordProjectSql = "(" . implode(" OR ", $pwordProjectSql) . ")"; $pwordInstrumentSql = "(" . implode(" OR ", $pwordInstrumentSql) . ")"; $pwordFieldSql = "(" . implode(" OR ", $pwordFieldSql) . ")"; $credentialCheckReports = array( array ( "reportName" => "Credentials Check (Project Titles)", "customID" => "projectCredentials", "description" => "List of projects titles that contain strings related to login credentials (usernames/passwords). Search terms include the following: " . implode(', ', $pwordSearchTerms), "tabIcon" => "key", "defaultVisibility" => false, "sql" => "SELECT projects.project_id AS 'PID', app_title AS 'Project Title', CAST(CASE status WHEN 0 THEN 'Development' WHEN 1 THEN 'Production' WHEN 2 THEN 'Inactive' WHEN 3 THEN 'Archived' ELSE status END AS CHAR(50)) AS 'Status', CAST(CASE WHEN projects.date_deleted IS NULL THEN 'N/A' ELSE projects.date_deleted END AS CHAR(50)) AS 'Project Deleted Date (Hidden)' FROM redcap_projects AS projects, redcap_user_information AS users WHERE (projects.created_by = users.ui_id) AND " . $pwordProjectSql ), array ( "reportName" => "Credentials Check (Instruments)", "customID" => "instrumentCredentials", "description" => "List of projects that contain strings related to login credentials (usernames/passwords) in the instrument or form name. Search terms include the following: " . implode(', ', $pwordSearchTerms), "tabIcon" => "key", "defaultVisibility" => false, "sql" => "SELECT projects.project_id AS 'PID', projects.app_title AS 'Project Title', meta.form_menu_description AS 'Instrument Name', CAST(CASE WHEN projects.date_deleted IS NULL THEN 'N/A' ELSE projects.date_deleted END AS CHAR(50)) AS 'Project Deleted Date (Hidden)' FROM redcap_projects AS projects, redcap_metadata AS meta, redcap_user_information AS users WHERE (projects.created_by = users.ui_id) AND (projects.project_id = meta.project_id) AND (meta.form_menu_description IS NOT NULL) AND " . $pwordInstrumentSql ), array ( "reportName" => "Credentials Check (Fields)", "customID" => "fieldCredentials", "description" => "List of projects that contain strings related to login credentials (usernames/passwords) in fields. Search terms include the following: " . implode(', ', $pwordSearchTerms), "tabIcon" => "key", "defaultVisibility" => false, "sql" => "SELECT projects.project_id AS 'PID', projects.app_title AS 'Project Title', meta.form_name AS 'Form Name', meta.field_name AS 'Variable Name', meta.element_label AS 'Field Label', meta.element_note AS 'Field Note', CAST(CASE WHEN projects.date_deleted IS NULL THEN 'N/A' ELSE projects.date_deleted END AS CHAR(50)) AS 'Project Deleted Date (Hidden)' FROM redcap_projects AS projects, redcap_metadata AS meta, redcap_user_information AS users WHERE (projects.created_by = users.ui_id) AND (projects.project_id = meta.project_id) AND " . $pwordFieldSql . " ORDER BY projects.project_id, form_name, field_name; " ) ); $existingCustomReports = $this->getSystemSetting('custom-reports'); $mergedCustomReports = array_merge($credentialCheckReports, $existingCustomReports); $this->setSystemSetting('custom-reports', $mergedCustomReports); } } public function __construct() { parent::__construct(); define("MODULE_DOCROOT", $this->getModulePath()); } public function initializeSmarty() { self::$smarty = new \Smarty(); self::$smarty->setTemplateDir(MODULE_DOCROOT . 'templates'); self::$smarty->setCompileDir(MODULE_DOCROOT . 'templates_c'); self::$smarty->setConfigDir(MODULE_DOCROOT . 'configs'); self::$smarty->setCacheDir(MODULE_DOCROOT . 'cache'); // self::$smarty->compile_check = false; // self::$smarty->caching = true; } public function displayTemplate($template) { self::$smarty->display($template); } public function includeJsAndCss() { ?> <script src="<?= $this->getUrl("/resources/tablesorter/jquery.tablesorter.min.js") ?>"></script> <script src="<?= $this->getUrl("/resources/tablesorter/jquery.tablesorter.widgets.min.js") ?>"></script> <script src="<?= $this->getUrl("/resources/tablesorter/widgets/widget-pager.min.js") ?>"></script> <script src="<?= $this->getUrl("/resources/c3/d3.min.js") ?>" charset="utf-8"></script> <script src="<?= $this->getUrl("/resources/c3/c3.min.js") ?>"></script> <script src="<?= $this->getUrl("/resources/tablesorter/parsers/parser-input-select.min.js") ?>"></script> <script src="<?= $this->getUrl("/resources/tablesorter/widgets/widget-output.min.js") ?>"></script> <script src="<?= $this->getUrl("/resources/Chart.min.js") ?>"></script> <script src="<?= $this->getUrl("/resources/jquery.validate.min.js") ?>"></script> <link href="<?= $this->getUrl("/resources/tablesorter/tablesorter/theme.blue.min.css") ?>" rel="stylesheet"> <link href="<?= $this->getUrl("/resources/tablesorter/tablesorter/theme.ice.min.css") ?>" rel="stylesheet"> <link href="<?= $this->getUrl("/resources/tablesorter/tablesorter/jquery.tablesorter.pager.min.css") ?>" rel="stylesheet"> <link href="<?= $this->getUrl("/resources/c3/c3.css") ?>" rel="stylesheet" type="text/css"> <link href="<?= $this->getUrl("/resources/styles.css") ?>" rel="stylesheet" type="text/css"/> <link href="<?= $this->getUrl("/resources/tablesorter/tablesorter/theme.bootstrap_4.min.css") ?>" rel="stylesheet"> <script src="<?= $this->getUrl("/resources/bootstrap-toggle/bootstrap-toggle.min.js") ?>"></script> <link href="<?= $this->getUrl("/resources/bootstrap-toggle/bootstrap-toggle.min.css") ?>" rel="stylesheet"> <script src="<?= $this->getUrl("/resources/ace/ace.js") ?>" type="text/javascript" charset="utf-8"></script> <script src="<?= $this->getUrl("/adminDash.js") ?>"></script> <?php if ($_REQUEST['page'] == 'settings') { echo '<script src="' . $this->getUrl("/resources/settings.js") . '"></script>'; } } public function initializeVariables() { $reportReference = $this->generateReportReference(); $configSettings = $this::$configSettings; $executiveUsers = $this->getSystemSetting("executive-users"); $executiveAccess = ($_REQUEST['page'] == 'executiveView' && (in_array(USERID, $executiveUsers) || SUPER_USER) ? 1 : 0); $exportEnabled = ($this->getSystemSetting("executive-export-enabled") && $executiveAccess) || (SUPER_USER && !$executiveAccess); //todo make configurable on a per user basis $reportIDlookup = []; // if reports have custom IDs, match them to report IDs for future reference foreach($reportReference as $index => $reportInfo) { array_push($reportIDlookup, $reportInfo['customID']); $reportReference[$index]['url'] = $this->formatReportUrl($index, $reportInfo['customID']); } // if report ID is given, convert it to a report ID if (isset($_REQUEST['report'])) { $reportIndex = array_search($_REQUEST['report'], $reportIDlookup); if ($reportIndex !== false) { $_REQUEST['id'] = $reportIndex; } else { unset($_REQUEST['report']); unset($_REQUEST['id']); } } // if report ID isn't valid, send to the landing page if (intval($_REQUEST['id']) > sizeof($reportReference)) { unset($_REQUEST['id']); } if ($_REQUEST['page'] != 'settings') { $_REQUEST['lastPage'] = $_REQUEST['page']; } $pageInfo = $reportReference[$_REQUEST['id']]; $adminVisibility = $this->loadVisibilitySettings('admin', $reportReference); $executiveVisibility = $this->loadVisibilitySettings('executive', $reportReference); $executiveVisible = false; if ($pageInfo['reportName']) { $executiveVisible = in_array(USERID, $executiveVisibility->{$pageInfo['reportName']}); } if (!SUPER_USER) { if (!$executiveAccess || (!$executiveVisible && isset($_REQUEST['id']))) { die("Access denied! You do not have permission to view this page."); } } // todo sort out error display if ($pageInfo['type'] == 'table') { // error out if query doesn't begin with "select" if (!(strtolower(substr($pageInfo['sql'], 0, 6)) == "select")) { $pageInfo['sql'] = ''; $pageInfo['sqlErrorMsg'] = 'ERROR: SQL query is not a SELECT query.'; } // error out if no query elseif ($pageInfo['sql'] == '') { $pageInfo['sqlErrorMsg'] = 'ERROR: No SQL query defined.'; } elseif ($pageInfo['sql'] != '') { // execute the SQL statement $result = $this->sqlQuery($pageInfo['sql']); $pageInfo['sqlErrorMsg'] = $this->formatQueryResults($result); } } // construct URL redirect to alternate view if (SUPER_USER) { if ($_REQUEST['page'] == 'executiveView') { $viewUrl = 'index.php'; } else { $viewUrl = 'executiveView.php'; } if (isset($_REQUEST['report'])) { $viewUrl .= '?report=' . $_REQUEST['report']; } else if (isset($_REQUEST['report'])) { $viewUrl .= '?id=' . $_REQUEST['id']; } $viewUrl = urldecode($this->getUrl($viewUrl)); self::$smarty->assign('viewUrl', $viewUrl); } // todo update notes $updateNotes = "todo"; $iconUrls = array( 'first' => $this->getUrl("resources/tablesorter/tablesorter/images/icons/first.png"), 'prev' => $this->getUrl("resources/tablesorter/tablesorter/images/icons/prev.png"), 'next' => $this->getUrl("resources/tablesorter/tablesorter/images/icons/next.png"), 'last' => $this->getUrl("resources/tablesorter/tablesorter/images/icons/last.png"), ); foreach ($configSettings as $index => $setting) { if(isset($setting['key'])) { $getSetting = $this->getSystemSetting($setting['key']); if (isset($getSetting)) { $configSettings[$index]['default'] = $getSetting; } } } self::$smarty->assign('configSettings', $configSettings); // Get list of valid "target" REDCap projects for export feature $sql = " select u.project_id, app_title from redcap_user_rights as u left join redcap_projects as p on p.project_id = u.project_id where api_token is not null and api_import = 1 and username = '" . USERID . "' "; $sql = db_query($sql); $exportProjects = []; while ($row = db_fetch_assoc($sql)) { array_push($exportProjects, $row); } self::$smarty->assign('exportProjects', $exportProjects); self::$smarty->assign('executiveAccess', $executiveAccess); self::$smarty->assign('executiveUsers', $executiveUsers); self::$smarty->assign('superUser', SUPER_USER); self::$smarty->assign('reportId', $_REQUEST['id']); self::$smarty->assign('reportReference', $reportReference); self::$smarty->assign('updateNotes', $updateNotes); self::$smarty->assign('iconUrls', $iconUrls); self::$smarty->assign('exportEnabled', $exportEnabled); self::$smarty->assign('sqlErrorMsg', $pageInfo['sqlErrorMsg']); self::$smarty->assign('readmeUrl', $this->getUrl('README.md')); self::$smarty->assign('loadingGif', $this->getUrl('resources/loading.gif')); ?> <script> UIOWA_AdminDash.csvFileName = '<?= sprintf("%s.csv", $pageInfo['customID']); ?>'; UIOWA_AdminDash.renderDatetime = '<?= date("Y-m-d_His") ?>'; UIOWA_AdminDash.executiveAccess = <?= $executiveAccess ?>; UIOWA_AdminDash.executiveUsers = <?= json_encode($executiveUsers) ?>; UIOWA_AdminDash.adminVisibility = <?= json_encode($adminVisibility) ?>; UIOWA_AdminDash.executiveVisibility = <?= json_encode($executiveVisibility) ?>; UIOWA_AdminDash.reportIDs = <?= json_encode($reportIDlookup) ?>; UIOWA_AdminDash.requestHandlerUrl = "<?= $this->getUrl("requestHandler.php") ?>"; UIOWA_AdminDash.reportUrlTemplate = "<?= $this->getUrl( $executiveAccess ? "executiveView" : "index" . ".php", false, true) ?>"; UIOWA_AdminDash.settingsUrl = "<?= $this->getUrl("settings.php") ?>"; UIOWA_AdminDash.redcapBaseUrl = "<?= APP_PATH_WEBROOT_FULL ?>"; UIOWA_AdminDash.redcapVersionUrl = "<?= rtrim(APP_PATH_WEBROOT_FULL, '/') . APP_PATH_WEBROOT ?>"; UIOWA_AdminDash.hideColumns = []; UIOWA_AdminDash.reportReference = <?= json_encode($reportReference) ?>; UIOWA_AdminDash.showArchivedReports = false; UIOWA_AdminDash.superuser = <?= SUPER_USER ?>; UIOWA_AdminDash.theme = UIOWA_AdminDash.executiveAccess ? 'ice' : 'blue'; UIOWA_AdminDash.userID = '<?= USERID ?>'; UIOWA_AdminDash.lastTestQuery = { report: -1, columns: [], rowCount: 0, checked: false }; UIOWA_AdminDash.reportInfo = <?= json_encode($pageInfo) ?>; UIOWA_AdminDash.formattingReference = <?= file_get_contents($this->getUrl("config/formattingReference.json")) ?>; </script> <?php } private function generateReportReference() { $hideDeleted = !self::getSystemSetting('show-deleted-projects'); $hideArchived = !self::getSystemSetting('show-archived-projects'); $hidePractice = !self::getSystemSetting('show-practice-projects'); $hideFiltersSql = array(); if ($hideArchived) { $hideFiltersSql[] = "projects.status != 3"; } if ($hideDeleted) { $hideFiltersSql[] = "projects.date_deleted IS NULL"; } if ($hidePractice) { $hideFiltersSql[] = "projects.purpose != 0"; } $formattedFilterSql = ($hideDeleted || $hideArchived || $hidePractice) ? ("AND " . implode(" AND ", $hideFiltersSql)) : ''; $formattedWhereFilterSql = ($hideDeleted || $hideArchived || $hidePractice) ? ("WHERE " . implode(" AND ", $hideFiltersSql)) : ''; $reportReference = json_decode(file_get_contents($this->getUrl("config/reportReference.json")), true); foreach ($reportReference as $index => $report) { $reportReference[$index]['readOnly'] = true; $reportReference[$index]['type'] = 'table'; // load report sql from file and add filters $reportSql = file_get_contents($this->getUrl($reportReference[$index]['sql'])); $reportSql = str_replace('$formattedFilterSql', $formattedFilterSql, $reportSql); $reportSql = str_replace('$formattedWhereFilterSql', $formattedWhereFilterSql, $reportSql); $reportReference[$index]['sql'] = $reportSql; } ?> <script> var defaultReports = <?= json_encode($reportReference) ?>; UIOWA_AdminDash.defaultReportNames = $.map(defaultReports, function(report) { return report['reportName']; }); </script> <?php $customReports = $this->getSystemSetting('custom-reports'); foreach ($customReports as $report) { array_push($reportReference, $report); } return $reportReference; } private function formatQueryResults($result) { // $redcapProjectsLookup = $this->getRedcapProjectNames(); $isFirstRow = true; $record_id = 1; $tableData = array( 'headers' => array(), 'data' => array(), 'project_data' => array(), 'project_headers' => array() ); while ($row = db_fetch_assoc($result)) { // if (isset($row['project_id']) == 1) { // $pid = $row['project_id']; // $row['~app_title'] = $redcapProjectsLookup[$pid]; // } if ($isFirstRow) { // get column titles $tableData['headers'] = array_keys($row); foreach ($row as $key => $value) { $key = str_replace(' ', '_', preg_replace("/[^A-Za-z0-9 _]/", '', strtolower($key))); array_push($tableData['project_headers'], $key); //todo format headers for field names } $isFirstRow = false; } array_push($tableData['data'], $row); // save unformatted data for import to REDCap project todo - dealing with duplicate field names $index = 0; $fieldNames = array(); foreach ($row as $key => $value) { if (!array_search($key, $fieldNames)) { $row[$tableData['project_headers'][$index]] = $value; array_push($key, $fieldNames); $index++; } unset($row[$key]); } $row['record_id'] = $record_id; array_push($tableData['project_data'], $row); $record_id++; } if ($this->sqlError) { ?> <script> UIOWA_AdminDash.data = null; </script> <?php return "Failed to run report!<br /><br />" . $this->sqlError; } if (!$tableData['data']) { ?> <script> UIOWA_AdminDash.data = null; </script> <?php return "No results returned."; } else { ?> <script> UIOWA_AdminDash.data = <?= json_encode($tableData) ?>; </script> <?php return null; } } private function sqlQuery($query) { // execute the SQL statement $result = db_query($query); if (! $result || $result == 0) // sql failed { $this->sqlError = json_encode(db_error()); } return $result; } public function getRedcapProjectNames() { $sql = "SELECT project_id AS pid, TRIM(app_title) AS title FROM redcap_projects ORDER BY pid"; $query = db_query($sql); $projectNameHash = array(); while ($row = db_fetch_assoc($query)) { // $value = strip_tags($row['app_title']); $key = $row['pid']; $value = $row['title']; if (strlen($value) > 80) { $value = trim(substr($value, 0, 70)) . " ... " . trim(substr($value, -15)); } if ($value == "") { $value = "[Project title missing]"; } $projectNameHash[$key] = $value; } return $projectNameHash; } private function formatReportUrl($reportIndex, $customID) { unset($_GET['report']); unset($_GET['id']); if ($_GET['page'] == 'settings') { $_GET['page'] = 'index'; } $query = $_GET; $moduleParam = array('type' => 'module'); $query = $moduleParam + $query; if ($customID !== '') { $query['report'] = $customID; } else { $query['id'] = $reportIndex; } $url = http_build_query($query); $url = $this->getSystemSetting('use-api-urls') ? APP_PATH_WEBROOT_FULL . 'api/?' . $url : $_SERVER['PHP_SELF'] . '?' . $url; return ($url); } private function loadVisibilitySettings($type, $reportReference) { $storedVisibility = $this->getSystemSetting("report-visibility-" . $type); if ($storedVisibility) { $visibilityArray = $storedVisibility; } else { $visibilityArray = array(); foreach ($reportReference as $index => $reportInfo) { if ($type == 'admin') { $visibilityArray[$reportInfo['reportName']] = $reportInfo['defaultVisibility']; } if ($type == 'executive') { $visibilityArray[$reportInfo['reportName']] = array(); } } } return $visibilityArray; } public function saveConfigSetting() { $setting = json_decode(file_get_contents('php://input')); error_log(json_encode($setting)); $this->setSystemSetting($setting->key, $setting->value); } public function saveReportSettings() { $allSettings = json_decode(file_get_contents('php://input')); if ($allSettings->reportReference) { if ($allSettings->reportReference == 'none') { $this->removeSystemSetting('custom-reports'); } else { $this->setSystemSetting('custom-reports', $allSettings->reportReference); } } if ($allSettings->adminVisibility) { $this->setSystemSetting('report-visibility-admin', $allSettings->adminVisibility); } if ($allSettings->executiveVisibility) { $this->setSystemSetting('report-visibility-executive', $allSettings->executiveVisibility); } } public function exportDiagnosticFile() { $sql = "select external_module_id from redcap_external_modules where directory_prefix = 'admin_dash'"; $moduleID = db_fetch_assoc(db_query($sql))['external_module_id']; $sql = "select * from redcap_external_module_settings where external_module_id = $moduleID"; $result = db_query($sql); $data = array(); while ( $row = db_fetch_assoc( $result ) ) { $data[] = $row; } header('Content-disposition: attachment; filename=admin-dash-settings.json'); header('Content-type: application/json'); echo json_encode($data); } public function getApiToken($pid) { $sql = " select api_token from redcap_user_rights as u left join redcap_projects as p on p.project_id = u.project_id where u.project_id = $pid and username = '" . USERID . "' "; $sql = db_query($sql); $token = db_fetch_assoc($sql)['api_token']; echo $token; } public function testQuery() { $result = $this->sqlQuery(file_get_contents('php://input')); $data = array(); if ($this->sqlError) { $data['error'] = $this->sqlError; } else { while ( $row = db_fetch_assoc( $result ) ) { $data[] = $row; } } echo json_encode($data); } } ?><file_sep>/config/reports/usersByProject.sql SELECT projects.project_id AS 'PID', projects.app_title AS 'Project Title', CAST(CASE projects.status WHEN 0 THEN 'Development' WHEN 1 THEN 'Production' WHEN 2 THEN 'Inactive' WHEN 3 THEN 'Archived' ELSE projects.status END AS CHAR(50)) AS 'Status', counts.record_count AS 'Record Count', CAST(CASE projects.purpose WHEN 0 THEN 'Practice / Just for fun' WHEN 4 THEN 'Operational Support' WHEN 2 THEN 'Research' WHEN 3 THEN 'Quality Improvement' WHEN 1 THEN 'Other' ELSE projects.purpose END AS CHAR(50)) AS 'Purpose', GROUP_CONCAT(rights.username SEPARATOR '@@@') AS 'Users', DATE_FORMAT(projects.creation_time, '%Y-%m-%d') AS 'Creation Date', DATE_FORMAT(projects.last_logged_event, '%Y-%m-%d') AS 'Last Logged Event Date', DATEDIFF(now(), projects.last_logged_event) AS 'Days Since Last Event', COUNT(rights.username) AS 'Total Users', -- Hidden reference columns projects.project_id, projects.status, projects.date_deleted, GROUP_CONCAT(CAST( CASE WHEN info.user_suspended_time IS NOT NULL THEN 'T' ELSE 'F' END AS CHAR(1)) SEPARATOR '@@@') AS 'user_suspended_time' FROM redcap_projects AS projects LEFT JOIN redcap_record_counts AS counts ON projects.project_id = counts.project_id LEFT JOIN redcap_user_rights AS rights ON projects.project_id = rights.project_id LEFT JOIN redcap_user_information AS info ON rights.username = info.username $formattedWhereFilterSql GROUP BY projects.project_id ORDER BY projects.project_id<file_sep>/README.md ## Admin Dashboard ### Description The REDCap Admin Dashboard provides a number of reports on various project and user metadata in a sortable table view. This data can also be downloaded as a CSV formatted file (as well as other delimited formats). Additionally, user-defined reports can be included via custom SQL queries. Reports can optionally be shared with non-admin users in a limited format (Executive View). The following reports are enabled by default: * **Projects by User** (List of all users and the projects to which they have access) * **Users by Project** (List of all projects and the users which have access) * **Research Projects** (List of all projects that are identified as being used for research purposes) * **Development Projects** (List of all projects that are in Development Mode) * **All Projects** (List of all projects) Additional reports are included but hidden by default: * **External Modules by Project** (List of External Modules and the projects they are enabled in) * **Credentials Check (Project Titles)** (Reports to find strings related to usernames/passwords in project titles) * **Credentials Check (Instruments)** (Reports to find strings related to usernames/passwords in project instruments) * **Credentials Check (Fields)** (Reports to find strings related to usernames/passwords in project fields) All reports (built-in and user-defined) can be toggled on/off via the "Configure Reports" button located in the top left of any dashboard page. Hidden reports will not be shown in the navigation bar but can still be accessed via direct link. User-defined reports can also be added/edited/deleted in this view (built-in reports can be opened in a read-only view for reference purposes). ### Usage After downloading and enabling this module on your REDCap instance, a link to the Admin Dashboard will appear at the bottom of the Control Center sidebar. #### Filtering Just below the header for each column is an input for filtering. Simple text filtering can be performed as well as more complex filtering with the following: * **Greater/Less than (equal to):** `< <= >= >` * **Not:** `!` or `!=` * **Exact:** `"` or `=` * **And:** `&&` or `and` * **Range:** `-` or `to` * **Wildcard:** `*` or `?` * **Or:** `|` or `or` * **Fuzzy:** `~` Regular Expressions can also be used for filtering. #### Exporting Report results can be exported via the button located in the top right (just above the report title) of the page. By default, this button will download a CSV file with all rows titled with the name of the report and the date/time it was loaded. A dropdown menu with additional export options can be opened by clicking the arrow next to this button. The options are as follows: * **Separator:** The delimiter for exported data can be selected from 4 common options (comma, semicolon, tab, and space) or special formatting to JSON or an array format can be selected via two additional buttons. The separator can also be manually defined. * **Include:** 'All' will export all rows regardless of visibility due to pagination or filtering. 'Filtered' will only return the rows currently visible based on the current column filters set (this also does not care about pagination and will return rows not currently visible as well, so long as they meet the filter criteria). * **Export to:** 'Download' will initiate a file download of the exported data. Additionally, the filename can be defined and the appended date/timestamp can be toggled on/off. 'Popup' will open a popup window with the exported data in a text box so it can be easily copied and pasted elsewhere. When exporting a report that includes the "Purpose Specified" column, it will split the purpose data into separate columns marked as TRUE/FALSE for easier analysis. #### Executive Dashboard Non-admin users with a valid REDCap login can be granted access to a limited version of the dashboard without link formatting (projects, emails, etc). The reports accessible in this view can be customized on a per-user basis via the "Configure Reports" button located in the top left of the page. By default, no reports are enabled for Executive View and attempts to access it by non-admin users will display an "access denied" error instead (this will also happen if a user attempts to follow a direct link to a specific report that they do not have permission to access). Access to this view can be granted by whitelisting usernames via the module configuration page. Admins can switch between the "Admin" and "Executive" views by clicking the button located at the bottom of any dashboard page. Admins can also access the Configure Reports button from either view, but both of these buttons will be hidden from non-admin users. When viewing the Executive Dashboard as an admin, the "Viewing as" dropdown is visible below the page header. This allows you to quickly switch between whitelisted users and preview their dashboard views and ensure the proper set of reports are visible/invisible to them. This dropdown is also available in the Configure Reports modal, where report visibility can be modified per-user. **NOTE:** Changes made to report visibility will only take effect after the "Save" button is pressed. This means changing one user's permissions and switching to another user via the dropdown will cause any changes to the first user to be lost. This is intentional as it ensures no changes are ever saved without explicit acknowledgement (reducing the chance of an executive user gaining access to a report they should not have access to). For executive users, there is no way to directly access this view through the REDCap UI. An admin will need to provide them with a direct link to the page so they can bookmark it for future use. ### User Defined Reports Additional reports can be defined through custom SQL queries. They can be added by clicking the "Configure Reports" button and then the "Add New Report" button found at the bottom of the report list. The following information can be defined: * **Title** - The name of your report. This value must be unique (no two reports can have the same title) and cannot be blank. * **Icon** - An icon that will appear next to your report title in the report navigation bar. This accepts most "solid" icons from Font Awesome and will display a preview if the icon name entered is valid. * **Description** - A short description that will appear under the report title when a report is rendered. * **Report ID** - A unique alphabetical string that can be used as an alternative to the report index when loading a report directly via URL. This can be useful for permanently bookmarking reports (report indexes can change as reports are added and deleted so they are not reliable in this respect). The report index can still be used even if a custom ID is defined. * **SQL Query** - A valid SQL SELECT query that is used to populate your report. Please exercise caution when adding your own SQL queries. Executing queries with large result sets could impact server performance. After clicking the "Save" button, your report will be added to the list with all visibility toggles set to "Hide". The blue pen and paper button can be used to edit your existing reports and the red trashcan button can be used to delete reports. Please note that user-defined reports are not affected by the "Show archived/deleted projects" configuration options (any filtering of this sort should be included in your query). When the following column aliases are used in queries (e.g. `SELECT app_title AS 'Project Title'`), their results will receive special formatting in the Admin View (same as the built-in reports): * 'Project Title' - Returns a link to the related project. * 'PID' - Returns a link to the related project's settings page inside the Control Center. * 'Username' - Returns a link to the related user's information page inside the Control Center). * 'Email'/'PI Email' - Returns a mailto link addressed to the given email address. Some additional special formatting may be available (if a built-in report uses it, a custom report can use it), but may require more specific usage to work correctly. The built-in reports can be opened in a read-only view and used for reference if you would like to take advantage of any special formatting. ### Configuration Options * **Show "Practice / Just for Fun" projects:** Enabling this option will include projects marked as "Practice / Just for Fun" in report views (this is enabled by default). * **Show archived projects:** Enabling this option will include archived projects in report views. Archived project titles are grey in color. * **Show deleted projects:** Enabling this option will include projects marked for deletion in report views. Deleted project titles are red in color. * **Mark suspended users with red [suspended] tag:** Enabling this option will add a red "[suspended]" tag after suspended usernames in the reports that they appear. Suspended users will always be included in default reports regardless of this setting; it only changes how they are displayed. The following settings are specific to optional reports: * **Additional search term for Login Credentials Check reports:** This repeatable field can be used to define additional search terms to be queried when running the Login Credentials Check reports. This can be helpful for defining institution specific usernames. See [this page](https://www.w3schools.com/sql/sql_wildcards.asp) for information about using wildcards in search terms. The following settings are specific to Executive View: * **Username to allow access to the Executive View:** This repeatable field can be used to define which REDCap users are allowed access to the Executive View. * **Enable export button in Executive View:** Enabling this option will allow the Export button to appear on the Executive View (disabled by default).<file_sep>/config/reports/projectsByUser.sql SELECT info.username AS 'Username', info.user_lastname AS 'Last Name', info.user_firstname AS 'First Name', info.user_email AS 'Email', GROUP_CONCAT(projects.app_title SEPARATOR '@@@') AS 'Project Titles', COUNT(projects.project_id) AS 'Total Projects', -- Hidden reference columns GROUP_CONCAT(projects.project_id SEPARATOR '@@@') AS 'project_id', GROUP_CONCAT(projects.status SEPARATOR '@@@') AS 'status', GROUP_CONCAT(CAST( CASE WHEN projects.date_deleted IS NOT NULL THEN 'T' ELSE 'F' END AS CHAR(1)) SEPARATOR '@@@') AS 'date_deleted', info.user_suspended_time FROM redcap_user_information AS info, redcap_projects AS projects, redcap_user_rights AS access WHERE info.username = access.username AND access.project_id = projects.project_id $formattedFilterSql GROUP BY info.ui_id ORDER BY info.user_lastname, info.user_firstname, info.username<file_sep>/config/reports/modulesInProjects.sql SELECT REPLACE(directory_prefix, '_', ' ') AS 'Module Title', GROUP_CONCAT(DISTINCT CAST(projects.project_id AS CHAR(50)) SEPARATOR ', ') AS 'Project Titles', GROUP_CONCAT(DISTINCT CAST(users.user_email AS CHAR(50)) SEPARATOR ', ') AS 'User Emails', GROUP_CONCAT(CAST(CASE projects.status WHEN 0 THEN 'Development' WHEN 1 THEN 'Production' WHEN 2 THEN 'Inactive' WHEN 3 THEN 'Archived' ELSE projects.status END AS CHAR(50))) AS 'Project Statuses (Hidden)', GROUP_CONCAT(CAST(CASE WHEN projects.date_deleted IS NULL THEN 'N/A' ELSE projects.date_deleted END AS CHAR(50))) AS 'Project Deleted Date (Hidden)', COUNT(DISTINCT projects.project_id) AS 'Total Projects' FROM redcap_external_module_settings AS settings LEFT JOIN redcap_external_modules ON redcap_external_modules.external_module_id = settings.external_module_id LEFT JOIN redcap_projects AS projects ON projects.project_id = settings.project_id LEFT JOIN redcap_user_rights AS rights ON rights.project_id = projects.project_id LEFT JOIN redcap_user_information AS users ON users.username = rights.username WHERE settings.key = 'enabled' AND (settings.value = 'true' OR settings.value = 'enabled') AND settings.project_id IS NOT NULL $formattedFilterSql GROUP BY settings.external_module_id ORDER BY directory_prefix<file_sep>/requestHandler.php <?php /** @var \UIOWA\AdminDash\AdminDash $module */ if ($_REQUEST['type'] == 'saveConfigSetting') { $module->saveConfigSetting(); } elseif ($_REQUEST['type'] == 'saveReportSettings') { $module->saveReportSettings(); } elseif ($_REQUEST['type'] == 'exportDiagnosticFile') { $module->exportDiagnosticFile(); } elseif ($_REQUEST['type'] == 'getApiToken') { $module->getApiToken($_POST['pid']); } elseif ($_REQUEST['type'] == 'testQuery') { $module->testQuery(); }<file_sep>/index.php <?php /** @var \UIOWA\AdminDash\AdminDash $module */ $page = new HtmlPage(); $page->PrintHeaderExt(); include APP_PATH_VIEWS . 'HomeTabs.php'; $module->initializeSmarty(); $module->includeJsAndCss(); $module->initializeVariables(); $module->displayTemplate('nav.tpl'); $module->displayTemplate('table.tpl');<file_sep>/config/reports/researchProjects.sql SELECT projects.project_id AS PID, app_title AS 'Project Title', CAST(CASE status WHEN 0 THEN 'Development' WHEN 1 THEN 'Production' WHEN 2 THEN 'Inactive' WHEN 3 THEN 'Archived' ELSE status END AS CHAR(50)) AS 'Status', CAST(CASE WHEN projects.date_deleted IS NULL THEN 'N/A' ELSE projects.date_deleted END AS CHAR(50)) AS 'Project Deleted Date (Hidden)', record_count AS 'Record Count', purpose_other AS 'Purpose Specified', project_pi_lastname AS 'PI Last Name', project_pi_firstname AS 'PI First Name', project_pi_email AS 'PI Email', project_irb_number AS 'IRB Number', DATE_FORMAT(creation_time, '%Y-%m-%d') AS 'Creation Date', DATE_FORMAT(last_logged_event, '%Y-%m-%d') AS 'Last Logged Event Date', DATEDIFF(now(), last_logged_event) AS 'Days Since Last Event' FROM redcap_projects as projects LEFT JOIN redcap_record_counts ON projects.project_id = redcap_record_counts.project_id WHERE purpose = 2 -- 'Research' $formattedFilterSql ORDER BY app_title<file_sep>/config/reports/allProjects.sql SELECT projects.project_id AS 'PID', app_title AS 'Project Title', CAST(CASE WHEN record_count IS NULL THEN 0 ELSE record_count END AS CHAR(50)) AS 'Record Count', CAST(CASE status WHEN 0 THEN 'Development' WHEN 1 THEN 'Production' WHEN 2 THEN 'Inactive' WHEN 3 THEN 'Archived' ELSE status END AS CHAR(50)) AS 'Status', CAST(CASE purpose WHEN 0 THEN 'Practice / Just for fun' WHEN 4 THEN 'Operational Support' WHEN 2 THEN 'Research' WHEN 3 THEN 'Quality Improvement' WHEN 1 THEN 'Other' ELSE purpose END AS CHAR(50)) AS 'Purpose', CAST(CASE WHEN projects.date_deleted IS NULL THEN 'N/A' ELSE projects.date_deleted END AS CHAR(50)) AS 'Project Deleted Date (Hidden)', DATE_FORMAT(creation_time, '%Y-%m-%d') AS 'Creation Date', DATE_FORMAT(last_logged_event, '%Y-%m-%d') AS 'Last Logged Event Date', DATEDIFF(now(), last_logged_event) AS 'Days Since Last Event' FROM redcap_projects AS projects LEFT JOIN redcap_record_counts ON projects.project_id = redcap_record_counts.project_id $formattedWhereFilterSql ORDER BY app_title<file_sep>/adminDash.js (function($, window, document) { $(document).ready(function () { UIOWA_AdminDash.updateReportTabs(UIOWA_AdminDash.userID); $('#pagecontainer').css('cursor', 'default'); $('#loading').hide(); // build report table if (UIOWA_AdminDash.data != null) { var data = UIOWA_AdminDash.data['data']; var headers = Object.values(UIOWA_AdminDash.data['headers']); var table = $('#reportTable'); var specialFormatting = {}; $.each(data, function (i, row) { var formattedRow = []; $.each(headers, function (j, header) { formattedRow.push(row[header]); }); data[i] = formattedRow; }); if (UIOWA_AdminDash.reportInfo['formatting']) { specialFormatting = UIOWA_AdminDash.reportInfo['formatting']; data = UIOWA_AdminDash.formatTableData(data, headers, specialFormatting); } var strTable = ""; strTable += "<thead>"; $.each(headers, function(headerIndex, headerValue) { strTable += "<th>"; strTable += headerValue; strTable += "</th>"; }); strTable += "</thead>"; $.each(data, function(rowIndex, rowValue) { strTable += "<tr>"; $.each(rowValue, function(cellIndex, cellValue) { strTable += "<td>"; strTable += cellValue; strTable += "</td>"; }); strTable += "</tr>"; }); // get column indexes to hide in export var columnId = 0; var hiddenExportColumns = []; $.each(specialFormatting, function(key, value) { if (value['display'] == 1 || value['display'] == 3) { hiddenExportColumns.push(columnId); } columnId++; }); table.append(strTable); table.tablesorter({ theme: UIOWA_AdminDash.theme, widthFixed: true, usNumberFormat: false, sortReset: false, sortRestart: true, widgets: ['zebra', 'filter', 'stickyHeaders', 'pager', 'output'], widgetOptions: { // output default: '{page}/{totalPages}' // possible variables: {size}, {page}, {totalPages}, {filteredPages}, {startRow}, {endRow}, {filteredRows} and {totalRows} // also {page:input} & {startRow:input} will add a modifiable input in place of the value pager_output: '{startRow:input} – {endRow} / {totalRows} rows', // '{page}/{totalPages}' // apply disabled classname to the pager arrows when the rows at either extreme is visible pager_updateArrows: true, // starting page of the pager (zero based index) pager_startPage: 0, // Number of visible rows pager_size: 10, // Save pager page & size if the storage script is loaded (requires $.tablesorter.storage in jquery.tablesorter.widgets.js) pager_savePages: true, // if true, the table will remain the same height no matter how many records are displayed. The space is made up by an empty // table row set to a height to compensate; default is false pager_fixedHeight: false, // remove rows from the table to speed up the sort of large tables. // setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled. pager_removeRows: false, // removing rows in larger tables speeds up the sort // use this format: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}" // where {page} is replaced by the page number, {size} is replaced by the number of records to show, // {sortList:col} adds the sortList to the url into a "col" array, and {filterList:fcol} adds // the filterList to the url into an "fcol" array. // So a sortList = [[2,0],[3,0]] becomes "&col[2]=0&col[3]=0" in the url // and a filterList = [[2,Blue],[3,13]] becomes "&fcol[2]=Blue&fcol[3]=13" in the url pager_ajaxUrl: null, // modify the url after all processing has been applied pager_customAjaxUrl: function (table, url) { return url; }, // ajax error callback from $.tablesorter.showError function // pager_ajaxError: function( config, xhr, settings, exception ){ return exception; }; // returning false will abort the error message pager_ajaxError: null, // modify the $.ajax object to allow complete control over your ajax requests pager_ajaxObject: { dataType: 'json' }, // process ajax so that the following information is returned: // [ total_rows (number), rows (array of arrays), headers (array; optional) ] // example: // [ // 100, // total rows // [ // [ "row1cell1", "row1cell2", ... "row1cellN" ], // [ "row2cell1", "row2cell2", ... "row2cellN" ], // ... // [ "rowNcell1", "rowNcell2", ... "rowNcellN" ] // ], // [ "header1", "header2", ... "headerN" ] // optional // ] pager_ajaxProcessing: function (ajax) { return [0, [], null]; }, // css class names that are added pager_css: { container: 'tablesorter-pager', // class added to make included pager.css file work errorRow: 'tablesorter-errorRow', // error information row (don't include period at beginning); styled in theme file disabled: 'disabled' // class added to arrows @ extremes (i.e. prev/first arrows "disabled" on first page) }, // jQuery selectors pager_selectors: { container: '.pager', // target the pager markup (wrapper) first: '.first', // go to first page arrow prev: '.prev', // previous page arrow next: '.next', // next page arrow last: '.last', // go to last page arrow gotoPage: '.gotoPage', // go to page selector - select dropdown that sets the current page pageDisplay: '.pagedisplay', // location of where the "output" is displayed pageSize: '.pagesize' // page size selector - select dropdown that sets the "size" option }, //stickyHeaders_attachTo: '.redcap-home-navbar-collapse', stickyHeaders_offset: 50, output_separator : ',', // ',' 'json', 'array' or separator (e.g. ';') output_ignoreColumns : hiddenExportColumns, // columns to ignore [0, 1,... ] (zero-based index) output_hiddenColumns : true, // include hidden columns in the output output_includeFooter : true, // include footer rows in the output output_includeHeader : true, // include header rows in the output output_headerRows : false, // output all header rows (if multiple rows) output_dataAttrib : 'data-export', // data-attribute containing alternate cell text output_delivery : 'd', // (p)opup, (d)ownload output_saveRows : 'a', // (a)ll, (v)isible, (f)iltered, jQuery filter selector (string only) or filter function output_duplicateSpans: true, // duplicate output data in tbody colspan/rowspan output_replaceQuote : '\u201c;', // change quote to left double quote output_includeHTML : false, // output includes all cell HTML (except the header cells) output_trimSpaces : true, // remove extra white-space characters from beginning & end output_wrapQuotes : false, // wrap every cell output in quotes output_popupStyle : 'width=580,height=310', output_saveFileName : UIOWA_AdminDash.csvFileName, // callback executed after the content of the table has been processed output_formatContent : function(config, widgetOptions, data) { // data.isHeader (boolean) = true if processing a header cell // data.$cell = jQuery object of the cell currently being processed // data.content = processed cell content (spaces trimmed, quotes added/replaced, etc) // data.columnIndex = column in which the cell is contained // data.parsed = cell content parsed by the associated column parser return data.content.replace(/ \[suspended]/ig, '').replace(/Email All/ig, ''); }, // callback executed when processing completes output_callback : function(config, data, url) { // return false to stop delivery & do something else with the data // return true OR modified data (v2.25.1) to continue download/output if (config['widgetOptions']['output_delivery'] == 'd') { data = '\ufeff' + data; } return data; }, // callbackJSON used when outputting JSON & any header cells has a colspan - unique names required output_callbackJSON : function($cell, txt, cellIndex) { return txt + '(' + cellIndex + ')'; }, // the need to modify this for Excel no longer exists //output_encoding : 'data:application/octet-stream;charset=utf8', // override internal save file code and use an external plugin such as // https://github.com/eligrey/FileSaver.js output_savePlugin : null /* function(config, widgetOptions, data) { var blob = new Blob([data], {type: widgetOptions.output_encoding}); saveAs(blob, widgetOptions.output_saveFileName); } */ } }); // additonal post-tablesorter formatting columnId = 1; $.each(specialFormatting, function(key, value) { var column = $('td:nth-child(' + columnId + ')'); column.each(function (i, td) { var links = $('a', td); var csvList = ''; var mailto = 'mailto:?bcc='; // format link lists into csv for export if (links.length > 1) { links.each(function (j, link) { var linkText = $(link).text(); if (value['link'] == 'Email') { mailto += linkText + ';'; } if (csvList == '') { csvList = linkText; } else { csvList += ',' + linkText; } }); if (value['link'] == 'Email') { // add 'Email All' button where appropriate $(td).append('<div style="padding-top:10px;"><button style="float:right;" class="btn btn-info btn-sm" onclick="location.href=\'' + mailto + '\'">Email All</button></div>') } $(td).attr('data-export', csvList); } }); if (value['display'] == 2 || value['display'] == 3) { column = $('td:nth-child(' + columnId + '),th:nth-child(' + columnId + ')'); column.hide(); } columnId++; }); var $this = $(".output-button"); $this.find('.dropdown-toggle').click(function(e) { // this is needed because clicking inside the dropdown will close // the menu with only bootstrap controlling it. $this.find('.dropdown-menu').toggle(); return false; }); // make separator & replace quotes buttons update the value $this.find('.output-separator').click(function() { $this.find('.output-separator').removeClass('active'); var txt = $(this).addClass('active').html(); $this.find('.output-separator-input').val( txt ); var filename = $this.find('.output-filename'); var filetype = (txt === 'json' || txt === 'array') ? 'js' : txt === ',' ? 'csv' : 'txt'; filename.val(function(i, v) { // change filename extension based on separator return v.replace(/\.\w+$/, '.' + filetype); }); var outputType = $($this.find('.output-type.active'))[0].innerText; if (outputType == 'File') { $this.find('.download').html('<span class="fas fa-download"></span> Export ' + filetype.toUpperCase() + ' File'); } else if (outputType == 'Popup') { $this.find('.download').html('<span class="far fa-window-maximize"></span> Open ' + filetype.toUpperCase() + ' Popup'); } return false; }); $this.find('.output-type').click(function() { var outputType = $(this)[0].innerText; var filename = $this.find('.output-filename'); var txt = $($this.find('.output-separator.active')).html(); var filetype = (txt === 'json' || txt === 'array') ? 'js' : txt === ',' ? 'csv' : 'txt'; if (outputType == 'File') { $this.find('.download').html('<span class="fas fa-download"></span> Export ' + filetype.toUpperCase() + ' File'); $this.find('.filename-field-display').removeClass('hidden'); $this.find('.separator-field-display').removeClass('hidden'); $this.find('.include-field-display').removeClass('hidden'); $this.find('.target-field-display').addClass('hidden'); $this.find('.download').prop('disabled', false); } else if (outputType == 'Popup') { $this.find('.download').html('<span class="far fa-window-maximize"></span> Open ' + filetype.toUpperCase() + ' Popup'); $this.find('.filename-field-display').addClass('hidden'); $this.find('.separator-field-display').removeClass('hidden'); $this.find('.include-field-display').removeClass('hidden'); $this.find('.target-field-display').addClass('hidden'); $this.find('.download').prop('disabled', false); } else if (outputType == 'Project') { $this.find('.download').html('<span class="far fa-list-alt"></span> Send to REDCap'); $this.find('.filename-field-display').addClass('hidden'); $this.find('.separator-field-display').addClass('hidden'); $this.find('.include-field-display').addClass('hidden'); $this.find('.target-field-display').removeClass('hidden'); $this.find('.download').prop('disabled', true); } //return false; }); // clicking the download button; all you really need is to // trigger an "output" event on the table $this.find('.download').click(function() { var outputType = $($this.find('.output-type.active'))[0].innerText; if (outputType == 'Project') { $('#projectImportConfirm').modal({backdrop: 'static', keyboard: false}); } else { var typ, $table = $("#reportTable"), wo = $table[0].config.widgetOptions, val = $this.find('.output-filter-all :checked').attr('class'); wo.output_saveRows = val === 'output-filter' ? 'f' : val === 'output-visible' ? 'v' : // checked class name, see table.config.checkboxClass val === 'output-selected' ? '.checked' : val === 'output-sel-vis' ? '.checked:visible' : 'a'; val = $this.find('.output-download-popup :checked').attr('class'); wo.output_delivery = val === 'output-download' ? 'd' : 'p'; wo.output_separator = $this.find('.output-separator-input').val(); //wo.output_replaceQuote = $this.find('.output-replacequotes').val(); //wo.output_trimSpaces = $this.find('.output-trim').is(':checked'); //wo.output_includeHTML = $this.find('.output-html').is(':checked'); //wo.output_wrapQuotes = $this.find('.output-wrap').is(':checked'); var filename = $this.find('.output-filename').val(); if ($this.find('.filename-datetime').is(':checked')) { var splitFilename = filename.split('.'); splitFilename.splice(-1, 0, UIOWA_AdminDash.renderDatetime); wo.output_saveFileName = splitFilename.join('.'); } else { wo.output_saveFileName = filename; } $table.trigger('outputTable'); return false; } }); $this.show(); $('#report-content').show(); } else { $('#no-results').show(); } if (UIOWA_AdminDash.hideColumns) { for (var i in UIOWA_AdminDash.hideColumns) { $('#reportTable tr > *:nth-child(' + UIOWA_AdminDash.hideColumns[i] + ')').hide(); $('#reportTable-sticky tr > *:nth-child(' + UIOWA_AdminDash.hideColumns[i] + ')').hide(); } } //todo ??? //if (sessionStorage.getItem("selectedUser") && UIOWA_AdminDash.superuser) { // $('.executiveUser').val( sessionStorage.getItem("selectedUser") ); // UIOWA_AdminDash.userID = $('.executiveUser')[0].value; //} //$('.executiveUser').change(function() { // $('.executiveUser').not(this).val( this.value ); // sessionStorage.setItem("selectedUser", this.value); // UIOWA_AdminDash.updateSettingsModal(this.value); //}); $('.output-filename').val(UIOWA_AdminDash.csvFileName); $('#exportProjectSelect').change(function() { $('#pagecontainer').css('cursor', 'progress'); $this.find('.download').prop('disabled', true); var projectLink = $('.target-project-link'); projectLink.html($('#exportProjectSelect option:selected').text()); projectLink.attr('href', UIOWA_AdminDash.redcapVersionUrl + 'ProjectSetup/index.php?pid=' + $('#exportProjectSelect').val()); if (this.value != '') { $.ajax({ method: 'POST', url: UIOWA_AdminDash.requestHandlerUrl + '&type=getApiToken', data: { pid: $this.find('#exportProjectSelect')[0].value } }) .done(function(token) { $.ajax({ method: 'POST', url: UIOWA_AdminDash.redcapBaseUrl + 'api/', data: { token: token, content: 'metadata', format: 'json', field: JSON.stringify(UIOWA_AdminDash.data['project_headers']) }, success: function(data) { var projectFields = $.map(data, function (field) { return field['field_name']; }); var requiredFields = UIOWA_AdminDash.data['project_headers']; var validProject = projectFields.filter(function (elem) { return requiredFields.indexOf(elem) > -1; }).length == requiredFields.length; // if project contains required fields for import, enable button if (validProject) { $this.find('.download').prop('disabled', false); } else { $this.find('.download').prop('disabled', true); $('#invalidProjectWarning').modal('show'); } $('#pagecontainer').css('cursor', 'default'); } }) }); } else { $this.find('.download').prop('disabled', true); } }); $('#invalidProjectWarning').on('hidden.bs.modal', function () { $('#confirmProjectUpdate').hide(); $('.force-import').hide(); $('.force-import-close').html('Close'); }); $('.show-project-warning-text').click(function () { $('#confirmProjectUpdate').show(); $('.force-import').show(); $('.force-import-close').html('Cancel'); }); $('.confirm-import').click(function () { $(this).prop('disabled', true); $('.import-close').prop('disabled', true); $(this).html('<i class="fas fa-spinner fa-spin import-progress"></i>'); // get project api token $.ajax({ method: 'POST', url: UIOWA_AdminDash.requestHandlerUrl + '&type=getApiToken', data: { pid: $this.find('#exportProjectSelect')[0].value } }) .done(function(token) { // import data $.ajax({ method: 'POST', url: UIOWA_AdminDash.redcapBaseUrl + 'api/', data: { token: token, content: 'record', format: 'json', data: JSON.stringify(UIOWA_AdminDash.data['project_data']) }, success: function(data) { $('.confirm-import').html('<i class="fas fa-check"></i> Success').removeClass('btn-primary').addClass('btn-success'); $('#importInfoText').hide(); $('.import-close').html('Close').prop('disabled', false); if (data['count']) { $('#importedRecordCount').html(data['count']); $('#importCompleteText').show(); } }, error: function(data) { var response = data['responseJSON']; $('.confirm-import').html('<i class="fas fa-times"></i> Error').removeClass('btn-primary').addClass('btn-danger'); $('#importInfoText').hide(); $('.import-close').html('Close').prop('disabled', false); if (response['error']) { $('#redcapApiErrorText').html(response['error']); $('#importErrorText').show(); } else { $('#redcapApiErrorText').html('An unknown error occurred.'); $('#importErrorText').show(); } } }) }) }); $('#projectImportConfirm').on('hidden.bs.modal', function () { $('#importErrorText').hide(); $('#importCompleteText').hide(); $('#importInfoText').show(); $('.import-close').html('Cancel'); $('.confirm-import').html('Import').prop('disabled', false).removeClass('btn-danger btn-success').addClass('btn-primary'); }); $('.force-import').click(function () { $.ajax({ method: 'POST', url: UIOWA_AdminDash.requestHandlerUrl + '&type=getApiToken', data: { pid: $this.find('#exportProjectSelect')[0].value } }) .done(function (token) { UIOWA_AdminDash.importProjectMetadata(token); }); }); $('.open-settings').click(function() { window.open(UIOWA_AdminDash.settingsUrl, "_self"); }); UIOWA_AdminDash.updateReportTabs(''); $('#primaryUserSelect').change(function() { UIOWA_AdminDash.updateReportTabs($('#primaryUserSelect').val()); }); // Enable tooltips $('[data-toggle="tooltip"]').tooltip(); }); }(window.jQuery, window, document)); var UIOWA_AdminDash = {}; UIOWA_AdminDash.formatTableData = function(data, headers, formatting) { var formattingReference = UIOWA_AdminDash.formattingReference['links']; var formattedData = {}; // loop through each row $.each(data, function(rowIndex, row) { //var pidIndex = headers.indexOf('project_id'); //var projectIds = (row[pidIndex] == null) ? null : row[pidIndex].split('@@@'); //headers = $.grep(headers, function(value) { // return value != 'project_id'; //}); //delete row[pidIndex]; //console.log(JSON.parse(JSON.stringify(projectIds))); formattedData[rowIndex] = {}; var newHeaders = []; var newValues = []; // loop through each cell $.each(row, function(cellIndex, cell) { formattedData[rowIndex][cellIndex] = ''; var columnHeader = headers[cellIndex]; var cellValues = (cell == null) ? [] : cell.split('@@@'); // prepare reference columns, otherwise use self var projectIds = (row[headers.indexOf('project_id')]) ? row[headers.indexOf('project_id')].split('@@@') : []; var projectStatuses = (row[headers.indexOf('status')]) ? row[headers.indexOf('status')].split('@@@') : []; var projectDeletedDates = (row[headers.indexOf('date_deleted')]) ? row[headers.indexOf('date_deleted')].split('@@@') : []; var userSuspendedTimes = (row[headers.indexOf('user_suspended_time')]) ? row[headers.indexOf('user_suspended_time')].split('@@@') : []; // repeat for each group item in cell $.each(cellValues, function (index, value) { var columnFormatting = formatting[columnHeader] ? formatting[columnHeader] : { linkGroup: 'none', link: 'not set' }; var linkGroup = columnFormatting['linkGroup']; var linkType = columnFormatting['link']; if (linkType != 'not set' && linkGroup != 'Code Lookup') { var linkUrl = ''; var linkStyle = ''; var suspendedTag = ''; if (linkType == 'Custom') { linkUrl = columnFormatting['custom'].replace('{value}', value); } else if (linkType == 'Survey Hash') { linkUrl = UIOWA_AdminDash.redcapBaseUrl + formattingReference[linkGroup][linkType] + value; } else if (linkType == 'Email') { linkUrl = 'mailto:' + value; } else if (linkGroup == 'Project Links (project_id)') { if (projectDeletedDates != null) { var status = projectStatuses[index]; var dateDeleted = projectDeletedDates[index]; if (status == '3') { linkStyle = 'id="archived"'; } if (dateDeleted != 'F' && dateDeleted != null) { linkStyle = 'id="deleted"'; } } linkUrl = UIOWA_AdminDash.redcapVersionUrl + formattingReference[linkGroup][linkType] + projectIds[index]; } else if (linkGroup == 'User Links (username)') { if (userSuspendedTimes != null) { var suspended = userSuspendedTimes[index]; if (suspended != 'F' && suspended != null) { suspendedTag = '<br /><span id="suspended">[suspended]</span>'; } } linkUrl = UIOWA_AdminDash.redcapVersionUrl + formattingReference[linkGroup][linkType] + value; } formattedData[rowIndex][cellIndex] += '<a href="' + linkUrl + '" target="_blank"' + linkStyle + '>' + value + '</a>' + suspendedTag + '<br />'; } else if (linkType == 'Project Purpose' || linkType == 'Project Status') { formattedData[rowIndex][cellIndex] = formattingReference[linkGroup][linkType][value]; } else if (linkType == 'Research Purpose') { value = value.split(','); value = $.map(value, function (index, item) { return formattingReference[linkGroup][linkType][item]; }); formattedData[rowIndex][cellIndex] = value.join(', '); } else if (linkType == 'Research Purpose (Split)') { //todo value = value.split(','); $.each(formattingReference[linkGroup][linkType], function (index, item) { newHeaders.push(item); if (value.indexOf(index) != -1) { newValues.push('TRUE'); } else { newValues.push('FALSE'); } }); //formattedData[rowIndex][cellIndex] = formattingReference[linkGroup][linkType][value]; } else { formattedData[rowIndex][cellIndex] += value + '<br />'; } }); }); //console.log(newHeaders); //console.log(newValues); //formattedData.splice(0, 0, newValues) }); return formattedData; }; UIOWA_AdminDash.updateReportTabs = function(user) { var keys = Object.keys(UIOWA_AdminDash.adminVisibility); for (var i in keys) { var reportTitle = keys[i]; var adminVisible = UIOWA_AdminDash.adminVisibility[reportTitle]; var executiveVisible = $.inArray(user, UIOWA_AdminDash.executiveVisibility[reportTitle]) != -1; var reportTab = $('.report-tabs > li ').filter(function() { return $('.report-title', this).text() === reportTitle; }); if (!adminVisible && !UIOWA_AdminDash.executiveAccess) { reportTab.hide("slow"); } else if (!executiveVisible && UIOWA_AdminDash.executiveAccess) { reportTab.hide(); } else { reportTab.show("slow"); } } }; UIOWA_AdminDash.importProjectMetadata = function (token) { var reportTitle = $('#reportTitle').html().trim().toLowerCase().split(' ').join('_'); var metadata = []; var fieldInfo = { field_name: 'record_id', form_name: reportTitle, section_header: '', field_type: 'text', field_label: 'Record ID' }; metadata.push(fieldInfo); $.each(UIOWA_AdminDash.data['project_headers'], function (index, value) { fieldInfo = { field_name: value, form_name: reportTitle, section_header: '', field_type: 'text', field_label: UIOWA_AdminDash.data['headers'][index] }; metadata.push(fieldInfo); }); $.ajax({ method: 'POST', url: UIOWA_AdminDash.redcapBaseUrl + 'api/', data: { token: token, content: 'metadata', format: 'json', data: JSON.stringify(metadata) }, success: function(data) { console.log(data); $('#invalidProjectWarning').modal('hide'); $('#projectImportConfirm').modal({backdrop: 'static', keyboard: false}); }, error: function(data) { var response = data['responseJSON']; if (response['error']) { alert(response['error']); } else { alert('An unknown error occurred when attempting to update your project.'); } } }) };
3f0373f673cec003e031f9242955e6c531aafee9
[ "Markdown", "SQL", "JavaScript", "PHP" ]
10
PHP
tmotoole/redcap-admin-dashboard
96384c19f6a33e71d6219431433f6c74409805ba
62d79a5e485e8abfdd220089a868142995ff2e4e
refs/heads/main
<repo_name>mastertar/softwaresatAssistantBot<file_sep>/main.py import discord import os from keep_alive import keep_alive from discord.ext import commands # from replit import db # db["key"] = "value" # value = db["key"] # del db["key"] # keys = db.keys() # matches = db.prefix("prefix") # db["number"] = { # "counter": 1, # } # print(db["number"]) import sqlite3 conn = sqlite3.connect("deezgunz.db") # db - database cursor = conn.cursor() create_table = """ CREATE TABLE deezgunz ( userid varchar(18) NOT NULL, thread INT DEFAULT 0 ); """ # cursor.execute(create_table) conn.commit() intents = discord.Intents.all() bot = commands.Bot(command_prefix=',', intents=intents) @bot.event async def on_ready(): print("I'm in") print(bot.user) await bot.change_presence(activity=discord.Game(",help | Assisting You!")) @bot.event async def on_message(message): if not message.author.bot and message.author != bot.user and not message.guild: #Make user cursor.execute('Select * from deezgunz where userid = ?', (message.author.id,)) rows1 = cursor.fetchall() if(rows1 == []): cursor.execute('insert into deezgunz(userid, thread) values(?,?)', (message.author.id,1,)) else: cursor.execute('Select * from deezgunz where userid = ?', (message.author.id,)) rows1 = cursor.fetchall() conn.commit() # Mod mail cursor.execute('Select * from deezgunz where userid = ?', (message.author.id,)) rows1 = cursor.fetchall() if rows1[0][1] == 0: cursor.execute('update deezgunz set thread = ? where userid = ?', (1)), server = bot.get_guild(763913144653316126) channel = server.get_channel(842464175472115754) await channel.send(f'({message.author.id}){message.author} has said {message}') server_add = discord.Embed(title="Support", color=discord.Color.green()) server_add.add_field(name=f'New Thread', value=f'The staff will get back to you as soon as possible, please bare with us!\n \n Thanks,\nSoftwaresat Bot Staff Team', inline=True) await message.author.send(embed=server_add) await channel.send(embed=server_add) elif rows1[0][1] == 1: user = bot.get_user(420339994754940928) # await user.send('👀') guild = bot.get_guild(763913144653316126) # member = await message.guild.fetch_member(message.author.id) await message.author.send(f'Please chat in Softwaresat Community! {rows1[0][1]}') await bot.process_commands(message) #Suggestions! @bot.command() async def suggest(message, *, suggestion: str): """Suggest a wonderful idea!""" guild = message.guild channel = guild.get_channel(805963952059318283) suggestion_embed = discord.Embed(title='Suggestion!', description=f'Suggestion Made By: **{message.author}**', color=discord.Color.green()) suggestion_embed.set_thumbnail(url=message.author.avatar_url) suggestion_embed.add_field(name='My Suggestion is:', value=suggestion, inline=True) msg = await channel.send(embed=suggestion_embed) await message.channel.send("Your suggestion has been sent successfully!") await msg.add_reaction('\U0001f44d') await msg.add_reaction('\U0001f44e') #reply! @bot.command() @commands.has_permissions(administrator=True) async def mod_reply(message, id: int, *, reply: str): """Reply to Mod Mail - Admin Only!""" member = await message.guild.fetch_member(id) try: suggestion_embed = discord.Embed(title='Staff Reply!', description=f'Reply Made By: **{message.author}**', color=discord.Color.gold()) suggestion_embed.set_thumbnail(url=message.author.avatar_url) suggestion_embed.add_field(name='Reply:', value=f'{reply}', inline=True) await member.send(embed=suggestion_embed) await message.channel.send(embed=suggestion_embed) except: await message.channel.send('This message cannot be send. A possible cause is that this server may not have my owner in it! Go to my support server for help.') #Approve! @bot.command() @commands.has_permissions(administrator=True) async def approve(message, message_id: int, *, notes: str): """Administrator Only - Approve Suggestions""" guild = message.guild channel = guild.get_channel(805963952059318283) msg = await channel.fetch_message(message_id) suggestion = discord.Embed(title='Suggestion **approved**!', description=f'Suggestion approved by: **{message.author}**', color=discord.Color.green()) suggestion.add_field(name='Notes:', value=notes, inline=True) await msg.reply(embed=suggestion) await message.channel.send(f'Suggestion **approved** by **{message.author}**!') #serverinfo Command @bot.command() async def serverinfo(message): """Get your server's info!""" server = message.guild num_categories = len(server.categories) icon = server.icon_url member_count = server.member_count created_at = server.created_at num_emoji = len(server.emojis) id = server.id owner = server.owner name = server.name description = server.description num_c = len(server.channels) num_vc = len(server.voice_channels) num_tc = len(server.text_channels) boost_level = server.premium_tier total_boosts = server.premium_subscription_count role_count = len(server.roles) embedVar = discord.Embed(title=f'Info for {name}!', description=f'Description for server: {description}', color=discord.Color.blue()) embedVar.set_thumbnail(url=icon) embedVar.add_field(name="ID", value=id, inline=True) embedVar.add_field(name="Owner", value=owner, inline=True) embedVar.add_field(name="Created at", value=created_at, inline=True) embedVar.add_field(name="Member Count", value=f'Total Members: {member_count}', inline=True) embedVar.add_field(name="Channel/Category Info", value=f'Total Categories: {num_categories}\nTotal Channels: {num_c}\nText Channels: {num_tc}\nVoice Channels: {num_vc}', inline=True) embedVar.add_field(name="Boost Info", value=f'Boost Level: {boost_level}\nTotal Boosts: {total_boosts}', inline=True) embedVar.add_field(name="Role/Emoji Info", value=f'Number of Roles: {role_count}\nNumber of Emojis: {num_emoji}', inline=True) embedVar.set_footer(text=f'Requested by {message.author}!') await message.channel.send(embed=embedVar) #Deny! @bot.command() @commands.has_permissions(administrator=True) async def deny(message, message_id: int, *, notes: str): """Administrator Only - Deny Suggestions""" guild = message.guild channel = guild.get_channel(805963952059318283) msg = await channel.fetch_message(message_id) suggestion = discord.Embed(title='Suggestion **denied**!', description=f'Suggestion denied by: **{message.author}**', color=discord.Color.red()) suggestion.add_field(name='Notes:', value=notes, inline=True) await msg.reply(embed=suggestion) await message.channel.send(f'Suggestion has been **denied** by **{message.author}**!') #oneword story @bot.command() async def story(message): """Read the story!""" f = open("story.txt", "r") await message.send(file=discord.File('story.txt')) f.close() # #oneword story add # @bot.command() # async def add(ctx, *, word: str): # """Add words to the story!!""" # f = open("story.txt", "a") # if word == "": # await ctx.channel.send('Please add a word or a set of words!') # f.write(str(f' {word}')) # await ctx.channel.send("I have successfully added the words!") # f.close() @suggest.error async def suggest_error(ctx, error): if isinstance(error, commands.MissingRequiredArguments): await ctx.send("Please make sure your syntax is correct! Ex: `$suggest This is my suggestion`") @approve.error async def approve_error(ctx, error): if isinstance(error, commands.MissingRequiredArguments): await ctx.send("Please make sure your syntax is correct! Ex: `$approve 830224912476143678 Great Suggestion!`") @deny.error async def deny_error(ctx, error): if isinstance(error, commands.MissingRequiredArguments): await ctx.send("Please make sure your syntax is correct! Ex: `$deny 830224912476143678 I don't think this is a good idea!") @deny.error async def admin1_error(ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send("You need Administrator Permissions to run this!") @approve.error async def admin2_error(ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send("You need Administrator Permissions to run this!") keep_alive() token = os.environ.get("DISCORD_BOT_SECRET") bot.run(token)
d32b9c022f16f52f4643cda37d022cfa952c1033
[ "Python" ]
1
Python
mastertar/softwaresatAssistantBot
dfb355cd1dc9a819d8f34f46f0471aea04d9c1ba
270edc3a49f2f8a106c053d28f2255af35c1c850
refs/heads/master
<file_sep> # Assignment_14_Fizz_Buzz """ Print numbers from 1 to 100 inclusively following these instructions: if a number is multiple of 3, print "Fizz" instead of this number, if a number is multiple of 5, print "Buzz" instead of this number, for numbers that are multiples of both 3 and 5, print "FizzBuzz", print the rest of the numbers unchanged. Output each value on a separate line. """ num_list = list(range(1,101)) for i in num_list: if i % 15 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i)<file_sep>import random nr = random.randint(0,20) print("In this program, you will try to find a number between 0 and 100") rep = 0 find = False while find == False: guess = int(input("Enter your guess : ")) rep += 1 if guess > nr: print("Go lower :\n") elif guess < nr: print("Go higher :\n") else: print(f"You made it in {rep} attempts.") find = True <file_sep># Assignment_10_Covid-19 """ Task : Estimating the risk of death from coronavirus. Write a program that; Takes "Yes" or "No" from the user as an answer to the following questions : Are you a cigarette addict older than 75 years old? Variable → age Do you have a severe chronic disease? Variable → chronic Is your immune system too weak? Variable → immune Set a logical algorithm using boolean logic operators (and/or) and use if-statements with the given variables in order to print out us a message : "You are in risky group"(if True ) or "You are not in risky group" (if False). """ age = (input("Are you a cigarette addict older than 75 years old? ")).title().strip() == "Yes" chronic = (input("Do you have a severe chronic disease? ")).title().strip() == "Yes" immune = (input ("Is your immune system too weak? ")).title().strip() == "Yes" #def check(x): # if x == "Yes": # return(True) # else: # return (False) #risk = check(age) and check(chronic) and check(immune) risk = age and chronic and immune if risk: print("You are in risky group") else: print("You are not in risky group")<file_sep># Assignment_7_Comfortable_Words """ Task : Find out if the given word is "comfortable words" in relation to the ten-finger keyboard use. A comfortable word is a word which you can type always alternating the hand you type with (assuming you type using a Q-keyboard and use of the ten-fingers standard). The word will always be a string consisting of only letters from a to z. Write a program to returns True if it's a comfortable word or False otherwise. """ left_letters = set("qazwsxedcrfvtgb") right_letters = set("yhnujmikolp") given_str = input("Enter a word: ") given_str_set = set(given_str) left_check = bool(given_str_set - left_letters) right_check = bool(given_str_set - right_letters) check = left_check and right_check print(check * f"\"{given_str}\" is a comfortable word") print((not check) * f"\"{given_str}\" is not a comfortable word")<file_sep># Assignment_6_Profit """ Task - 1 : You work for a manufacturer as a programmer and have been asked to calculate the total profit made on the sales of a product. You are given a dictionary (sales) containing the cost price per unit (in dollars), sell price per unit (in dollars), and the beginning inventory. Write a program to return the total profit made, rounded to the nearest dollar. Assume all of the inventory has been sold. The name and the keys of the dictionary are constant, so use them as they are. """ sales = { "cost_value": 31.87, "sell_value": 45.00, "inventory": 1000 } profit = (sales.get('sell_value') - sales.get('cost_value')) * sales.get('inventory') print("Profit is $",round(profit)) # the profit will be : 13130 #profit = ((sales['sell_value'] - sales['cost_value']) * sales['inventory']) """ Task-2: Your boss wants you to prepare the payrolls of the workers in your department. You have to convert the amount of dollars into payroll format. In order to help move things along, you have volunteered to write a code that will take a float and return the amount formatting in dollars and cents. """ payroll = float(input("Enter the payroll ")) print('Payroll is $%.2f' %(payroll)) #.2f means let only 2 decimal digits<file_sep># Assignment_12_Prime_Numbers #Print the prime numbers which are between 1 to entered limit number (nr). nr = int(input("Enter a range of numbers : ")) prime_list = [] for j in range(1, nr+1): counter = 0 for i in range (1, j+1): if j % i == 0: counter += 1 if (counter < 3) and (n != 0) and (n != 1): prime_list.append(j) print(prime_list)<file_sep>#Assignment_1_Weekly_Profit # If you had deposited a coin on the cryptocurrency exchange #that brought 7% fixed profit daily for a week, #how much would your $ 1000 reach at the end of the 7th day? deposit = 1000 profit = 0.07 print("You have $", deposit, "as initial deposit\nThe profit ratio is: ", int(profit*100), "%") deposit += profit * deposit #new deposit = deposit + profit ratio times deposit deposit += profit * deposit #2nd day deposit += profit * deposit #3rd day deposit += profit * deposit #4th day deposit += profit * deposit #5th day deposit += profit * deposit #6th day deposit += profit * deposit #7th day print("At the end of the 7th day your deposit will be : $", int(deposit) ) """ deposit = 1000 print("You have $", deposit, "as initial deposit\nThe profit ratio is: ", int(deposit * 0.07), "% \n") # deposit = deposit * 0.07 * deposit # deposit = deposit (1 + 0.07) # deposit = deposit * 1.07 ......... deposit = deposit * (1.07 **7) print("At the end of the 7th day your deposit will be : $", int(deposit) ) """<file_sep>## Python_Helper #### This repo includes frequently used Python codes and functions along with code challanges that help improving algorithm building ability. <file_sep># Assignment_8_Most_Frequent_Element """ Task : Find out the most frequent number and its frequency. Write a program that; Finds out the most frequent number in the given list. Calculates its frequency. Prints out the result such as : Example Given list: numbers = [1, 3, 7, 4, 3, 0, 3, 6, 3] Desired Output: the most frequent number is 3 and it was 4 times repeated Note : You can/should use a useful built-in function and a method of the list operation. """ num = "137430363" num_list = list(num) most_freq = max(num_list, key=num_list.count) repet = num_list.count(most_freq) print(f"The most frequent number in the list is {most_freq}, and it is repeated {repet} times.")<file_sep># Assignment_18_Most_Frequent_Element """Given a list, return the most frequent (repeating) element.""" def most_freq(given_list): rep = 0 result = given_list[0] for i in given_list: live_rep = given_list.count(i) if live_rep > rep: rep = live_rep result = i return result # Shorter way # def my_fact(n): # return 1 if n==0 else n*my_fact(n-1) <file_sep># Assignment_3_Measure_Converter """ Task-1: Write a short Python program that asks the user to enter Celsius temperature (it can be a decimal number), converts the entered temperature into Fahrenheit degree and prints the result. """ celcius = int(input("Enter the temperature value in Celcius:")) fahrenheit = celcius * 9 / 5 + 32 print("The temperature is", round(fahrenheit,2), "F") """ Task-2: Write a short Python program that asks the user to enter a distance (it can be a decimal number) in kilometers, converts the entered distance into miles and prints the result. """ print("Enter the distance in kilometers:") kilometers = input() miles = int(kilometers) * 0.62137 print("The distance is", round(miles, 2), "miles")<file_sep># Assignment_2_Covid_19_Possibility """ Task : Estimating the risk of death from coronavirus. Consider the following questions in terms of True/False regarding someone else. Are you a cigarette addict older than 75 years old? Variable → age Do you have a severe chronic disease? Variable → chronic Is your immune system too weak? Variable → immune Set a logical algorithm using boolean logic operators (and/or) and the given variables in order to give us True (there is a risk of death) or False (there is not a risk of death) as a result. """ print("Estimating the risk of death from coronavirus.") age = False print("You are over 75 :", age) chronic = False print("You have chronic diseases :", chronic) immune = False print("Your immune system is weak:", immune, "\n") risk = age or chronic or immune print(risk * "You have high risk of death") print((not risk) * "You are not in danger")<file_sep># Assignment_13_Fibonacci_Numbers # Create a list of fibonacci numbers from 1 to 55 # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] fi_nu = [] for i in range (-2,8): if i < 0 : fi_nu.append(1) else: fi_nu.append(fi_nu[i] + fi_nu[i+1]) print(fi_nu) <file_sep># Assignment_16_Letters_Count # Count the number of each letter in a sentence. sentence = "Her gun daha ileri, hep ileri" letter_count = {} for i in sentence: keys = letter_count.keys() if i in keys: letter_count[i] +=1 else: letter_count[i] =1 print(letter_count) <file_sep># Assignment_5_Leap_Year year = int(input("Enter the year :")) leap = (year % 4 == 0) and not(year % 100 == 0) or (year % 400 == 0) #output = f"It is {leap} that {year} is a leap year" print(leap * f"{year} is a leap year") print((not leap) * f"{year} is a not leap year")<file_sep># Assignment_11_Armstrong_Number """ Task: Find out if a given number is an "Armstrong Number". An n-digit number that is the sum of the nth powers of its digits is called an n-Armstrong number. Examples : 371 = 3^3 + 7^3 + 1^3; 9474 = 9^4 + 4^4 + 7^4 + 4^4; 93084 = 9^5 + 3^5 + 0^5 + 8^5 + 4^5 Write a Python program that; -takes a positive integer number from the user, -checks the entered number if it is Armstrong, -consider the negative, float and any entries other than numeric values then display a warning message to the user. """ nr = input("Enter a number :\n ") numbers_set = set("0123456789") nr_valid = False while not nr_valid: if nr.isdigit(): nr_valid = True elif nr[0] == "-": nr = input("Please enter a positive number :\n ") elif ("," in nr) or ("." in nr): nr = input("Please enter an integer :\n ") elif (numbers_set & set(nr)) == set(): nr = input("Do not use any entries other than numeric values :\n ") else: nr = input("Enter something valid :\n ") i = 0 sum = 0 for i in (range(len(nr))): sum += (int(nr[i]) ** (len(nr))) if sum == int(nr): print(f"{nr} is an Armstrong Number") else: print(f"{nr} is not an Armstrong Number") <file_sep># Assignment_15_Leap_Year_w_IF year = int(input("Enter the year :")) if year % 4 != 0 and year % 100 == 0: leap_indicator = "not leap" elif year % 400 != 0: leap_indicator = "not leap" else: leap_indicator = "leap" print (f"{year} is {leap_indicator}") <file_sep># Assignment_9_If_Statements """ Task : Let's say you left a message in the past that prints a password you need. To see the password you wrote, you need to enter your name and the program should recognize you. Write a program that Takes the first name from the user and compares it to yours, Then if the name the user entered is the same as yours, print out such as : "Hello, Joseph! The password is : <PASSWORD>", If the name the user entered is not the same as yours, print out such as : "Hello, Amina! See you later." """ initial_name = "Joseph" given_name = input("Enter your name : ") given_name = given_name.title().strip() if initial_name == given_name: print(f"Hello, {initial_name}! The password is : <PASSWORD>") else: print(f"Hello, {given_name}! See you later.")
5f1be11b69b3fb42d2bc737610529288f9a3596c
[ "Markdown", "Python" ]
18
Python
SemihDurmus/Python_Helper
0f85a963a18bfdfeec5a03c2392824abd51077dc
ee434d5cdb0abe4198a799ad42aa7600fbd5c5b1
refs/heads/master
<repo_name>mgicode/mgicode-jenkins-pipeline<file_sep>/jenkins/ms-echo/1.0-snapshot/dev/springboot-maven-docker/config/init_before_config.properties dockerServerIP="10.1.12.50" dockerServerPort="8030" dockerServerUser="root" dockerServerPwd="1" DOCKER_HOST_SSH_CREDENTIALSID="<KEY>" CODE_CREDENTIALSID='<KEY>' CODE_GIT_URL='http://10.1.12.35/pengrk/ms-test.git'<file_sep>/jenkins01/common/springboot-maven-docker/dev/scripts/12configmerge.sh #!/usr/bin/env bash echo -e "\n\n\n##################################################################" echo -e "##################### 合并配置脚本 start ################################" cp -rf ../jenkins-job/jenkins jenkins ; function getdir(){ for element in `ls $1` do dir_or_file=$1"/"$element if [ -d $dir_or_file ] then getdir $dir_or_file else echo $dir_or_file fi done } getdir jenkins/ echo -e "##################### 合并配置脚本 end ################################" echo -e "###########################################################\n\n\n" <file_sep>/jenkins02/common/springboot-maven-docker/dev/config/pre/init_before_config.properties dockerImageAddr="10.1.12.41:5000" SONAR_IP_PORT='http://10.1.12.40:9000' SONAR_CREDENTIALSID="<KEY>" <file_sep>/jenkins01/scripts/dockerbuild.sh #!/usr/bin/env bash echo -e "\n\n\n##################################\n" echo -e "#### dockerBuild #######\n\n\n" source $(pwd)/target/init_var.sh export templateDir=${rootDir}/jenkins/template/docker targetStartUp=${targetPath}/startup.sh targetDockerfile=${targetPath}/Dockerfile echo "templateDir:$templateDir, targetStartUp:$targetStartUp,targetDockerfile:$targetDockerfile" echo -e "\n\n#### 生成${targetStartUp}\n\n\n" if [ -d "${targetStartUp}" ] ; then rm -rf ${targetStartUp} fi cp ${templateDir}/startup.sh ${targetStartUp} sed -i "s/{{JAR_NAME}}/$jarNameVersionOrig/g;" ${targetStartUp} cat ${targetStartUp} echo -e "\n\n#### 生成${targetDockerfile}\n\n\n" if [ -d "${targetDockerfile}" ] ; then rm -rf ${targetDockerfile} fi cp ${templateDir}/Dockerfile ${targetDockerfile} sed -i "s/{{JAR_NAME}}/$jarNameVersionOrig/g;" ${targetDockerfile} cat ${targetDockerfile} #构建docker images 并上传到docker register echo "dockerPath:${dockerPath},targetPath:${targetPath}" docker rmi ${dockerPath} cd ${targetPath}/ echo "\n\n####构建${dockerPath}\n\n\n." docker build -t ${dockerPath} -f ${targetDockerfile} ${targetPath}/ echo "\n\n####上传到docker habor\n\n\n" docker push ${dockerPath} echo -e "\n\n\n##################################\n" echo -e "#### dockerBuild #######\n\n\n" <file_sep>/jenkins01/scripts/dockerdeploy.sh #!/usr/bin/env bash echo -e "\n\n\n##################################\n" echo -e "#### dockerDeploy #######\n\n\n" source $(pwd)/target/init_var.sh export echo "MSNAME:${jarNameVersion}, HTTPPORT:${dockerPort}..." execScript=" docker stop ${jarNameVersion} ; docker rm ${jarNameVersion} ; #一定要清除原有镜像,不然不会拉 docker rmi -f ${dockerPath} ; docker run -d --name ${jarNameVersion} --restart=always \ -p ${dockerPort}:${dockerPort} ${dockerPath} sleep 15 docker logs ${jarNameVersion} " echo "${execScript}" sleep 5 ssh $k8sUser@$k8sAddr "${execScript}" echo -e "\n\n\n##################################\n" echo -e "#### dockerDeploy #######\n\n\n" # --env MS_ALL_CONF=\" # --spring.application.name=${MSNAME} \ # --server.port=${HTTPPORT} \ # --tcp.port=${TCPPORT} \ # --endpoints.health.sensitive=false \ # --management.security.enabled=false \ # --management.health.consul.enabled=false \ # --spring.cloud.consul.discovery.enabled=true \ # --spring.cloud.consul.discovery.hostname=${ip} \ # --spring.cloud.consul.discovery.port=${HTTPPORT} \ # --spring.cloud.consul.discovery.serviceName=${MSNAME} \ # --spring.cloud.consul.host=${consulIP} \ # --spring.cloud.consul.port=${consulPort} \ # # --spring.cloud.consul.discovery.healthCheckUrl=http://${ip}:${HTTPPORT}/health \ # \"<file_sep>/jenkins01/template/docker/Dockerfile #FROM registry.cn-hangzhou.aliyuncs.com/prk/centos7_jdk1.8 FROM 10.1.12.61:5000/centos7_jdk1.8 WORKDIR / ENV LANG en_US.UTF-8 ENV LANGUAGE en_US:en #ENV LC_ALL en_US.UTF-8 #解决时区的问题 ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone ADD startup.sh /startup.sh #jenkins的构建时其相对路径有问题,采用绝对路径 #{{JAR_ROOT_PATH}}/ ADD {{JAR_NAME}}.jar /{{JAR_NAME}}.jar RUN chmod +x /startup.sh RUN chmod +x /{{JAR_NAME}}.jar ENTRYPOINT /startup.sh <file_sep>/jenkins01/common/springboot-maven-docker/dev/scripts/03staticCheck.sh #!/usr/bin/env bash echo -e "\n\n\n##################################################################" echo -e "##################### 静态代码检测 start ################################" source $(pwd)/init_var.sh init_after_staticcheck_config="${projectConfigDir}/init_after_staticcheck.properties" if [ -f "$init_after_staticcheck_config" ]; then while read line do line=${line// /} echo "$line" k=${line%=*} v=${line#*=} if [ -z "$k" ] then echo "empty row" elif [ $(echo $k | grep "^#") != "" ] then echo ${line} else echo " export $k=${v} " >> ${rootDir}/init_var.sh echo " export $k=${v}" fi done < $init_after_staticcheck_config fi source ${rootDir}/init_var.sh #export echo -e "\n进行静态检测...\n." echo "SONAR_IP_PORT:$SONAR_IP_PORT, SONAR_CREDENTIALSID:$SONAR_CREDENTIALSID " ; mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent \ install -Dmaven.test.failure.ignore=true sonar:sonar \ -Dsonar.host.url=${SONAR_IP_PORT} -Dsonar.login=${SONAR_CREDENTIALSID} echo -e "##################### 静态代码检测 end ################################" echo -e "###########################################################\n\n\n" <file_sep>/jenkins01/common/springboot-maven-docker/dev/scripts/04buildjar.sh #!/usr/bin/env bash echo -e "\n\n\n##################################################################" echo -e "##################### 构建JAR包 start ################################" source $(pwd)/init_var.sh init_after_buildjar_config="${projectConfigDir}/init_after_buildjar.properties" if [ -f "$init_after_buildjar_config" ]; then while read line do line=${line// /} echo "$line" k=${line%=*} v=${line#*=} if [ -z "$k" ] then echo "empty row" elif [ $(echo $k | grep "^#") != "" ] then echo ${line} else echo " export $k=${v} " >> ${rootDir}/init_var.sh echo " export $k=${v}" fi done < $init_after_buildjar_config fi source ${rootDir}/init_var.sh #export echo -e "\n进行打包构建...\n." mvn -B -DskipTests clean package echo -e "##################### 构建JAR包 end ################################" echo -e "###########################################################\n\n\n" <file_sep>/jenkins/bak/template/k8s/bak1/k8s.sh #!/usr/bin/env bash #Uploading: http://10.1.12.28:8081/repository/distributionRepo/com/sirius/sys-gateway-springboot/0.0.1/sys-gateway-springboot-0.0.1.jar #修改这几个参数 COMMON_NAME="sys-gateway-test" JAR_ADDR=http://10.1.12.77:8081/repository/distributionRepo/com/sirius/sys-gateway-springboot/0.0.1/ JAR_NAME=sys-gateway-springboot-0.0.1.jar IMAGES_ADDR=10.1.12.61:5000/centos7_jdk1.8 HTTP_PORT=8080 THRIFT_PORT=8081 REPEAT_COUNT=1 JAR_ADDR1=`echo $JAR_ADDR |sed "s/\//\\\\\\\\\//g"` IMAGES_ADDR1=`echo $IMAGES_ADDR |sed "s/\//\\\\\\\\\//g"` kubectl get all |grep "${COMMON_NAME}" echo "k8s中目前存在相关的服务: $COMMON_NAME,请稍等..." sleep 5 echo "\n\n\n正在生成检查生成 $COMMON_NAME.yaml...\n\n\n" cp k8s-template.yaml $COMMON_NAME.yaml sed -i "s/{{COMMON_NAME}}/$COMMON_NAME/g;s/{{JAR_ADDR}}/$JAR_ADDR1/g;s/{{JAR_NAME}}/$JAR_NAME/g;s/{{REPEAT_COUNT}}/$REPEAT_COUNT/g;s/{{IMAGES_ADDR}}/$IMAGES_ADDR1/g;s/{{HTTP_PORT}}/$HTTP_PORT/g;s/{{THRIFT_PORT}}/$THRIFT_PORT/g" $COMMON_NAME.yaml #显示生成文件 cat $COMMON_NAME.yaml echo "\n\n\n请检查生成 $COMMON_NAME.yaml\n\n\n" sleep 5 kubectl delete -f $COMMON_NAME.yaml kubectl create -f $COMMON_NAME.yaml kubectl get all |grep "${COMMON_NAME}" #网上查了一下,原来是mac的sed对\n的处理和linux不一样 #解决办法:1.brew install gnu-sed --with-default-names<file_sep>/jenkins/bak/scripts/dockerDeployTest.sh #!/usr/bin/env bash echo -e "\n\n\n##################################\n" echo -e "#### autoTest start #######\n" source $(pwd)/target/init_var.sh export templateDir=${rootDir}/jenkins/autoTest targetCollection=${targetPath}/ms-echo.postman_collection.json targetEnvironment=${targetPath}/ms-echo.postman_environment.json #ms-echo.postman_environment_template.json echo "templateDir:$templateDir, targetCollection:$targetCollection,targetEnvironment:$targetEnvironment" echo -e "\n\n#### 生成${targetCollection}\n" if [ -d "${targetCollection}" ] ; then rm -rf ${targetCollection} fi cp ${templateDir}/ms-echo.postman_collection.json ${targetCollection} echo -e "\n\n#### 生成${targetEnvironment}\n" if [ -d "${targetEnvironment}" ] ; then rm -rf ${targetEnvironment} fi cp ${templateDir}/ms-echo.postman_environment_template.json ${targetEnvironment} sed -i "s/{{HTTP_URL}}/$k8sAddr/g;s/{{HTTP_PORT}}/$dockerPort/g;" ${targetEnvironment} cat ${targetEnvironment} sleep 20 curl http://$k8sAddr:$dockerPort/hello echo -e "\n\n#### 执行批量测试\n" newman run ${targetCollection} --environment ${targetEnvironment} echo -e "\n\n\n##################################\n" echo -e "#### autoTest finish #######\n" <file_sep>/jenkins/bak/scripts/k8sconfig.sh #!/usr/bin/env bash echo -e "\n\n\n##################################\n" echo -e "#### k8sConfig start#######\n\n\n" export source $(pwd)/target/init_var.sh configTemplateDir=${rootDir}/jenkins/template/k8s/configmap configDir=${rootDir}/configmap configYaml=${configDir}/config.yaml k8sDir=/helmdata/$jarNameVersion/configmap if [ -d "${configYaml}" ] ; then rm -rf ${configYaml} fi #rm -rf ${targetPath}/configmap/config.yaml mkdir -p ${configDir}/ cp ${configTemplateDir}/config.yaml ${configYaml} #名称中去掉小数点,如my-app-1.0-snapshot COMMON_NAME=${jarNameVersion/./} sed -i "s/{{COMMON_NAME}}/${COMMON_NAME}/g;s/{{MS_ALL_CONF}}/$MS_ALL_CONF/g;" ${configYaml} echo "gen ${configYaml}..." cat ${configYaml} sleep 5 echo "ssh upload ..." ssh $k8sUser@$k8sAddr "rm -rf ${k8sDir}/* ; mkdir -p ${k8sDir}/ " scp ${configYaml} $k8sUser@$k8sAddr:${k8sDir}/config.yaml ssh $k8sUser@$k8sAddr " cd ${k8sDir}; kubectl delete -f config.yaml; kubectl create -f config.yaml " echo -e "\n\n\n##################################\n" echo -e "#### k8sConfig end #######\n\n\n" <file_sep>/jenkins/bak/scripts/k8sAuth.sh #!/usr/bin/env bash echo -e "\n\n\n##################################\n" echo -e "#### k8sAuth #######\n\n\n" source $(pwd)/target/init_var.sh echo "auth......" export #判断是否能登陆,如果能的话,那么就不需要使用expect,按道理讲用不上啊? ssh -o NumberOfPasswordPrompts=0 $k8sUser@$k8sAddr "date" if [ $? -eq 0 ];then echo "$i" >> 2.txt else if [ -d "~/.ssh/id_rsa.pub" ] ; then rm -rf ~/.ssh/* fi ssh-keygen -q -t rsa -N "" -f ~/.ssh/id_rsa echo -e "\nssh-keygen生成的文件###########\n" ls -la ~/.ssh/ #expect中不能直接使用~ rsaPath=~ sleep 1 # 2、进行ssh免证登录,ssh-copy-id到需要免登录的机器上 expect -c " set timeout 5 spawn ssh-copy-id -i $rsaPath/.ssh/id_rsa.pub $k8sUser@$k8sAddr expect { "*yes/no" { send "yes\\r"; exp_continue} "*INFO:" { exp_continue } "*ERROR:" { exp_continue } "*again" { send "$k8sPwd\\r"; } "*assword:" { send "$<PASSWORD>\\r" } } expect eof exit #expect进程要退出,不然在循环中再次运行报错 " #该时间需要足够长,不然spawn执行的命令的伪线程还没有关闭,那么第二次就会connect refused! echo "sleep: 10" sleep 10 fi echo -e "\n\n\n##################################\n" echo -e "#### k8sAuth #######\n\n\n" <file_sep>/jenkins01/mps-stationzone/0.1-snapshot/dev/springboot-maven-docker/config/init_before_config.properties dockerServerIP="10.1.12.50" dockerServerPort="8080" dockerServerUser="root" dockerServerPwd="1" DOCKER_HOST_SSH_CREDENTIALSID="<KEY>" CODE_CREDENTIALSID='<KEY>' CODE_GIT_URL='http://10.1.12.35/pengrk/ms-test.git'<file_sep>/jenkins02/common/springboot-maven-k8s/dev/scripts/05dockerbuild.sh #!/usr/bin/env bash echo -e "\n\n\n##################################################################" echo -e "##################### dockerBuild start ################################" source $(pwd)/init_var.sh export init_after_dockerbuild_config="${projectConfigDir}/init_after_dockerbuild.properties" #if [ -d "$init_after_dockerbuild_config" ]; then IFS='=' while read k v do if [[ "$k" =~ ^# ]] then echo " export $k=${v}" else echo " export $k=${v} " >> ${rootDir}/init_var.sh echo " export $k=${v}" fi done < $init_after_dockerbuild_config #fi source ${rootDir}/init_var.sh #export templateDir=${commonConfigBaseDir}/template/docker targetStartUp=${targetPath}/startup.sh targetDockerfile=${targetPath}/Dockerfile echo "templateDir:$templateDir, targetStartUp:$targetStartUp,targetDockerfile:$targetDockerfile" echo -e "\n\n#### 生成${targetStartUp}\n\n\n" if [ -d "${targetStartUp}" ] ; then rm -rf ${targetStartUp} fi cp ${templateDir}/startup.sh ${targetStartUp} sed -i "s/{{JAR_NAME}}/$jarNameVersionOrig/g;" ${targetStartUp} cat ${targetStartUp} echo -e "\n\n#### 生成${targetDockerfile}\n\n\n" if [ -d "${targetDockerfile}" ] ; then rm -rf ${targetDockerfile} fi cp ${templateDir}/Dockerfile ${targetDockerfile} sed -i "s/{{JAR_NAME}}/$jarNameVersionOrig/g;" ${targetDockerfile} cat ${targetDockerfile} #构建docker images 并上传到docker register echo "dockerPath:${dockerPath},targetPath:${targetPath}" docker rmi ${dockerPath} cd ${targetPath}/ echo "\n\n####构建${dockerPath}\n\n\n." docker build -t ${dockerPath} -f ${targetDockerfile} ${targetPath}/ echo "\n\n####上传到docker habor\n\n\n" docker push ${dockerPath} echo -e "##################### dockerBuild end ################################" echo -e "###########################################################\n\n\n" <file_sep>/jenkins/common/springboot-maven-docker/dev/scripts/01init-1.sh #!/usr/bin/env bash #set -xv #不加上/usr/bin/env bash 找不到source echo -e "\n\n\n##################################################################" echo -e "##################### init start ################################" ENV_DEPLOY="dev" ENV_BUILD="springboot-maven-docker" jarName=`mvn help:evaluate -Dexpression=project.name | grep "^[^\[]"` jarVersion=`mvn help:evaluate -Dexpression=project.version | grep "^[^\[]"` jarNameVersionOrig=${jarName}-${jarVersion} jarNameVersion=$(echo $jarNameVersionOrig | tr '[A-Z]' '[a-z]') jarNameLower=$(echo $jarName | tr '[A-Z]' '[a-z]') jarVersionLower=$(echo $jarVersion | tr '[A-Z]' '[a-z]') dockerName=${jarNameVersion} dockerVersion=${jarVersion} rootDir=$(pwd) targetPath=${rootDir}/target projectConfigBaseDir=$rootDir/jenkins/$jarNameLower/$jarVersionLower/${ENV_DEPLOY}/${ENV_BUILD} projectConfigDir=${projectConfigBaseDir}/config projectAutoTestDir=${projectConfigBaseDir}/autoTestData commonConfigBaseDir=$rootDir/jenkins/common/${ENV_BUILD}/${ENV_DEPLOY} #mkdir -p ${targetPath} cat > ${rootDir}/jenkins/init_var.sh <<EOF EOF #读取通用文件 init_before_config="${commonConfigBaseDir}/config/init_before_config.properties" echo "init_before_config :$init_before_config" if [ -f "$init_before_config" ]; then echo "${init_before_config}的内容:" cat $init_before_config echo -e "\n*********************" while read line do line=${line// /} echo "$line" k=${line%=*} v=${line#*=} if [ -z "$k" ] then echo "empty row" elif [ $(echo $k | grep "^#") != "" ] then echo "emit:${k}" else echo " export $k=${v} " >> ${rootDir}/jenkins/init_var.sh echo " export $k=${v}" fi done < $init_before_config fi echo -e "\n ***********************************\n" #在init之前进行不同项目的初始化,可以进行项目变量定义 init_before_config="${projectConfigDir}/init_before_config.properties" echo "init_before_config :$init_before_config" if [ -f "$init_before_config" ]; then echo "${init_before_config}的内容:" cat $init_before_config echo -e "\n*********************" while read line do line=${line// /} echo "$line" k=${line%=*} v=${line#*=} if [ -z "$k" ] then echo "" elif [ $(echo $k | grep "^#") != "" ] then echo ${line} else echo " export $k='${v}' " >> ${rootDir}/jenkins/init_var.sh echo " export $k=${v}" fi done < $init_before_config fi source ${rootDir}/jenkins/init_var.sh echo -e "\n ***********************************\n" dockerPath="${dockerImageAddr}/${dockerName}:${dockerVersion}" echo ' export jarName="${jarName}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export jarVersion="${jarVersion}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export jarNameLower="${jarNameLower}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export jarVersionLower="${jarVersionLower}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export jarNameVersion="${jarNameVersion} ' >> ${rootDir}/jenkins/init_var.sh echo 'export jarNameVersionOrig="${jarNameVersionOrig}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export projectConfigDir="${projectConfigDir}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export projectConfigBaseDir="${projectConfigBaseDir}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export projectAutoTestDir="${projectAutoTestDir}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export commonConfigBaseDir="${commonConfigBaseDir}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export rootDir="${rootDir}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export targetPath="${targetPath}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export dockerName="${dockerName}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export dockerVersion="${dockerVersion}" ' >> ${rootDir}/jenkins/init_var.sh echo ' export dockerPath="${dockerPath}" ' >> ${rootDir}/jenkins/init_var.sh #3.3 创建安装的shell cat >> ${rootDir}/jenkins/init_var.sh <<EOF export jarName="${jarName}" export jarVersion="${jarVersion}" export jarNameLower="${jarNameLower}" export jarVersionLower="${jarVersionLower}" export jarNameVersion="${jarNameVersion} export jarNameVersionOrig="${jarNameVersionOrig}" export projectConfigDir="${projectConfigDir}" export projectConfigBaseDir="${projectConfigBaseDir}" export projectAutoTestDir="${projectAutoTestDir}" export commonConfigBaseDir="${commonConfigBaseDir}" export rootDir="${rootDir}" export targetPath="${targetPath}" export dockerName="${dockerName}" export dockerVersion="${dockerVersion}" export dockerPath="${dockerPath}" EOF chmod 777 ${rootDir}/jenkins/init_var.sh source ${rootDir}/jenkins/init_var.sh echo -e "\n ***********************************\n" #在init之前进行不同项目的初始化,可以进行项目变量定义 init_after_config="${projectConfigDir}/init_after_config.properties" if [ -f "$init_after_config" ]; then IFS='=' while read k v do line=${line// /} echo "$line" k=${line%=*} v=${line#*=} if [ -z "$k" ] then echo "" elif [ $(echo $k | grep "^#") != "" ] then echo ${line} else echo " export $k='${v}' " >> ${rootDir}/jenkins/init_var.sh echo " export $k=${v}" fi done < $init_after_config fi source ${rootDir}/jenkins/init_var.sh export echo -e "###################### init end ######################################" echo -e "######################################################################\n\n\n" #>>/etc/profile #export NODE_ADMIN_IP="10.1.12.70" #编辑/etc/profile修改全局环境变量 #编辑.bash_profile修改当前用户的环境变量 #修改完成之后source一下即可生效,例如source ~/.bash_profile #echo ${str// /} #echo $str | sed 's/ //g' #echo $str | tr -d " "<file_sep>/jenkins02/common/springboot-maven-k8s/dev/scripts/07autoTest.sh #!/usr/bin/env bash echo -e "\n\n\n##################################################################" echo -e "##################### autoTest start ################################" source $(pwd)/init_var.sh export init_after_autoTest_config="${projectConfigDir}/init_after_autoTest.properties" #if [ -d "$init_after_autoTest_config" ]; then IFS='=' while read k v do if [[ "$k" =~ ^# ]] then echo " export $k=${v}" else echo " export $k=${v} " >> ${rootDir}/init_var.sh echo " export $k=${v}" fi done < $init_after_autoTest_config #fi source ${rootDir}/init_var.sh #export targetEnvironment=${targetPath}/postman_environment_template.json #ms-echo.postman_environment_template.json echo "targetCollection:$targetCollection,targetEnvironment:$targetEnvironment" echo -e "\n\n#### 生成${targetEnvironment}\n" if [ -d "${targetEnvironment}" ] ; then rm -rf ${targetEnvironment} fi cp ${projectAutoTestDir}/postman_environment_template.json ${targetEnvironment} sed -i "s/{{HTTP_URL}}/$dockerServerIP/g;s/{{HTTP_PORT}}/$dockerServerPort/g;" ${targetEnvironment} cat ${targetEnvironment} sleep 20 curl http://$dockerServerIP:$dockerServerPort/ echo -e "\n\n#### 执行批量测试\n" newman run ${projectAutoTestDir}/*_collection.json --environment ${targetEnvironment} echo -e "##################### autoTest end ################################" echo -e "\n\n\n################################################################\n" <file_sep>/jenkins/bak/scripts/init.sh #!/usr/bin/env bash #不加上/usr/bin/env bash 找不到source #>>/etc/profile #export NODE_ADMIN_IP="10.1.12.70" #编辑/etc/profile修改全局环境变量 #编辑.bash_profile修改当前用户的环境变量 #修改完成之后source一下即可生效,例如source ~/.bash_profile echo -e "\n\n\n##################################\n" echo -e "#### init start #######\n\n\n" MS_ALL_CONF=`echo "${1}" |sed "s/\//\\\\\\\\\//g"` dockerPort="${2:-8080}" k8sAddr="${3:-10.1.12.50}" k8sUser="${4:-root}" k8sPwd="${5:-<PASSWORD>}" dockerAddr="${6:-10.1.12.41:5000}" #var=$(cat name.txt) #怎样用shell读取properties里面特定键对应的值 #v=`grep key2 my.properties|cut -d'=' -f2` #sed -n '/key2/{s/.*=//;p}' urfile #awk -F'=' '{if($1~/key2/) print $2}' yourfile #sed '/key2/!d;s/.*=//' urfile #IFS='=' #while read k v #do # echo $k # echo $v #done < mypro.propertes jarName=`mvn help:evaluate -Dexpression=project.name | grep "^[^\[]"` jarVersion=`mvn help:evaluate -Dexpression=project.version | grep "^[^\[]"` jarNameVersionOrig=${jarName}-${jarVersion} jarNameVersion=$(echo $jarNameVersionOrig | tr '[A-Z]' '[a-z]') #[a-z0-9]([-a-z0-9]*[a-z0-9])? k8sServiceName=$(echo $jarName | tr '[A-Z]' '[a-z]') rootDir=$(pwd) toPath=${rootDir}/target targetPath=${toPath} dockerName=${jarNameVersion} dockerVersion=${jarVersion} dockerPath="${dockerAddr}/${dockerName}:${dockerVersion}" echo -e "jarNameVersion:$jarNameVersion \n" echo -e "根目录 : ${rootDir} \n" echo -e "k8sAddr:$k8sAddr,k8sUser:$k8sUser,toPath:$toPath \n " #3.3 创建安装的shell cat > ${targetPath}/init_var.sh <<EOF export jarName=${jarName} export jarVersion=${jarVersion} export jarNameVersion=${jarNameVersion} export jarNameVersionOrig=${jarNameVersionOrig} export k8sServiceName=${k8sServiceName} export rootDir=${rootDir} export toPath=${toPath} export targetPath=${targetPath} export k8sAddr=${k8sAddr} export k8sUser=${k8sUser} export k8sPwd=${<PASSWORD>} export MS_ALL_CONF=${MS_ALL_CONF} export dockerAddr=${dockerAddr} export dockerName=${dockerName} export dockerVersion=${dockerVersion} export dockerPath=${dockerPath} export dockerPort=${dockerPort} EOF chmod 777 ${targetPath}/init_var.sh #这两个地址在自动化测试时可能需要使用 #echo " export HTTP_URL=${HTTP_URL} " >> ${targetPath}/init_var.sh echo -e "\n\n\n##################################\n" echo -e "#### init end#######\n\n\n" #echo " export jarName=${jarName} " >> ${targetPath}/init_var.sh #source $(pwd)/target/init_var #echo " export jarName=${jarName} " >> /etc/profile #echo " export jarVersion=${jarVersion} " >> /etc/profile #echo " export jarNameVersion=${jarNameVersion} " >> /etc/profile #echo " export rootDir=${rootDir} " >> /etc/profile #echo " export toPath=${toPath} " >> /etc/profile #echo " export targetPath=${targetPath} " >> /etc/profile # #echo " export k8sAddr=${k8sAddr} " >> /etc/profile #echo " export k8sUser=${k8sUser} " >> /etc/profile #echo " export k8sPwd=${k8sPwd} " >> /etc/profile #echo " export MS_ALL_CONF=${MS_ALL_CONF} " >> /etc/profile # #echo " export dockerAddr=${dockerAddr} " >> /etc/profile #echo " export dockerName=${dockerName} " >> /etc/profile #echo " export dockerVersion=${dockerVersion} " >> /etc/profile #echo " export dockerPath=${dockerPath} " >> /etc/profile # # #source /etc/profile #这样后面的stages取不到 #echo " export jarName=${jarName} " >> ~/.bash_profile #echo " export jarVersion=${jarVersion} " >> ~/.bash_profile #echo " export jarNameVersion=${jarNameVersion} " >> ~/.bash_profile #echo " export rootDir=${rootDir} " >> ~/.bash_profile #echo " export toPath=${toPath} " >> ~/.bash_profile #echo " export targetPath=${targetPath} " >> ~/.bash_profile # #echo " export k8sAddr=${k8sAddr} " >> ~/.bash_profile #echo " export k8sUser=${k8sUser} " >> ~/.bash_profile #echo " export k8sPwd=${k8sPwd} " >> ~/.bash_profile #echo " export MS_ALL_CONF=${MS_ALL_CONF} " >> ~/.bash_profile # #echo " export dockerAddr=${dockerAddr} " >> ~/.bash_profile #echo " export dockerName=${dockerName} " >> ~/.bash_profile #echo " export dockerVersion=${dockerVersion} " >> ~/.bash_profile #echo " export dockerPath=${dockerPath} " >> ~/.bash_profile # # #source ~/.bash_profile <file_sep>/jenkins01/template/docker/startup1.sh export POD_IP=`/sbin/ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print \$2}' | tr -d "addr" ` echo -e " ############ POD_IP ###################### \n\n $POD_IP \n\n\n" echo -e " ############# ALL_CONF #################### \n\n ${ALL_CONF} \n\n\n" java -jar -Xms256m -Xmx512m /{{JAR_NAME}}.jar ${ALL_CONF} <file_sep>/jenkins/common/springboot-maven-docker/dev/scripts/06dockerdeploy.sh #!/usr/bin/env bash echo -e "\n\n\n##################################################################" echo -e "##################### dockerDeploy start ################################" source $(pwd)/jenkins/init_var.sh #export init_after_dockerdeploy_config="${projectConfigDir}/init_after_dockerdeploy.properties" if [ -d "$init_after_dockerdeploy_config" ]; then while read line do line=${line// /} echo "$line" k=${line%=*} v=${line#*=} if [ -z "$k" ] then echo "empty row" elif [ $(echo $k | grep "^#") != "" ] then echo ${line} else echo " export $k=${v} " >> ${rootDir}/jenkins/init_var.sh echo " export $k=${v}" fi done < $init_after_dockerdeploy_config fi source ${rootDir}/jenkins/init_var.sh #export #ALL_CONF=`echo "${MS_ALL_CONF}" |sed "s/\//\\\\\\\\\//g"` #MYSQL_URL=`echo "${MYSQL_URL}" |sed "s/\//\\\\\\\\\//g"` echo "MSNAME:${jarNameVersion}, HTTPPORT:${dockerServerPort}..." execScript=" docker stop ${jarNameVersion} ; docker rm ${jarNameVersion} ; #一定要清除原有镜像,不然不会拉 docker rmi -f ${dockerPath} ; docker run -d --name ${jarNameVersion} --restart=always -p ${dockerServerPort}:${dockerServerPort} \ -e MS_ALL_CONF=\" -Dserver.port=${dockerServerPort} \ -Dendpoints.health.sensitive=false \ -Dmanagement.security.enabled=false \ -Dspring.datasource.url=${MYSQL_URL} \ -Dspring.datasource.username=${MYSQL_USERNAME} \ -Dspring.datasource.password=${<PASSWORD>} \ -Dmanagement.health.consul.enabled=false \ -Dspring.cloud.consul.discovery.enabled=true \ -Dspring.cloud.consul.discovery.hostname=${dockerServerIP} \ -Dspring.cloud.consul.discovery.port=${dockerServerPort} \ -Dspring.cloud.consul.host=${CONSUL_IP} \ -Dspring.cloud.consul.port=${CONSUL_PORT} \ -Dspring.cloud.consul.discovery.healthCheckUrl=http://${dockerServerIP}:${dockerServerPort}/health \ \" ${dockerPath} sleep 15 docker logs ${jarNameVersion} " #-Dspring.cloud.consul.discovery.serviceName=${jarNameLower} \ #-Dspring.application.name=${jarNameLower} \ #-Dserver.port=8020 #--endpoints.health.sensitive=false \ # --management.security.enabled=false \ # --spring.datasource.url=${MYSQL_URL} \ # --spring.datasource.username=${MYSQL_USERNAME} \ # --spring.datasource.password=${<PASSWORD>} \ # --management.health.consul.enabled=false \ # --spring.cloud.consul.discovery.enabled=true \ # --spring.cloud.consul.discovery.hostname=${dockerServerIP} \ # --spring.cloud.consul.discovery.port=${dockerServerPort} \ # --spring.cloud.consul.discovery.serviceName=${jarNameLower} \ # --spring.cloud.consul.host=${CONSUL_IP} \ # --spring.cloud.consul.port=${CONSUL_PORT} \ # --spring.cloud.consul.discovery.healthCheckUrl=http://${dockerServerIP}:${dockerServerPort}/health \ #--spring.datasource.password=${<PASSWORD>} \ #MYSQL_URL="jdbc:mysql://10.1.12.56:3306/RoadNet" #MYSQL_USERNAME="design" #MYSQL_PASSWRD="<PASSWORD>!@#" # --env MS_ALL_CONF= "${ALL_CONF}" \ echo "${execScript}" sleep 5 ssh $dockerServerUser@$dockerServerIP "${execScript}" temp=$? if [[ $temp -ne 0 ]]; then exit $temp fi echo -e "##################### dockerDeploy end ################################" echo -e "\n\n\n################################################################\n" # --env MS_ALL_CONF=\" # --spring.application.name=${MSNAME} \ # --server.port=${HTTPPORT} \ # --tcp.port=${TCPPORT} \ # --endpoints.health.sensitive=false \ # --management.security.enabled=false \ # --management.health.consul.enabled=false \ # --spring.cloud.consul.discovery.enabled=true \ # --spring.cloud.consul.discovery.hostname=${ip} \ # --spring.cloud.consul.discovery.port=${HTTPPORT} \ # --spring.cloud.consul.discovery.serviceName=${MSNAME} \ # --spring.cloud.consul.host=${consulIP} \ # --spring.cloud.consul.port=${consulPort} \ # # --spring.cloud.consul.discovery.healthCheckUrl=http://${ip}:${HTTPPORT}/health \ # \"<file_sep>/jenkins02/common/springboot-maven-docker/dev/scripts/07autoTest.sh #!/usr/bin/env bash echo -e "\n\n\n##################################################################" echo -e "##################### autoTest start ################################" source $(pwd)/jenkins/init_var.sh #export init_after_autoTest_config="${projectConfigDir}/init_after_autoTest.properties" if [ -f "$init_after_autoTest_config" ]; then while read line do line=${line// /} echo "$line" k=${line%=*} v=${line#*=} if [ -z "$k" ] then echo "empty row" elif [ $(echo $k | grep "^#") != "" ] then echo ${line} else echo " export $k=${v} " >> ${rootDir}/jenkins/init_var.sh echo " export $k=${v}" fi done < $init_after_autoTest_config fi source ${rootDir}/jenkins/init_var.sh #export targetEnvironment=${targetPath}/postman_environment_template.json #ms-echo.postman_environment_template.json echo "targetCollection:$targetCollection,targetEnvironment:$targetEnvironment" echo -e "\n\n#### 生成${targetEnvironment}\n" if [ -d "${targetEnvironment}" ] ; then rm -rf ${targetEnvironment} fi cp ${projectAutoTestDir}/postman_environment_template.json ${targetEnvironment} sed -i "s/{{HTTP_URL}}/$dockerServerIP/g;s/{{HTTP_PORT}}/$dockerServerPort/g;" ${targetEnvironment} cat ${targetEnvironment} sleep 50 #curl http://$dockerServerIP:$dockerServerPort/ echo -e "\n\n#### 执行批量测试\n" newman run ${projectAutoTestDir}/*_collection.json --environment ${targetEnvironment} temp=$? if [[ $temp -ne 0 ]]; then exit $temp fi echo -e "##################### autoTest end ################################" echo -e "\n\n\n################################################################\n" <file_sep>/jenkins/bak/template/k8s/bak1/exec.sh #!/usr/bin/env bash #第一次运行 #ssh-keygen #ssh-copy-id -i ~/.ssh/id_rsa.pub root@10.1.12.200 #修改这两个文件 ip=10.1.12.70 svcname=sys-gateway-test templateFileNme=k8s-template.yaml execFileName=k8s.sh toPath=/root/${svcname}/test/ ssh root@$ip "rm -rf $toPath ; mkdir -p $toPath" #复制模板和执行文件 scp $templateFileNme root@$ip:${toPath}${templateFileNme} scp $execFileName root@$ip:${toPath}${execFileName} #执行命令文件 echo $toPath ssh root@$ip "cd ${toPath}; chmod 777 ${execFileName} ; ./${execFileName} " <file_sep>/jenkins/common/springboot-maven-docker/dev/scripts/11configout.sh #!/usr/bin/env bash echo -e "\n\n\n##################################################################" echo -e "##################### 备份配置脚本 start ################################" #在父目录下创建jenkins-job项目 cd .. rm -rf jenkins-job/ mkdir -p jenkins-job/jenkins/ echo "项目目录:${WORKSPACE} $(pwd)" #回到当前项目 cd ${WORKSPACE} cp -rf jenkins/* ../jenkins-job/jenkins/ ; ls -l ../jenkins-job/jenkins/ function getdir(){ for element in `ls $1` do dir_or_file=$1"/"$element if [ -d $dir_or_file ] then getdir $dir_or_file else echo $dir_or_file fi done } #getdir ../jenkins-job/jenkins/ echo -e "##################### 备份配置脚本 end ################################" echo -e "###########################################################\n\n\n" <file_sep>/jenkins02/mps-template/0.0.1-snapshot/dev/springboot-maven-docker/config/init_after_dockerdeploy.properties #MS_ALL_CONF= # --env MS_ALL_CONF=\" # --spring.application.name=${MSNAME} \ # --server.port=${HTTPPORT} \ # --tcp.port=${TCPPORT} \ # --endpoints.health.sensitive=false \ # --management.security.enabled=false \ # --management.health.consul.enabled=false \ # --spring.cloud.consul.discovery.enabled=true \ # --spring.cloud.consul.discovery.hostname=${ip} \ # --spring.cloud.consul.discovery.port=${HTTPPORT} \ # --spring.cloud.consul.discovery.serviceName=${MSNAME} \ # --spring.cloud.consul.host=${consulIP} \ # --spring.cloud.consul.port=${consulPort} \ # # --spring.cloud.consul.discovery.healthCheckUrl=http://${ip}:${HTTPPORT}/health \ # \"<file_sep>/jenkins01/common/springboot-maven-docker/dev/scripts/02unittest.sh #!/usr/bin/env bash echo -e "\n\n\n##################################################################" echo -e "##################### 单元测试 start ################################" source $(pwd)/init_var.sh init_after_unittest_config="${projectConfigDir}/init_after_unittest.properties" if [ -f "$init_after_unittest_config" ]; then while read line do line=${line// /} echo "$line" k=${line%=*} v=${line#*=} if [ -z "$k" ] then echo "empty row" elif [ $(echo $k | grep "^#") != "" ] then echo ${line} else echo " export $k=${v} " >> ${rootDir}/init_var.sh echo " export $k=${v}" fi done < $init_after_unittest_config fi source ${rootDir}/init_var.sh #export echo -e "\n进行单元测试...\n " echo "SONAR_IP_PORT:$SONAR_IP_PORT, SONAR_CREDENTIALSID:$SONAR_CREDENTIALSID " ; mvn test echo -e "##################### 单元测试 end ################################" echo -e "###########################################################\n\n\n" <file_sep>/README.md # mgicode-jenkins-pipeline 完全使用pipeline来构建自动化devops的流程 ##文档 todo<file_sep>/jenkins/bak/scripts/k8sdeploy.sh #!/usr/bin/env bash echo -e "\n\n\n##################################\n" echo -e "#### k8sDeploy start #######\n\n\n" source $(pwd)/target/init_var.sh export REPEAT_COUNT=${1:-1} HTTP_PORT=${2:-8080} templateDir=${rootDir}/jenkins/template/k8s/deploy deployTarget=${targetPath}/deploy deployYaml=${deployTarget}/deploy.yaml k8sDir=/helmdata/$jarNameVersion/deploy #COMMON_NAME=${dockerName} #名称中去掉小数点,如my-app-1.0-snapshot COMMON_NAME=${dockerName/./} #k8sServiceName echo ${dockerName//\//\\} #修改这几个参数 IMAGES_ADDR=`echo $dockerPath |sed "s/\//\\\\\\\\\//g"` echo -e "\n\n\n#### 正在生成检查生成 ${deployYaml}...\n\n\n" mkdir -p ${deployTarget}/ cp ${templateDir}/deploy.yaml ${deployYaml} sed -i "s/{{SERVICE_NAME}}/$k8sServiceName/g;s/{{COMMON_NAME}}/$COMMON_NAME/g;s/{{REPEAT_COUNT}}/$REPEAT_COUNT/g;s/{{IMAGES_ADDR}}/$IMAGES_ADDR/g;s/{{HTTP_PORT}}/$HTTP_PORT/g" ${deployYaml} #显示生成文件 echo -e "\n\n#### 请检查生成 ${deployYaml}\n\n\n" cat ${deployYaml} echo -e "\n\n#### 删除老目录,创建新目录:${k8sDir}/" ssh $k8sUser@$k8sAddr " rm -rf ${k8sDir}/* ; mkdir -p ${k8sDir}/ ;ls ${k8sDir}/" echo -e "\n\n#### 把${deployYaml}文件部署到,$k8sUser@$k8sAddr:${k8sDir}/deploy.yaml" scp ${deployYaml} $k8sUser@$k8sAddr:${k8sDir}/deploy.yaml ssh $k8sUser@$k8sAddr " ls -la ${k8sDir}/ ; cat ${k8sDir}/deploy.yaml " echo -e "\n\n#### 在$k8sUser@$k8sAddr 中 ${k8sDir}/部署deploy.yaml" ssh $k8sUser@$k8sAddr " kubectl delete -f ${k8sDir}/deploy.yaml ; kubectl create -f ${k8sDir}/deploy.yaml ; kubectl get all |grep '${COMMON_NAME}' " echo -e "\n\n\n##################################\n" echo -e "#### k8sDeploy end #######\n\n\n"
ee70b9aea55d3f0a506162e21909476048822bb1
[ "Markdown", "Shell", "Dockerfile", "INI" ]
26
INI
mgicode/mgicode-jenkins-pipeline
e2a7c6e17d04c9bb8b0fc5e550364d6cea16a00b
f07d5ca36a47df72ae4386d7a9e889447ced5e85
refs/heads/master
<repo_name>Munjie/LogisticsMS<file_sep>/src/main/java/com/mwj/dao/ProducingareaDao.java package com.mwj.dao; import com.mwj.mapper.ProducingareaMapper; import com.mwj.model.Producingarea; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Repository public class ProducingareaDao { @Resource private ProducingareaMapper producingareaMapper; //显示烟叶产地 public List<Producingarea> selectByPrimaryKey(){ final List<Producingarea> producingareas = producingareaMapper.selectByPrimaryKey(); return producingareas; } } <file_sep>/src/main/java/com/mwj/mapper/CompanyMapper.java package com.mwj.mapper; import com.mwj.model.Company; import org.apache.ibatis.annotations.Param; import java.math.BigDecimal; import java.util.List; public interface CompanyMapper { //显示所有公司详细信息 List<Company> showAllCompany(); //显示委托方 Company showClient(int showClientId); //显示发货方 Company showDeliver(int showDeliverId); }<file_sep>/src/main/java/com/mwj/controller/RawentryController.java package com.mwj.controller; import com.mwj.model.*; import com.mwj.service.*; import org.apache.ibatis.annotations.Param; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.text.SimpleDateFormat; import java.util.*; @RequestMapping("/") @Controller public class RawentryController { @Resource private CompanyService companyService; @Resource private StoragelocationService storagelocationService; @Resource private UserService userService; @Resource private ProducingareaService producingareaService; @Resource private RawentryService rawentryService; @Resource private RawentrydetailService rawentrydetailService; @Resource private RawcheckService rawcheckService; @Resource private VerifyinfoService verifyinfoService; @InitBinder public void bindDate(ServletRequestDataBinder requestDataBinder) { requestDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false)); } @RequestMapping("creteRowentry.do") public String rawEntry(Model model){ final List<Company> companies = companyService.showAllCompany(); final List<Storagelocation> storagelocations = storagelocationService.displayStoragelocation(); final List<Users> users = userService.showUser(); final List<Producingarea> producingareas = producingareaService.selectByPrimaryKey(); model.addAttribute("company",companies); model.addAttribute("storagelocations",storagelocations); model.addAttribute("producingareas",producingareas); model.addAttribute("users",users); if (companies != null && storagelocations != null && users != null && producingareas != null) return "Raw/RawEntry/createRawEntry"; else return null; } //入库 @RequestMapping("addRowentry.do") public String addRowentry(Rawentry rawentry,@RequestParam("rawentryData")String rawentryData, Model model){ final boolean b = rawentryService.addRawentry(rawentry); String[] temp = rawentryData.split(","); Rawentrydetail rawentrydetail = new Rawentrydetail(); Verifyinfo verifyinfo = new Verifyinfo(); List<RawentryDetailSheet> list = new ArrayList<>(); int rawentryId = rawentry.getId(); verifyinfo.setRawEntryId(rawentryId); verifyinfo.setDate(rawentry.getEntrydate()); verifyinfo.setVerifier(rawentry.getOperator()); final boolean b2 = verifyinfoService.addVerifyinfo(verifyinfo); for (int i = 0;i<temp.length/8;i++){ rawentrydetail.setId(Integer.parseInt(temp[8*i]));//入库详细id rawentrydetail.setStandard(temp[8*i+2]);//入库规格 rawentrydetail.setAmount(Integer.parseInt(temp[8*i+3]));//入库数量 rawentrydetail.setLocation(Integer.parseInt(temp[8*i+4]));//库位 rawentrydetail.setWeight(temp[8*i+7]);//重量 rawentrydetail.setEntryinfo(rawentryId);//入库关联id rawentrydetail.setRawcheck(rawcheckService.queryRawChcekId(temp[8*i+1]));//入库关联抽检id final boolean b1 = rawentrydetailService.addRawentryDetail(rawentrydetail); } for(int j = 0; j < temp.length/8;j++){ RawentryDetailSheet rawentryDetailSheet = new RawentryDetailSheet(); rawentryDetailSheet.setId(j);//序号 rawentryDetailSheet.setRawcheck(temp[8*j+1]); rawentryDetailSheet.setStandard(temp[8*j+2]);//规格 rawentryDetailSheet.setAmount(Integer.parseInt(temp[8*j+3]));//数量 rawentryDetailSheet.setLocation(Integer.parseInt(temp[8*j+4]));//库位 rawentryDetailSheet.setLeaveName(temp[8*j+5]);//等级 rawentryDetailSheet.setTobaccoGory(temp[8*j+6]);//品种 rawentryDetailSheet.setWeight(temp[8*j+7]);//重量 list.add(rawentryDetailSheet); } final Map map = rawentryService.displayRawentry(rawentryId); model.addAttribute("map",map); model.addAttribute("sheetlist",list); if (b) return "table/RawEntrySheet"; else return null; } @RequestMapping("checknuminfo.do") @ResponseBody public List<Map> checkNumInfo(String checkNum){ List<Map> mapList = rawentryService.checkNemberInfo(checkNum); for (int i = 0;i<mapList.size();i++){ System.out.println(mapList.get(i)); } return mapList; } //回显入库打印表 @RequestMapping("displayRawentrySheet") public String showRawentrySheet(String entrynum,Model model){ final List<Map> mapList = rawentryService.showRawentrySheet(entrynum); model.addAttribute("maplist",mapList); return "Raw/RawEntry/retriveRawEntry"; } @RequestMapping("verifyRawentry.do") public String verifyRawentry(Model model){ final List<Map> mapList = rawentryService.allRawentry(); model.addAttribute("mapverify",mapList); if (mapList != null) return "Raw/RawEntry/allRawEntry"; else return null; } @RequestMapping("verifyByEntry.do") public String lastVerrify(@RequestParam("entryNumber") String entryNumber,Model model){ final List<Map> mapList = rawentryService.showVeryRawentry(entryNumber); model.addAttribute("entrymap",mapList); return "Raw/RawEntry/verifyRawEntry"; } } <file_sep>/src/main/java/com/mwj/dao/VerifyinfoDao.java package com.mwj.dao; import com.mwj.mapper.VerifyinfoMapper; import com.mwj.model.Verifyinfo; import org.springframework.stereotype.Repository; import javax.annotation.Resource; @Repository public class VerifyinfoDao { @Resource private VerifyinfoMapper verifyinfoMapper; //添加新入库审核信息 public boolean addVerifyinfo(Verifyinfo record){ final int i = verifyinfoMapper.addVerifyinfo(record); return i > 0; } } <file_sep>/src/main/java/com/mwj/mapper/TobaccocategoryMapper.java package com.mwj.mapper; import com.mwj.model.Tobaccocategory; import java.math.BigDecimal; import java.util.List; public interface TobaccocategoryMapper { //烟叶品种 List<Tobaccocategory> selectByPrimaryKey(); }<file_sep>/src/main/java/com/mwj/service/UserService.java package com.mwj.service; import com.mwj.dao.UserDao; import com.mwj.model.Users; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class UserService { @Resource private UserDao userDao; //登录 public Users login(Users users){ return userDao.login(users); } //显示员工 public List<Users> showUser(){ final List<Users> users = userDao.showUser(); return users; } } <file_sep>/src/main/java/com/mwj/service/CompanyService.java package com.mwj.service; import com.mwj.dao.CompanyDao; import com.mwj.model.Company; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class CompanyService { @Resource private CompanyDao companyDao; //显示所有公司详细信息 public List<Company> showAllCompany(){ return companyDao.showAllCompany(); } //显示委托方 public Company showClient(int id){ return companyDao.showClient(id); } //显示发货方 public Company showDeliver(int id){ return companyDao.showDeliver(id); } } <file_sep>/src/main/java/com/mwj/model/Rawtobacco.java package com.mwj.model; import java.math.BigDecimal; public class Rawtobacco { private int id; private int level; private int producingyear; private int producingarea; private int tobaccocategory; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public int getProducingyear() { return producingyear; } public void setProducingyear(int producingyear) { this.producingyear = producingyear; } public int getProducingarea() { return producingarea; } public void setProducingarea(int producingarea) { this.producingarea = producingarea; } public int getTobaccocategory() { return tobaccocategory; } public void setTobaccocategory(int tobaccocategory) { this.tobaccocategory = tobaccocategory; } }<file_sep>/src/main/java/com/mwj/mapper/RawentrydetailMapper.java package com.mwj.mapper; import com.mwj.model.Rawentrydetail; import java.math.BigDecimal; public interface RawentrydetailMapper { //添加入库重量信息 int addRawentryDetail(Rawentrydetail record); }<file_sep>/src/main/java/com/mwj/mapper/RawcheckMapper.java package com.mwj.mapper; import com.mwj.model.Rawcheck; import java.math.BigDecimal; import java.util.List; import java.util.Map; public interface RawcheckMapper { //新增抽检 int addRocheck(Rawcheck record); Rawcheck selectByPrimaryKey(BigDecimal id); //查询抽检信息 List<Rawcheck> showRawChcekById(int id); //根据抽检单号查询信息 List<Map> displayRawcheckByChecknum(String checknum); //根据抽检ID查询信息 Map displayRawcheckByCheckId(int checkId); //查询抽检单号根据抽检单 int queryRawChcekId (String checknum); }<file_sep>/src/main/java/com/mwj/model/Rawcheck.java package com.mwj.model; import java.util.Date; public class Rawcheck { private int id; private String code; private int deliverycompany; private int client; private String carnum; private int rawtobacco; private String checknum; private Date checkdate; private int operator; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code == null ? null : code.trim(); } public int getDeliverycompany() { return deliverycompany; } public void setDeliverycompany(int deliverycompany) { this.deliverycompany = deliverycompany; } public int getClient() { return client; } public void setClient(int client) { this.client = client; } public String getCarnum() { return carnum; } public void setCarnum(String carnum) { this.carnum = carnum == null ? null : carnum.trim(); } public int getRawtobacco() { return rawtobacco; } public void setRawtobacco(int rawtobacco) { this.rawtobacco = rawtobacco; } public String getChecknum() { return checknum; } public void setChecknum(String checknum) { this.checknum = checknum == null ? null : checknum.trim(); } public Date getCheckdate() { return checkdate; } public void setCheckdate(Date checkdate) { this.checkdate = checkdate; } public int getOperator() { return operator; } public void setOperator(int operator) { this.operator = operator; } }<file_sep>/src/main/java/com/mwj/model/Rawentrydetail.java package com.mwj.model; public class Rawentrydetail { private int id; private int entryinfo; private int rawcheck; private int amount; private String standard; private String weight; private int location; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getEntryinfo() { return entryinfo; } public void setEntryinfo(int entryinfo) { this.entryinfo = entryinfo; } public int getRawcheck() { return rawcheck; } public void setRawcheck(int rawcheck) { this.rawcheck = rawcheck; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public String getStandard() { return standard; } public void setStandard(String standard) { this.standard = standard == null ? null : standard.trim(); } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight == null ? null : weight.trim(); } public int getLocation() { return location; } public void setLocation(int location) { this.location = location; } }<file_sep>/src/main/java/com/mwj/dao/RawentryDao.java package com.mwj.dao; import com.mwj.mapper.RawentryMapper; import com.mwj.model.Rawentry; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.List; import java.util.Map; @Repository public class RawentryDao { @Resource private RawentryMapper rawentryMapper; //增加入库信息 public boolean addRawentry(Rawentry record){ final int i = rawentryMapper.addRawentry(record); return i > 0; } //显示入库信息 public Map displayRawentry(int rawentryId){ return rawentryMapper.displayRawentry(rawentryId); } //ajax显示抽检信息 public List<Map> checkNemberInfo(String checkNumber){ return rawentryMapper.checkNemberInfo(checkNumber); } //回显入库信息打印表 public List<Map> showRawentrySheet(String entryNumber){ return rawentryMapper.showRawentrySheet(entryNumber); } //入库审核显示 public List<Map> allRawentry(){ return rawentryMapper.allRawentry(); } //审核信息 public List<Map> showVeryRawentry(String veryEntryNumber){ return rawentryMapper.showVeryRawentry(veryEntryNumber); } } <file_sep>/src/main/java/com/mwj/model/Rawcheckdetail.java package com.mwj.model; import java.math.BigDecimal; public class Rawcheckdetail { private int id; private int checkinfo; private int sequence; private String checkweight; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCheckinfo() { return checkinfo; } public void setCheckinfo(int checkinfo) { this.checkinfo = checkinfo; } public int getSequence() { return sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public String getCheckweight() { return checkweight; } public void setCheckweight(String checkweight) { this.checkweight = checkweight == null ? null : checkweight.trim(); } @Override public String toString() { return "Rawcheckdetail{" + "id=" + id + ", checkinfo=" + checkinfo + ", sequence=" + sequence + ", checkweight='" + checkweight + '\'' + '}'; } }<file_sep>/src/main/java/com/mwj/service/RawcheckService.java package com.mwj.service; import com.mwj.dao.RawcheckDao; import com.mwj.model.Rawcheck; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; @Service public class RawcheckService { @Resource private RawcheckDao rawcheckDao; //新增抽检 public boolean addRocheck(Rawcheck record){ record.setChecknum(RawcheckService.getRawCheckId()); return rawcheckDao.addRocheck(record); } //查询抽检信息 public List<Rawcheck> showRawChcekById(int id){ return rawcheckDao.showRawChcekById(id); } //根据抽检单号查询信息 public List<Map> displayRawcheckByChecknum(String checknum){ return rawcheckDao.displayRawcheckByChecknum(checknum); } //根据抽检ID查询信息 public Map displayRawcheckByCheckId(int checkId){ return rawcheckDao.displayRawcheckByCheckId(checkId); } //查询抽检单号根据抽检单 public int queryRawChcekId (String checknum){ return rawcheckDao.queryRawChcekId(checknum); } public static String getRawCheckId(){ Date date = new Date(); DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSSS"); String tempDate = dateFormat.format(date); String racheckId = "CJ" + tempDate; return racheckId; } } <file_sep>/src/main/java/com/mwj/service/StoragelocationService.java package com.mwj.service; import com.mwj.dao.StoragelocationDao; import com.mwj.model.Storagelocation; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class StoragelocationService { @Resource private StoragelocationDao storagelocationDao; //显示所有的仓库 public List<Storagelocation> displayStoragelocation(){ return storagelocationDao.displayStoragelocation(); } } <file_sep>/src/main/java/com/mwj/model/Rawentry.java package com.mwj.model; import java.util.Date; public class Rawentry { private int id; private String entrynum; private Date entrydate; private int deliverycompany; private int client; private String carnum; private int operator; private int storagelocationid; private int producingyear; private int producingarea; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEntrynum() { return entrynum; } public void setEntrynum(String entrynum) { this.entrynum = entrynum == null ? null : entrynum.trim(); } public Date getEntrydate() { return entrydate; } public void setEntrydate(Date entrydate) { this.entrydate = entrydate; } public int getDeliverycompany() { return deliverycompany; } public void setDeliverycompany(int deliverycompany) { this.deliverycompany = deliverycompany; } public int getClient() { return client; } public void setClient(int client) { this.client = client; } public String getCarnum() { return carnum; } public void setCarnum(String carnum) { this.carnum = carnum == null ? null : carnum.trim(); } public int getOperator() { return operator; } public void setOperator(int operator) { this.operator = operator; } public int getStoragelocationid() { return storagelocationid; } public void setStoragelocationid(int storagelocationid) { this.storagelocationid = storagelocationid; } public int getProducingyear() { return producingyear; } public void setProducingyear(int producingyear) { this.producingyear = producingyear; } public int getProducingarea() { return producingarea; } public void setProducingarea(int producingarea) { this.producingarea = producingarea; } }<file_sep>/src/main/java/com/mwj/dao/RawentrydetailDao.java package com.mwj.dao; import com.mwj.mapper.RawentrydetailMapper; import com.mwj.model.Rawentrydetail; import org.springframework.stereotype.Repository; import javax.annotation.Resource; @Repository public class RawentrydetailDao { @Resource private RawentrydetailMapper rawentrydetailMapper; //添加入库重量信息 public boolean addRawentryDetail(Rawentrydetail record){ final int i = rawentrydetailMapper.addRawentryDetail(record); return i > 0; } } <file_sep>/src/main/java/com/mwj/mapper/RawtobaccoMapper.java package com.mwj.mapper; import com.mwj.model.Rawtobacco; import java.math.BigDecimal; public interface RawtobaccoMapper { int addRawtobacco(Rawtobacco record); }<file_sep>/src/main/java/com/mwj/service/RawentrydetailService.java package com.mwj.service; import com.mwj.dao.RawentrydetailDao; import com.mwj.model.Rawentrydetail; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class RawentrydetailService { @Resource private RawentrydetailDao rawentrydetailDao; //添加入库重量信息 public boolean addRawentryDetail(Rawentrydetail record){ return rawentrydetailDao.addRawentryDetail(record); } } <file_sep>/src/main/webapp/js/frame.js // JavaScript Document parent.document.all('content').style.height=document.body.scrollHeight; parent.document.all('content').style.width=document.body.scrollWidth;<file_sep>/src/main/java/com/mwj/mapper/RawentryMapper.java package com.mwj.mapper; import com.mwj.model.Rawentry; import java.util.List; import java.util.Map; public interface RawentryMapper { //增加入库信息 int addRawentry(Rawentry record); //显示入库信息 Map displayRawentry(int rawentryId); //ajax显示抽检信息 List<Map> checkNemberInfo(String checkNumber); //回显入库信息打印表 List<Map> showRawentrySheet(String entryNumber); //入库审核显示 List<Map> allRawentry(); //审核信息 List<Map> showVeryRawentry(String veryEntryNumber); }
e19d014db4e2c07d06a54c5abd872552f79bcc1d
[ "JavaScript", "Java" ]
22
Java
Munjie/LogisticsMS
4087f7a29538ad6ab28fc97af9621ed5ec5b371c
cb9206767c6d002dbc360228809a68a1a2ec8ef5
refs/heads/master
<repo_name>gitalek/lambda-brain-data-structures<file_sep>/README.md ![Testing](https://github.com/gitalek/lambda-brain-data-structures/workflows/Testing/badge.svg) ![Linting](https://github.com/gitalek/lambda-brain-data-structures/workflows/Linting/badge.svg) <file_sep>/Makefile install: poetry install run: poetry run linked_list build: rm -rf dist/ poetry build lint: poetry run flake8 data_structures tests test: poetry run pytest -vv test_linked_list: poetry run pytest -vv tests/test_linked_list.py -s test_doubly_linked_list: poetry run pytest -vv tests/test_doubly_linked_list.py -s <file_sep>/data_structures/scripts/linked_list.py # from linked_list.linked_list def main(): print('Linked list realization!') if __name__ == '__main__': main() <file_sep>/tests/test_doubly_linked_list.py from data_structures.doubly_linked_list import LinkedList2, Node import pytest @pytest.fixture def setup_nodes(): n1 = Node(1) n2 = Node(2) n3 = Node(3) n4 = Node(4) return [n1, n2, n3, n4] @pytest.fixture def setup_linked_list(setup_nodes): n1, n2, n3, n4 = setup_nodes linkedList = LinkedList2() linkedList.add_in_tail(n1) linkedList.add_in_tail(n2) linkedList.add_in_tail(n3) linkedList.add_in_tail(n4) return linkedList def test_len_and_clean_and_is_empty_methods(setup_nodes): n1, n2, n3, n4 = setup_nodes myLinkedList = LinkedList2() assert myLinkedList.len() == 0 assert myLinkedList.is_empty() is True myLinkedList.add_in_tail(n1) assert myLinkedList.len() == 1 assert myLinkedList.is_empty() is False myLinkedList.add_in_tail(n2) myLinkedList.add_in_tail(n3) myLinkedList.add_in_tail(n4) assert myLinkedList.len() == 4 assert myLinkedList.is_empty() is False myLinkedList.clean() assert myLinkedList.len() == 0 assert myLinkedList.is_empty() is True def test_find_all_method(setup_linked_list, setup_nodes): n1, n2, n3, n4 = setup_nodes emptyLinkedList = LinkedList2() assert emptyLinkedList.find_all('non-existent value') == [] assert setup_linked_list.find_all('non-existent value') == [] assert setup_linked_list.find_all(1) == [n1] assert setup_linked_list.find_all(4) == [n4] sameAsN1 = Node(1) sameAsN4 = Node(4) setup_linked_list.add_in_tail(sameAsN1) setup_linked_list.add_in_tail(sameAsN4) assert setup_linked_list.find_all(1) == [n1, sameAsN1] assert setup_linked_list.find_all(4) == [n4, sameAsN4] def test_delete_method(setup_linked_list, setup_nodes): n1, n2, n3, n4 = setup_nodes deletedN1 = setup_linked_list.delete(1) assert setup_linked_list.len() == 3 assert deletedN1 == n1 assert setup_linked_list.head == n2 assert setup_linked_list.tail == n4 deletedN2 = setup_linked_list.delete(2) assert setup_linked_list.len() == 2 assert deletedN2 == n2 assert setup_linked_list.head == n3 assert setup_linked_list.tail == n4 deletedN3 = setup_linked_list.delete(3) assert setup_linked_list.len() == 1 assert deletedN3 == n3 assert setup_linked_list.head == n4 assert setup_linked_list.tail == n4 assert n4.next is None assert n4.prev is None deletedN4 = setup_linked_list.delete(4) assert setup_linked_list.len() == 0 assert deletedN4 == n4 assert setup_linked_list.head is None assert setup_linked_list.tail is None def test_delete_method_delete_all_case(setup_linked_list, setup_nodes): n1, n2, n3, n4 = setup_nodes n2_01 = Node(2) n2_02 = Node(2) n2_03 = Node(2) n2_04 = Node(2) setup_linked_list.add_in_tail(n2_01) setup_linked_list.add_in_tail(n2_02) setup_linked_list.add_in_tail(n2_03) setup_linked_list.add_in_tail(n2_04) deletedN2Nodes = setup_linked_list.delete(2, True) assert deletedN2Nodes == [n2, n2_01, n2_02, n2_03, n2_04] assert setup_linked_list.len() == 3 assert setup_linked_list.head == n1 assert setup_linked_list.tail == n4 n3_01 = Node(3) setup_linked_list.add_in_tail(n3_01) deletedN3Nodes = setup_linked_list.delete(3, True) assert deletedN3Nodes == [n3, n3_01] assert setup_linked_list.len() == 2 assert setup_linked_list.head == n1 assert setup_linked_list.tail == n4 deletedN1Nodes = setup_linked_list.delete(1, True) assert deletedN1Nodes == [n1] deletedN4Nodes = setup_linked_list.delete(4, True) assert deletedN4Nodes == [n4] assert setup_linked_list.head is None assert setup_linked_list.tail is None def test_delete_method_delete_all_case_additional( setup_linked_list, setup_nodes, ): n1, n2, n3, n4 = setup_nodes n2_01 = Node(2) n2_02 = Node(2) n2_03 = Node(2) n2_04 = Node(2) setup_linked_list.delete(1, True) setup_linked_list.delete(4, True) assert setup_linked_list.len() == 2 setup_linked_list.add_in_tail(n2_01) setup_linked_list.add_in_tail(n2_02) setup_linked_list.add_in_tail(n2_03) setup_linked_list.add_in_tail(n2_04) assert setup_linked_list.len() == 6 deletedN2Nodes = setup_linked_list.delete(2, True) assert deletedN2Nodes == [n2, n2_01, n2_02, n2_03, n2_04] assert setup_linked_list.len() == 1 assert setup_linked_list.head == n3 assert setup_linked_list.tail == n3 assert n3.next is None assert n3.prev is None deletedN3Nodes = setup_linked_list.delete(3, True) assert deletedN3Nodes == [n3] assert setup_linked_list.len() == 0 assert setup_linked_list.head is None assert setup_linked_list.tail is None def test_insert_method(setup_linked_list, setup_nodes): n1, n2, n3, n4 = setup_nodes myLinkedList = LinkedList2() n5 = Node(5) n6 = Node(6) myLinkedList.insert(None, n5) assert myLinkedList.len() == 1 assert myLinkedList.head == n5 assert myLinkedList.tail == n5 myLinkedList.insert(n5, n6) assert myLinkedList.len() == 2 assert myLinkedList.head == n5 assert myLinkedList.tail == n6 <file_sep>/data_structures/linked_list.py class Node: def __init__(self, v): self.value = v self.next = None class LinkedList: # очистка нод (свойства next)?_? # мутабельный LinkedList?_? # добавить указатель на текущую ноду списка?_? def __init__(self): self.head = None self.tail = None def add_in_tail(self, item): if self.head is None: self.head = item else: self.tail.next = item self.tail = item def print_all_nodes(self): node = self.head while node is not None: print(node.value) node = node.next def find(self, val): node = self.head while node is not None: if node.value == val: return node node = node.next return None def find_all(self, val): node = self.head nodes = [] while node is not None: if node.value == val: nodes.append(node) node = node.next return nodes def delete(self, val, all=False): # returned value?_? curNode = self.head deletedNodes = [] while curNode is not None: if curNode.value != val: prevNode = curNode curNode = curNode.next continue if curNode is self.head and curNode is self.tail: self.head = None self.tail = None elif curNode is self.head: self.head = curNode.next elif curNode is self.tail: prevNode.next = None # experiment self.tail = prevNode else: prevNode.next = curNode.next if not all: return curNode else: deletedNodes.append(curNode) curNode = curNode.next return deletedNodes def clean(self): # need immutable version?_? # return LinkedList() self.head = None self.tail = None def len(self): node = self.head i = 0 while node is not None: i += 1 node = node.next return i def insert(self, afterNode, newNode): if afterNode is None: newNode.next = self.head self.head = newNode self.tail = newNode # Interface method?_? return if afterNode is self.tail: self.add_in_tail(newNode) return node = self.head while node is not None: if node is afterNode: # протестить эту строку newNode.next = afterNode.next afterNode.next = newNode node = node.next def to_list(self, onlyValues=False): node = self.head nodes = [] while node is not None: value = node.value if onlyValues else node nodes.append(value) node = node.next return nodes def zip_lists(list1, list2): count = list1.len() if count != list2.len(): return None if count == 0: return LinkedList() result = LinkedList() node1 = list1.head node2 = list2.head for _ in range(count): val1, val2 = node1.value, node2.value node = Node(val1 + val2) result.add_in_tail(node) node1, node2 = node1.next, node2.next return result <file_sep>/tests/test_linked_list.py from data_structures.linked_list import LinkedList, Node, zip_lists import pytest @pytest.fixture def setup_nodes(): n1 = Node(1) n2 = Node(2) n3 = Node(3) n4 = Node(4) return [n1, n2, n3, n4] @pytest.fixture def setup_linked_list(setup_nodes): n1, n2, n3, n4 = setup_nodes linkedList = LinkedList() linkedList.add_in_tail(n1) linkedList.add_in_tail(n2) linkedList.add_in_tail(n3) linkedList.add_in_tail(n4) return linkedList def test_len_and_clean_methods(setup_nodes): n1, n2, n3, n4 = setup_nodes myLinkedList = LinkedList() assert myLinkedList.len() == 0 myLinkedList.add_in_tail(n1) assert myLinkedList.len() == 1 myLinkedList.add_in_tail(n2) myLinkedList.add_in_tail(n3) myLinkedList.add_in_tail(n4) assert myLinkedList.len() == 4 myLinkedList.clean() assert myLinkedList.len() == 0 def test_find_all_method(setup_linked_list, setup_nodes): n1, n2, n3, n4 = setup_nodes emptyLinkedList = LinkedList() assert emptyLinkedList.find_all('non-existent value') == [] assert setup_linked_list.find_all('non-existent value') == [] assert setup_linked_list.find_all(1) == [n1] assert setup_linked_list.find_all(4) == [n4] sameAsN1 = Node(1) sameAsN4 = Node(4) setup_linked_list.add_in_tail(sameAsN1) setup_linked_list.add_in_tail(sameAsN4) assert setup_linked_list.find_all(1) == [n1, sameAsN1] assert setup_linked_list.find_all(4) == [n4, sameAsN4] def test_delete_method(setup_linked_list, setup_nodes): n1, n2, n3, n4 = setup_nodes emptyLinkedList = LinkedList() emptyLinkedList.delete(1) assert emptyLinkedList.len() == 0 deletedN1 = setup_linked_list.delete(1) assert setup_linked_list.len() == 3 assert deletedN1 == n1 deletedN4 = setup_linked_list.delete(4) assert setup_linked_list.len() == 2 assert deletedN4 == n4 assert setup_linked_list.head == n2 assert setup_linked_list.tail == n3 sameAsN2 = Node(2) sameAsN3 = Node(3) setup_linked_list.add_in_tail(sameAsN2) setup_linked_list.add_in_tail(sameAsN3) deletedN2Nodes = setup_linked_list.delete(2, True) assert deletedN2Nodes == [n2, sameAsN2] assert setup_linked_list.len() == 2 assert setup_linked_list.head == n3 assert setup_linked_list.tail == sameAsN3 deletedN3Nodes = setup_linked_list.delete(3, True) assert deletedN3Nodes == [n3, sameAsN3] assert setup_linked_list.len() == 0 assert setup_linked_list.head is None assert setup_linked_list.tail is None def test_delete_method_delete_all_case(setup_linked_list, setup_nodes): n1, n2, n3, n4 = setup_nodes n2_01 = Node(2) n2_02 = Node(2) n2_03 = Node(2) n2_04 = Node(2) setup_linked_list.add_in_tail(n2_01) setup_linked_list.add_in_tail(n2_02) setup_linked_list.add_in_tail(n2_03) setup_linked_list.add_in_tail(n2_04) deletedN2Nodes = setup_linked_list.delete(2, True) assert deletedN2Nodes == [n2, n2_01, n2_02, n2_03, n2_04] assert setup_linked_list.len() == 3 assert setup_linked_list.head == n1 assert setup_linked_list.tail == n4 n3_01 = Node(3) setup_linked_list.add_in_tail(n3_01) deletedN3Nodes = setup_linked_list.delete(3, True) assert deletedN3Nodes == [n3, n3_01] assert setup_linked_list.len() == 2 assert setup_linked_list.head == n1 assert setup_linked_list.tail == n4 deletedN1Nodes = setup_linked_list.delete(1, True) assert deletedN1Nodes == [n1] deletedN4Nodes = setup_linked_list.delete(4, True) assert deletedN4Nodes == [n4] assert setup_linked_list.head is None assert setup_linked_list.tail is None def test_insert_method(setup_linked_list, setup_nodes): n1, n2, n3, n4 = setup_nodes myLinkedList = LinkedList() n5 = Node(5) n6 = Node(6) myLinkedList.insert(None, n5) assert myLinkedList.len() == 1 assert myLinkedList.head == n5 assert myLinkedList.tail == n5 myLinkedList.insert(n5, n6) assert myLinkedList.len() == 2 assert myLinkedList.head == n5 assert myLinkedList.tail == n6 def test_zip_lists_function(setup_linked_list, setup_nodes): n1, n2, n3, n4 = setup_nodes result1 = zip_lists(LinkedList(), LinkedList()) assert result1.len() == 0 assert zip_lists(setup_linked_list, LinkedList()) is None result2 = zip_lists(setup_linked_list, setup_linked_list).to_list() actual = list(map(lambda node: node.value, result2)) expected = [2, 4, 6, 8] assert actual == expected <file_sep>/data_structures/doubly_linked_list.py class Node: def __init__(self, v): self.value = v self.prev = None self.next = None class LinkedList2: def __init__(self): self.head = None self.tail = None def add_in_tail(self, item): if self.head is None: self.head = item item.prev = None item.next = None else: self.tail.next = item item.prev = self.tail self.tail = item # покрыть тестами def add_in_head(self, item): if self.head is None: self.tail = item item.prev = None item.next = None else: self.head.prev = item item.next = self.head self.head = item # поиск с разных концов (флаг) # переписать на рекурсию def find(self, val): node = self.head while node is not None: if node.value == val: return node node = node.next return None def find_all(self, val): node = self.head nodes = [] while node is not None: if node.value == val: nodes.append(node) node = node.next return nodes def delete(self, val, all=False): pointer = self.head removedNodes = [] while pointer is not None: if pointer.value != val: pointer = pointer.next continue if pointer is self.head and pointer is self.tail: self.head = None self.tail = None elif pointer is self.head: self.head = pointer.next pointer.next.prev = None elif pointer is self.tail: self.tail = pointer.prev pointer.prev.next = None else: pointer.prev.next = pointer.next pointer.next.prev = pointer.prev if not all: return pointer else: removedNodes.append(pointer) pointer = pointer.next return removedNodes def clean(self): # need immutable version?_? # return LinkedList() self.head = None self.tail = None def len(self): node = self.head i = 0 while node is not None: i += 1 node = node.next return i def is_empty(self): return self.head is None def insert(self, afterNode, newNode): if afterNode is None: (self.add_in_head(newNode) if self.is_empty() else self.add_in_tail(newNode)) return if afterNode is self.tail: self.add_in_tail(newNode) return node = self.node while node is not None: if node is afterNode: newNode.next = afterNode.next afterNode.next = newNode newNode.prev = afterNode node = node.next def to_list(self, onlyValues=False): node = self.head nodes = [] while node is not None: value = node.value if onlyValues else node nodes.append(value) node = node.next return nodes <file_sep>/pyproject.toml [tool.poetry] name = "gitalek_linked_list" version = "0.2.4" description = "Data structures realization" authors = ["Alexander <<EMAIL>>"] packages = [ { include = "data_structures" } ] [tool.poetry.scripts] linked-list = "data_structures.scripts.linked_list:main" [tool.poetry.dependencies] python = "3.6.10" [tool.poetry.dev-dependencies] flake8 = "^3.7.9" pytest = "^5.3.5" [build-system] requires = ["poetry>=0.12"] build-backend = "poetry.masonry.api"
7bbf85415ea2e99ed08d7e312ad8a4880c8f1a26
[ "Markdown", "TOML", "Python", "Makefile" ]
8
Markdown
gitalek/lambda-brain-data-structures
e8c98126f80c642543d534623be20589a42a8b34
4e0558bb8edacf59daf8651a625c63e9e4376cdb
refs/heads/master
<file_sep>$(function ($) { $('.profileBG').backstretch($('.profileIMG').attr('src'), {fade: 800}); }); <file_sep>var body_var, html, doc, wnd, global_window_Height, popupOrderItem, controlPanelBtn, header, overlay, popupBtn, $completed_orders_form; $(function ($) { body_var = $('body'); html = $('html'); doc = $(document); wnd = $(window); global_window_Height = $(window).height(); popupOrderItem = $('.popup_order_item'); controlPanelBtn = $('.controlPanelBtn'); header = $('.header'); overlay = $('.glOverlay'); body_var .delegate('.scrollTo', 'click', function () { var el = $(this); el.parent().addClass('scroll_done').siblings().removeClass('scroll_done'); docScrollTo($(el.attr('data-scroll')).offset().top - header.outerHeight() - 20, 800); return false; }) .delegate('.openForm', 'click', function () { var btn = $(this), form = $(btn.attr('data-href')), step = $(this).attr('data-step'); html.toggleClass(form.attr('data-class')); overlay.toggle(); $('.voteStep').hide().filter(function () { return $(this).attr('data-step') == step; }).show(); form.fadeToggle(600); }) .delegate('.popupWrapper', 'click', function (e) { var target = $(e.target), el = $(this); if (!(target.hasClass('noClose') || target.closest('.noClose').length)) { $(this).fadeOut(600); overlay.fadeOut(600, function () { html.removeClass(el.attr('data-class')); }); } }) .delegate('.filterLink', 'click', function () { var item = $(this), target = $(item.attr('href')); item.parent().addClass('_active').siblings().removeClass('_active'); if (target.length) { $('.filterUnit').hide().addClass('_active'); target.show(); } else { $('.filterUnit').removeClass('_active').show(); } return false; }) .delegate('.popupClose', 'click', function () { var form = $(this).parents('.popupWrapper'); form.fadeOut(600); overlay.toggle(); html.toggleClass(form.attr('data-class')); return false; }) .delegate('.asideAddOpen', 'click', function () { $(this).parent().toggleClass('open_menu'); return false; }) .delegate('.voteStepBtn', 'click', function () { var step = $(this).attr('data-step'); $('.voteStep').hide().filter(function () { return $(this).attr('data-step') == step; }).show(); return false; }) .delegate('.voteCheck', 'change', function () { var radio = $(this), btn = $('.voteBtn'), new_class = btn.attr('class').replace(/btn_green|btn_red_3|btn_gray_2/, ''); btn.text(radio.attr('data-check-text')).attr('class', new_class).addClass(radio.attr('data-btn-class')); }) .delegate('.switchLights', 'change', function () { var slct = $(this); console.log(slct.find('option:selected').attr('data-class')); }) .delegate('.filterToggle', 'click', function () { var lnk = $(this); var dd = $(lnk.attr('href')); hideDropDowns(dd); lnk.parent().toggleClass('_active').siblings().removeClass('_active'); dd.toggleClass('open_menu'); return false; }) .delegate('.preloader', 'click', function () { runCircle($(this), 4000); return false; }) .delegate('.rmBtn', 'click', function () { $(this).closest('.rmUnit').remove(); return false; }) .delegate('.goTo', 'click', function (e) { if (!((e.target.tagName).toLowerCase() == 'a' || $(e.target).closest('a').length > 0 || $(e.target).closest('.open_menu').length > 0)) { var a = document.createElement('a'); a.href = $(this).attr('data-goto'); a.className = 'hide'; document.body.appendChild(a); setTimeout(function () { a.click(); }, 0); } }) .delegate('.userMenuBtn', 'click', function () { var dd = $(this).parent(); hideDropDowns(dd); dd.toggleClass('open_menu'); return false; }) .delegate('.loadMore', 'click', function () { var loaderBlock = $('.loaderBlock'), target = $($(this).attr('data-append-to')), interval; loaderBlock.show().find('.preloader').click(); console.log(target); interval = setInterval(function () { target.append($('<li> \ <div class="dash_box"> \ <div data-goto="meeting.html" class="dash_box_inner _meeting goTo"> \ <div class="fl"> \ <div class="mb"> \ <div class="dash_b_date"> \ <div class="day">1</div> \ <div class="month">сентября</div> \ </div> \ </div> \ <div class="mb"> \ <div class="dash_b_info fl"> \ <div class="dash_b_caption">№' + Math.floor(Math.random() * 999) + ', с 17:00 до 19:00</div> \ <p>Комитет по проектам и процессам</p> \ </div> \ </div> \ </div> \ <div class="fr"> \ <div class="mb">&nbsp; \ </div> \ <div class="mb"><a href="#" data-href="#vote_popup" data-step="3" class="dash_b_status openForm _in_preparation">ПОДГОТОВКА</a></div> \ <div class="mb"> \ <div class="menu_holder"> \ <div class="dash_b_menu_btn dashMenuBtn"> \ <div class="dash_b_menu_icon"></div> \ </div> \ <div class="dash_b_menu_w menu_w"> \ <ul class="dash_b_menu_list"> \ <li class="dash_menu_group"><span class="mb">Действия</span></li> \ <li><a href="#" class="dash_menu_link"><span class="mb">Редактировать</span></a></li> \ <li><a href="#" class="dash_menu_link"><span class="mb">Перейти к оформлению</span></a></li> \ <li><a href="#" class="dash_menu_link"><span class="mb">Удалить</span></a></li> \ </ul> \ <ul class="dash_b_menu_list"> \ <li class="dash_menu_group"><span class="mb">Cтатус</span></li> \ <li><a href="#" class="dash_menu_link"><span class="mb dash_m_status _in_process"></span><span class="mb">В ПРОЦЕССЕ</span></a></li> \ <li><a href="#" class="dash_menu_link"><span class="mb dash_m_status _new"></span><span class="mb">НОВАЯ</span></a></li> \ <li><a href="#" class="dash_menu_link"><span class="mb dash_m_status _completed"></span><span class="mb">ЗАВЕРШЕНО</span></a></li> \ </ul> \ </div> \ </div> \ </div> \ </div> \ </div> \ </div> \ </li>')); }, 500); setTimeout(function () { clearInterval(interval); loaderBlock.hide(); }, 4000); return false; }) .delegate('.dashMenuBtn', 'click', function () { var dd = $(this).parent(); hideDropDowns(dd); dd.toggleClass('open_menu').find('.autoFocus').click(); return false; }); $(document).click(function (e) { if (!$(e.target).parents().filter('.open_menu').length) { $('._active').removeClass('_active'); hideDropDowns(); } }); $('.select2').each(function (ind) { var slct = $(this); slct.select2({ minimumResultsForSearch: Infinity, dropdownParent: slct.parent(), width: '100%', templateResult: selectTemplate, templateSelection: selectTemplate }) }); catchNavBar(); initCalendar(); initTimePicker(); all_dialog_close(); }); function selectTemplate(data, container) { if (data.element) { var el = $(container); if (el.attr('class')) { el.attr('class', el.attr('class').replace(/ _\w+/, '')); el.addClass($(data.element).attr("class")); } } return data.text; } function customizeSelect(pckr) { $(pckr.container).find('select').each(function (ind) { var slct = $(this); slct.wrap($('<div class="calendar_select"/>')); slct.select2({ minimumResultsForSearch: Infinity, dropdownParent: slct.parent(), width: '100%' }) }); } function initTimePicker() { $('.timePicker').each(function (ind) { var tmp = $(this), val = tmp.find('.timePickerVal'); val.on('focus', function () { $(this).parent().addClass('open_menu'); }); }); $('.timeMinus').on('click', function () { var valCell = $(this).closest('.valCell'), inp = valCell.find('input'), tmPckr = valCell.closest('.timePicker'), val = parseInt(inp.val()), new_val = val - (1 * inp.attr('data-step')); inp.val(('0' + (new_val >= (1 * inp.attr('data-min')) ? new_val : inp.attr('data-max'))).substr(-2)); updateTime(tmPckr); return false; }); $('.timePlus').on('click', function () { var valCell = $(this).closest('.valCell'), inp = valCell.find('input'), tmPckr = valCell.closest('.timePicker'), val = parseInt(inp.val()), new_val = val + (1 * inp.attr('data-step')); inp.val(('0' + (new_val <= (1 * inp.attr('data-max')) ? new_val : inp.attr('data-min'))).substr(-2)); updateTime(tmPckr); return false; }); } function updateTime(el) { var inp = el.find('.timePickerVal'); inp.val(inp.attr('data-format').replace('hh', el.find('.valH').val()).replace('mm', el.find('.valM').val())); } function initCalendar() { var clndr = $('#range_calendar'), sngl = $('.singleDate'); if (sngl.length) { sngl .on('show.daterangepicker', function (ev, picker) { }) .on('showCalendar.daterangepicker', function (ev, picker) { customizeSelect(picker); }) .each(function (ind) { $(this).daterangepicker({ "alwaysShowCalendars": false, "singleDatePicker": true, "showDropdowns": true, "parentEl": $(this).parent(), "startDate": "14/02/2017", "endDate": "20/02/2017", "locale": { "format": "DD/MM/YYYY", "separator": " - ", "applyLabel": "Apply", "cancelLabel": "Cancel", "fromLabel": "From", "toLabel": "To", "customRangeLabel": "Custom", "weekLabel": "W", "daysOfWeek": [ "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб" ], "monthNames": [ "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" ], "firstDay": 1 } }); }); } if (clndr.length) { clndr .on('showCalendar.daterangepicker', function (ev, picker) { customizeSelect(picker); }) .daterangepicker({ "alwaysShowCalendars": true, "showDropdowns": true, "parentEl": clndr.parent(), "startDate": "14/02/2017", "endDate": "20/02/2017", "dateLimit": 20, "locale": { "format": "DD/MM/YYYY", "separator": " - ", "applyLabel": "Apply", "cancelLabel": "Cancel", "fromLabel": "From", "toLabel": "To", "customRangeLabel": "Custom", "weekLabel": "W", "daysOfWeek": [ "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб" ], "monthNames": [ "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" ], "firstDay": 1 } }); /* clndr.dateRangePicker({ autoClose: false, format: 'YYYY-MM-DD', separator: ' to ', language: 'auto', startOfWeek: 'monday',// or monday getValue: function () { return $(this).val(); }, setValue: function (s) { if (!$(this).attr('readonly') && !$(this).is(':disabled') && s != $(this).val()) { $(this).val(s); } }, startDate: false, endDate: false, time: { enabled: false }, minDays: 0, maxDays: 0, showShortcuts: false, shortcuts: { //'prev-days': [1,3,5,7], //'next-days': [3,5,7], //'prev' : ['week','month','year'], //'next' : ['week','month','year'] }, customShortcuts: [], inline: true, container: clndr.parent(), alwaysOpen: true, singleDate: false, lookBehind: true, batchMode: false, duration: 200, stickyMonths: true, dayDivAttrs: [], dayTdAttrs: [], applyBtnClass: '', singleMonth: 'auto', showTopbar: false, swapTime: false, selectForward: false, selectBackward: false, showWeekNumbers: false, // showDateFilter: function (time, date) { // return '<div style="padding:0 5px;">\ // <span style="font-weight:bold">' + date + '</span>\ // <div style="opacity:0.3;">$' + Math.round(Math.random() * 999) + '</div>\ // </div>'; // }, getWeekNumber: function (date) //date will be the first day of a week { return moment(date).format('w'); } });*/ } } function catchNavBar() { var navBarMark = $('.navBarMark'), navBar = $('.navBar'); if (navBarMark.length && navBar.length) { wnd.on('scroll', function () { navBar.css('top', ((navBarMark.offset().top - header.outerHeight() - 30) <= doc.scrollTop()) ? header.outerHeight() : 0); }); } } function hideDropDowns(excl) { $('.open_menu').not(excl).removeClass('open_menu'); } function all_dialog_close() { body_var.on('click', '.ui-widget-overlay', all_dialog_close_gl); } function all_dialog_close_gl() { $(".ui-dialog-content").each(function () { var $this = $(this); if (!$this.parent().hasClass('always_open')) { $this.dialog("close"); } }); } function docScrollTo(pos, speed, callback) { $('html,body').animate({'scrollTop': pos}, speed, function () { if (typeof(callback) == 'function') { callback(); } }); } function runCircle(pager_dot, duration) { var circle_1 = $('.timer_r', pager_dot), circle_2 = $('.timer_l', pager_dot); circle_1.attr('style', ''); circle_2.attr('style', ''); circle_1.snabbt({ fromRotation: [0, 0, Math.PI], rotation: [0, 0, 0], duration: duration, callback: function () { circle_2.snabbt({ fromRotation: [0, 0, Math.PI], rotation: [0, 0, 0], duration: duration, callback: function () { } }) } }); } <file_sep>$(function ($) { initDrop(); }); function initDrop() { var dropZone = $('.dropzone'), maxFileSize = 1024 * 1024 * 1024; // максимальный размер фалйа if (!dropZone.length) return; // Проверка поддержки браузером if (typeof(window.FileReader) == 'undefined') { dropZone.text('Не поддерживается браузером!'); dropZone.addClass('drag_error'); } // Добавляем класс hover при наведении dropZone[0].ondragover = function () { dropZone.addClass('drag_in'); return false; }; // Убираем класс hover dropZone[0].ondragleave = function () { dropZone.removeClass('drag_in'); return false; }; // Обрабатываем событие Drop dropZone[0].ondrop = function (event) { event.preventDefault(); dropZone.removeClass('drag_in'); dropZone.addClass('drop'); var file = event.dataTransfer.files[0]; console.log(file); // Проверяем размер файла if (file.size > maxFileSize) { console.log('Файл слишком большой!'); dropZone.addClass('drag_error'); return false; } $('.uploadTip').before($( '<li class="newUpload">\ <div class="upload_file rmUnit _loading"><span class="btn_red_2 unit_rm_btn rmBtn"></span>\ <div class="mb"><span class="upload_icon"><img src="./img/file_doc.svg"></span></div>\ <div class="upload_name mb">' + file.name + '</div>\ <div class="loading_progress">\ <div class="loading_progress_val loadingProgressVal"></div>\ <div class="loading_progress_text loadingProgressText"></div>\ </div>\ </div>\ </li>')); // Создаем запрос var xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', uploadProgress, false); xhr.onreadystatechange = stateChange; xhr.open('POST', './actions/upload.php'); xhr.setRequestHeader('X-FILE-NAME', file.name); xhr.send(file); }; // Показываем процент загрузки function uploadProgress(event) { var percent = parseInt(event.loaded / event.total * 100); $('.newUpload .loadingProgressVal').css('width', percent + '%'); $('.newUpload .loadingProgressText').text(percent + '%'); if (percent == 100) { $('.newUpload ._loading').removeClass('_loading'); $('.newUpload .loadingProgressVal').removeClass('loadingProgressVal'); $('.newUpload .loadingProgressText').removeClass('loadingProgressText'); $('.newUpload').removeClass('newUpload'); } } // Пост обрабочик function stateChange(event) { if (event.target.readyState == 4) { if (event.target.status == 200) { console.log('Загрузка успешно завершена!'); } else { $('.newUpload').remove(); console.log('Произошла ошибка!'); } } } }
34c63c9359e6a257bf304b2ae92c757be66a3e03
[ "JavaScript" ]
3
JavaScript
naverstay/senat
c3c200ab820b92b7b646b4db46b629ad11e5d339
98a996d19d588d763db66f885dc74de8ffde7c55
refs/heads/master
<repo_name>luimi/emws-server<file_sep>/Gemfile source 'http://rubygems.org' gem 'rails','~>3.0.1' gem 'thin' gem 'devise' gem 'json' gem 'eventmachine' gem 'em-websocket'
9350c6b69bd378a5be30624666e2a2853a1c886b
[ "Ruby" ]
1
Ruby
luimi/emws-server
ed37d52601b09d1d3c0f53531945e19a3e961588
ec36d705f50d130cda75dbff6c787f160d88cf9a
refs/heads/master
<file_sep>using System; namespace MiniS.Areas.Identity.Enums { [Flags] public enum UserLevel { Super = 100000 | Admin, Admin = 10000 | Access | Group, Access = 1000 | Regular, Group = 100 | Regular, Regular = 10 } }<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { ListItem } from '../../../models/list-item'; import { List } from '../../../models/list.model'; import { AccountDataListService } from '../../account-data-list.service'; @Component({ selector: 'app-account-data-list-item-edit', templateUrl: './account-data-list-item-edit.component.html', styleUrls: ['./account-data-list-item-edit.component.sass'] }) export class AccountDataListItemEditComponent implements OnInit { @Input('model') oModel: ListItem = new ListItem() @Input() list: List @Input() parentListItems : Array<ListItem> @Output() close: EventEmitter<any> = new EventEmitter() currentTab: Number = 1 edit: boolean model: ListItem constructor( private listService: AccountDataListService ) { } ngOnInit() { this.edit = this.oModel.showEdit this.model = Object.assign(Object.create(this.oModel), this.oModel) this.model.listId = this.oModel.listId || this.list.id } create() { (this.edit ? this.listService.editListItem(this.list.id, this.model): this.listService.createListItem(this.list.id, this.model)).subscribe(r => this.cancel()) } cancel() { this.close.emit() } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using MiniS.Areas.Admin.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Models; using MiniS.Areas.Master.Enums; using SignInResult = Microsoft.AspNetCore.Identity.SignInResult; using MiniS.Areas.Master.Controllers; using MiniS.Areas.Identity.Services; using MiniS.Areas.Data.Models; using MiniS.Helpers; namespace MiniS.Areas.Identity.Controllers { [Route("api/{account}/security/{parentId:long}/user")] [Authorize] public class AccountUserController : GroupableController<AccountUser, Folder, AccountUserService> { public AccountUserController(AccountUserService service, AuthorizationService authService) : base(service, authService) { } protected override Access _access => Access.User; [HttpPost("login")] [AllowAnonymous] public async Task<ActionResult<AccountUser>> OnPostAsync([FromBody] Login login) { var user = await _service.Login(login); if (_service.Fails()) { if (_service.NotFound) return NotFound(_service.ModelState); else return BadRequest(_service.ModelState); } return user; } [HttpGet("existsby/email/{email?}/{current?}")] [AllowAnonymous] public async Task<ActionResult<bool>> ExistsByEmail(string email = null, string current = null) { return await _service.ExistsByEmail(email, current); } [HttpGet("existsby/userName/{userName?}/{current?}")] [AllowAnonymous] public async Task<ActionResult<bool>> ExistsByUserName(string userName = null, string current = null) { return await _service.ExistsByUserName(userName, current); } } }<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { GroupEditComponent } from './components/group-edit.component'; import { FormsModule } from '@angular/forms'; import { EditModalModule } from 'src/app/master/components/edit-modal/edit-modal.module'; import { ListitemModule } from '../../data/listitem/listitem.module'; import { IconModule } from 'src/app/master/components/icon/icon.module'; import { ContextMenuModule } from 'src/app/widgets/ngx-contextmenu/ngx-contextmenu'; import { DatatableModule } from 'src/app/widgets/datatable/datatable.module'; import { TreeviewControlModule } from 'src/app/master/components/treeview-control/treeview-control.module'; import { InfoFormControlModule } from 'src/app/master/components/form-control/info-form-control/info-form-control.module'; import { TreeviewFolderableModule } from 'src/app/master/components/treeview-template/treeview-folderable.module'; import { GroupItemComponent } from './components/group-item.component'; import { GroupDisplayPageComponent } from './components/group-display-page.component'; import { GroupComponent } from './components/group.component'; import { LoaderModule } from 'src/app/master/components/loader/loader.module'; import { EntityItemModule } from 'src/app/master/components/entity-item/entity-item.module'; import { RouterModule } from '@angular/router'; import { DisplayViewModule } from 'src/app/master/components/display-view/display-view.module'; import { GroupTreeviewComponent } from './components/group-treeview.component'; import { GroupFormControlComponent } from './components/group-form-control.component'; import { Folder2Module } from '../folder/folder.module'; import { GroupService } from './state/group.service'; @NgModule({ declarations: [GroupEditComponent,GroupFormControlComponent, GroupItemComponent, GroupDisplayPageComponent, GroupComponent, GroupTreeviewComponent], imports: [ CommonModule, FormsModule, EditModalModule, InfoFormControlModule, TreeviewFolderableModule, IconModule, ContextMenuModule.forRoot(), TreeviewControlModule, DatatableModule, RouterModule, LoaderModule, Folder2Module, EntityItemModule, DisplayViewModule, LoaderModule ], exports: [GroupEditComponent, GroupFormControlComponent], providers: [GroupService] }) export class GroupModule { } <file_sep>export enum Right { None = 0, Read = 10, Create = 20, Modify = 30, Delete = 40, Admin = 50 } <file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using MiniS.Areas.Admin.Models; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Controllers; using MiniS.Areas.Master.Enums; namespace MiniS.Areas.Data.Controllers { [Route("api/{account}/data/{type}/{parentId:long}/Folder")] [Authorize] [Account] public class FolderController : GroupableController<Folder, Folder, FolderService> { protected override Access _access => Access.Folder; private Table type; public FolderController(FolderService service, AuthorizationService authService) : base(service, authService) { if (Enum.TryParse(_service.GetRouteValues().GetValueOrDefault("type").ToString(), true, out Table type)) _service.SetType(type); else _service.LogWarning(1, "type must not be none"); } } }<file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MiniS.Areas.Master.Models; using Newtonsoft.Json; namespace MiniS.Areas.Data.Models { public class FieldAttribute : Parentable<Form> { [Column (TypeName = "smallInt")] public int Order { get; set; } = 0; public long FieldId { get; set; } public Field Field { get; set; } public long StepperId { get; set; } public Stepper Stepper { get; set; } public FieldAttributeOptions Options { get; set; } } public class FieldAttributeConfiguration : ParentableConfiguration<FieldAttribute,Form> { public override void Configure (EntityTypeBuilder<FieldAttribute> builder) { base.Configure (builder); builder.Property (fa => fa.Options).HasConversion (new ValueConverter<FieldAttributeOptions, string> ( v => JsonConvert.SerializeObject (v), v => JsonConvert.DeserializeObject<FieldAttributeOptions> (v) )); } } public class FieldAttributeOptions { public TextFieldAttributeOptions Text { get; set; } public IntegerFieldAttributeOptions Integer { get; set; } public DecimalFieldAttributeOptions Decimal { get; set; } public SelectFieldAttributeOptions Select { get; set; } public MultiSelectFieldAttributeOptions MultiSelect { get; set; } } public abstract class BaseFieldAttributeOptions { public string Placeholder { get; set; } public bool Required { get; set; } public bool Hidden { get; set; } public bool ReadOnly { get; set; } } public class TextFieldAttributeOptions : BaseFieldAttributeOptions, IValidatableObject { public string Default { get; set; } public int? MinLength { get; set; } public int? MaxLength { get; set; } public Regex Regex { get; set; } public Mask Mask { get; set; } public virtual IEnumerable<ValidationResult> Validate (ValidationContext validationContext) { if ((MinLength != null || MaxLength != null) && MaxLength < MinLength) { yield return new ValidationResult ( $"the minimum length must be less tha the maximum length", new [] { "MinLength" }); } } } public class IntegerFieldAttributeOptions : TextFieldAttributeOptions, IValidatableObject { public new int? Default { get; set; } public int? Max { get; set; } public int? Min { get; set; } public override IEnumerable<ValidationResult> Validate (ValidationContext validationContext) { base.Validate (validationContext); if ((Min != null || Max != null) && Max < Min) { yield return new ValidationResult ( $"the minimum value must be less than the maximum value", new [] { "Min" }); } } } public class DecimalFieldAttributeOptions : IntegerFieldAttributeOptions { public new decimal? Default { get; set; } public new decimal? Max { get; set; } public new decimal? Min { get; set; } } public class SelectFieldAttributeOptions : BaseFieldAttributeOptions { public int Default { get; set; } } public class MultiSelectFieldAttributeOptions : BaseFieldAttributeOptions { public int[] Default { get; set; } } public class Mask { public string Content { get; set; } public string Prefix { get; set; } public string Suffix { get; set; } public bool DropSpecialCharacter { get; set; } public bool ShowMask { get; set; } public bool ClearIfNotMatch { get; set; } } public class Regex { public string Value { get; set; } public string Message { get; set; } } /* public string Placeholder { get; set; } public object DefaultValue { get; set; } public Mask Mask { get; set; } public bool Required { get; set; } public bool Hidden { get; set; } public bool ReadOnly { get; set; } public decimal? Min { get; set; } public decimal? Max { get; set; } public int? MinLength { get; set; } public int? MaxLength { get; set; } public Regex Regex { get; set; } */ }<file_sep>using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.AspNetCore.Mvc; using MiniS.Areas.Master.Controllers; using MiniS.Areas.Master.Enums; namespace MiniS.Areas.Master.Models { public abstract class Identificable: Trackable, IIdentificable { public virtual long Id { get; set; } [StringLength(100, ErrorMessage = "name-message-length", MinimumLength = 2)] public string Name { get; set; } [Column(TypeName = "text")] public string Description { get; set; } [NotMapped] public bool Updated { get; set; } = true; [NotMapped] public bool Created { get; set; } = true; public Table Table { get => (Table)Enum.Parse(typeof(Table), this.GetType().Name); } } public interface IIdentificable: ITrackable { long Id { get; set; } string Name { get; set; } string Description { get; set; } public Table Table { get; } } public abstract class IdentificableConfiguration<T> : TrackableConfiguration<T> where T : Identificable { } }<file_sep>import { FolderableService } from './folderable.service' import { IParentable } from '../base-model/parentable.model' import { IAccountable } from '../base-model/accountable.model' import { OnInit, Input, EventEmitter, Output } from '@angular/core' import { Observable } from 'rxjs' import { TreeviewItem } from 'src/app/widgets/ngx-treeview' import { Injector } from '@angular/core' import { GroupService } from 'src/app/account/security/group/state/group.service' import { Table } from 'src/app/enums/table.enum' import { FactoryService } from './factory.service' export abstract class FolderableEditComponent<Model extends IParentable<Parent>, Parent extends IAccountable> implements OnInit { protected type: Table protected service: FolderableService<any> constructor( protected injector: Injector ) { } @Input() parent: Parent @Input('model') oModel: Model = {} as Model @Input() dependant: boolean = false @Output() close: EventEmitter<any> = new EventEmitter() public items: Observable<TreeviewItem[]> public model: Model protected factoryService: FactoryService @Input() isEdit: boolean = false created: boolean ngOnInit() { this.factoryService = new FactoryService(this.injector) //this.model = new Group().clone(this.oModel) this.service = this.factoryService.get(this.type) this.service.updateParentId(this.parent.id) this.model.parent = this.parent } create() { (this.isEdit ? this.service.update(this.model.id, this.model) : this.service.add(this.model) ).subscribe(r => this.close.emit() ); } }<file_sep>import { Component, Input, Output, EventEmitter, forwardRef, TemplateRef, OnInit } from "@angular/core"; import { TreeviewItem, TreeviewHelper } from "src/app/widgets/ngx-treeview"; import { ITrackable } from "../../base-model/trackable.model"; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms"; import { isNil, castArray } from "lodash"; import { Table } from 'src/app/enums/table.enum'; import { IIdentificable } from '../../base-model/identificable.model'; export interface TreeviewContext { items: TreeviewItem[], onSelect: (s: ITrackable[]) => void, multi: boolean, loading: boolean } @Component({ selector: "app-treeview-control", templateUrl: "./treeview-control.component.html", styleUrls: ["./treeview-control.component.sass"], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TreeviewControlComponent), multi: true } ] }) export class TreeviewControlComponent implements ControlValueAccessor, OnInit { constructor() { } ngOnInit(): void { } get treeviewContext() { return { items: this.items, onSelect: this.onSelect.bind(this), multi: this.multi, loading: this.loading } } public selected: Array<ITrackable> = []; public mShow: boolean = false; @Input() loading: boolean @Input() items: Array<TreeviewItem>; @Input() zIndex: number = 200; @Input() multi: boolean = false @Input() placeholder: string = "Select you choice" @Input("icon") icon: string = "list"; @Input() public treeviewTemplate: TemplateRef<TreeviewContext> // public treeviewContext: TreeviewContext @Output() selectedChange: EventEmitter<any> = new EventEmitter(); public onSelect(selected: IIdentificable[]) { this.selected = selected; this.onChange(selected); this.onTouch(selected); } onChange: any = () => { }; onTouch: any = () => { }; writeValue(selected: Array<any>) { this.selectedChange.emit(selected); this.onSelect(selected) } registerOnChange(fn: any) { this.onChange = fn; } registerOnTouched(fn: any) { this.onTouch = fn; } } <file_sep>import { Component, OnInit, Output, EventEmitter, Input, AfterContentInit, Renderer2, ElementRef, OnDestroy } from '@angular/core'; @Component({ selector: 'app-edit-modal', templateUrl: './edit-modal.component.html', styleUrls: ['./edit-modal.component.sass'] }) export class EditModalComponent implements OnInit, AfterContentInit, OnDestroy { ngOnDestroy(): void { this.renderer.removeClass(this.ele.nativeElement, "show") } ngAfterContentInit(): void { this.renderer.addClass(this.ele.nativeElement, "show") } constructor(private renderer: Renderer2, private ele: ElementRef) { } @Output() public close: EventEmitter<any> = new EventEmitter<any>() @Input() public killScroll: boolean = false @Input() public hide: boolean = false @Input() public modalSize: 'modal-lg'|'modal-sm'| 'modal-md' = 'modal-lg' @Input('close-text') closeText: string = "Cancel" ngOnInit() { } } <file_sep>import { Field } from './field'; export class Db extends Groupable <Folder>{ public fields: Array<Field> = [] public showFields: boolean = false public showForm: boolean = false public fieldProcessing: boolean = false } <file_sep>/* using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using MiniS.Areas.Admin.Models; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Repositories; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; namespace MiniS.Areas.Data.Controllers { [Route ("api/{account}/data/{formId}/fieldAttribute")] [Authorize] [Account] public class DatabaseFieldAttributeController : ControllerBase { private readonly FormRepository _formRepo; private readonly DatabaseFieldRepository _FieldRepo; public AuthorizationService _authService { get; } public DatabaseFieldAttributeRepository _FieldAttrRepo { get; } public DatabaseRepository _dbRepo { get; } public StepperRepository _stepperRepo { get; } public AppDbContext _dbContext { get; } public DatabaseFieldAttributeController (AuthorizationService authService, DatabaseFieldAttributeRepository FieldAttrRepo, FormRepository formRepo, DatabaseFieldRepository FieldRepo, DatabaseRepository dbRepo, StepperRepository stepperRepo, AppDbContext dbContext) { _authService = authService; _FieldAttrRepo = FieldAttrRepo; _formRepo = formRepo; _FieldRepo = FieldRepo; _dbRepo = dbRepo; _stepperRepo = stepperRepo; _dbContext = dbContext; } [HttpGet] public async Task<ActionResult<List<FieldAttribute>>> GetAllAsync (long formId) { if (_authService.AuthorizePermission (HttpContext, new Tuple<Access, Right> (Access.DatabaseFieldAttribute, Right.Read)).Fails ()) return Forbid (_authService.GetMessage ()); long accountId = _authService.GetAccountId (); Form form = await _formRepo.GetForm (formId, accountId); if (_authService.AuthorizeResource (HttpContext, form).Fails ()) return Forbid (_authService.GetMessage ()); return await _FieldAttrRepo.GetFieldAttributes (formId, accountId); } [HttpGet ("{fieldAttributeId}", Name = "GetFieldAttribute")] public async Task<ActionResult<FieldAttribute>> GetAsync (long formId, long fieldAttributeId) { if (_authService.AuthorizePermission (HttpContext, new Tuple<Access, Right> (Access.DatabaseFieldAttribute, Right.Read)).Fails ()) return Forbid (_authService.GetMessage ()); long accountId = _authService.GetAccountId (); Form form = await _formRepo.GetForm (formId, accountId); if (form == null) return NotFound (); if (_authService.AuthorizeResource (HttpContext, form).Fails ()) return Forbid (_authService.GetMessage ()); FieldAttribute fieldAttribute = await _FieldAttrRepo.GetFieldAttribute (fieldAttributeId, accountId); if (fieldAttribute == null) return NotFound (); return fieldAttribute; } [HttpPost ("/post")] public string test ([FromBody] object array) { return array.GetType ().Name; } [HttpPost ()] public async Task<ActionResult<bool>> CreateAsync (long formId, FieldAttribute model) { if (_authService.AuthorizePermission (HttpContext, new Tuple<Access, Right> (Access.DatabaseFieldAttribute, Right.Create)).Fails ()) return Forbid (_authService.GetMessage ()); long accountId = _authService.GetAccountId (); FieldAttribute fieldAttribute = new FieldAttribute (); fieldAttribute.Field = await _FieldRepo.GetField (model.FieldId, accountId); if (fieldAttribute.Field == null) return NotFound (new { Message = "no associated field found" }); fieldAttribute.Form = await _formRepo.GetForm (formId, accountId); if (fieldAttribute.Form == null) return NotFound (new { Message = "No associated form found" }); if (_authService.AuthorizeResource (HttpContext, fieldAttribute.Form).Fails ()) return Forbid (_authService.GetMessage ()); fieldAttribute.Stepper = await _stepperRepo.GetStepper (model.StepperId, accountId); if (fieldAttribute.Stepper == null) return NotFound (new { Message = "no associated Stepper found" }); // Get the existing database fields await _FieldAttrRepo.GetFieldAttributes (formId, accountId); // Check if the name already exits if (_FieldAttrRepo.Exists (model)) return BadRequest (new { Message = "label already exists" }); if (_FieldAttrRepo.FieldHasAttribute (model)) return BadRequest (new { Message = "There is already a field attribute assosiated with this field" }); model = await _FieldAttrRepo.CreateFieldAttribute (fieldAttribute, model, _authService.GetAuthUser ()); return CreatedAtRoute ("GetFieldAttribute", new { fieldAttributeId = model.Id, formId = formId, account = _authService.GetAccount ().NormalizedName }, model); } [HttpPut ("{id}")] public async Task<ActionResult<FieldAttribute>> updateAsync (long formId, long id, FieldAttribute model) { if (id != model.Id) return BadRequest (new { Message = "mismatch field Attribute ID" }); if (_authService.AuthorizePermission (HttpContext, new Tuple<Access, Right> (Access.DatabaseFieldAttribute, Right.Modify)).Fails ()) return Forbid (_authService.GetMessage ()); long accountId = _authService.GetAccountId (); FieldAttribute fieldAttribute = await _FieldAttrRepo.GetFieldAttribute (id, accountId); model.Form = await _formRepo.GetForm (fieldAttribute.FormId, accountId); if (_authService.AuthorizeResource (HttpContext, model.Form).Fails ()) return Forbid (_authService.GetMessage ()); await _FieldAttrRepo.GetFieldAttributes (formId, accountId); // Check if the name already exits if (_FieldAttrRepo.Exists (model)) return BadRequest (new { Message = "label already exists" }); return await _FieldAttrRepo.UpdateFieldAttribute (model, _authService.GetAuthUser ()); } [HttpDelete ("{id}")] public async Task<IActionResult> DeleteAsync (long formId, long id) { if (_authService.AuthorizePermission (HttpContext, new Tuple<Access, Right> (Access.DatabaseFieldAttribute, Right.Delete)).Fails ()) return Forbid (_authService.GetMessage ()); long accountId = _authService.GetAccountId (); Form form = await _formRepo.GetForm (formId, accountId); if (form == null) return NotFound (new { Message = "asoociated form not found" }); if (_authService.AuthorizeResource (HttpContext, form).Fails ()) return Forbid (_authService.GetMessage ()); FieldAttribute fieldAttribute = await _FieldAttrRepo.GetFieldAttribute (id, accountId); if (fieldAttribute == null) return NotFound (new { Message = "Field Attribute not found" }); // ToDo Verify the is no data inserted at this column field await _FieldAttrRepo.Delete (fieldAttribute); return NoContent (); } } } */<file_sep>import { Component, OnInit, Input, HostBinding } from '@angular/core'; @Component({ selector: 'app-loader, [app-loader]', templateUrl: './loader.component.html', styleUrls: ['./loader.component.sass'] }) export class LoaderComponent implements OnInit { constructor() { } @Input() spinner: boolean = false @Input() size: 'small'| 'medium' | 'large' | 'x-large' = 'medium' @Input('app-loader') loading = false ngOnInit() { } } <file_sep>/* using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.Logging; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Repositories; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Enums; using MiniS.Areas.Services; namespace MiniS.Areas.Data.Services { public class DatabaseDataService : BaseService { private readonly DatabaseDataRepository _databaseDataRepository; private readonly ILogger<DatabaseDataService> _logger; private DatabaseData _model; private List<DatabaseData> _models; public DatabaseDataService (DatabaseDataRepository databaseDataRepository, ILogger<DatabaseDataService> logger) { _databaseDataRepository = databaseDataRepository; _logger = logger; } public DatabaseData GetDatabaseData () { return _model; } public List<DatabaseData> GetAllDatabaseData () { return _models; } public async Task<int> FetchDatabaseData (long id, long accountId) { try { _model = await _databaseDataRepository.GetDatabaseData (id, accountId); } catch (Exception ex) { _logger.LogError (LoggingEvents.GetItemError, ex, "Get DatabaseData ({id})", id); return LoggingEvents.GetItemError; } if (_model == null) { _logger.LogWarning (LoggingEvents.GetItemNotFound, "Get DatabaseData ({Id}) NOT FOUND", id); return LoggingEvents.GetItemNotFound; } _logger.LogInformation (LoggingEvents.GetItem, "Get Database Data ({id})", id); if (!_model.AllGroup) { try { _model.Groups = _databaseDataRepository.GetGroups (_model); } catch (Exception ex) { _logger.LogError (LoggingEvents.GetItemError, ex, "Get DatabaseData ({id}) Groups", id); return LoggingEvents.GetItemError; } if (_model.Groups.Count == 0) { _logger.LogWarning (LoggingEvents.GetItemsEmpty, "Get DatabaseData ({Id}) Groups is Empty", id); return LoggingEvents.GetItemsEmpty; } } _logger.LogInformation (LoggingEvents.GetItem, "Get Groups of of database data"); return LoggingEvents.GetItem; } public int FetchAllDatabaseData (long id, AccountUser authUser) { try { _models = _databaseDataRepository.GetAllDatabaseData (id, authUser).Result; } catch (Exception ex) { _logger.LogError (LoggingEvents.GetItemsError, ex, "Get DatabaseData ({id})", id); return LoggingEvents.GetItemsError; } try { foreach (DatabaseData databaseData in _models) { databaseData.Groups = _databaseDataRepository.GetGroups (databaseData); } } catch (Exception ex) { _logger.LogError (LoggingEvents.GetItemError, ex, "Get All DatabaseData ({id}) Groups Error", id); return LoggingEvents.GetItemsError; } /* If user has not all group access filter by group access if (!authUser.UserLevel.HasFlag (Identity.Enums.UserLevel.Group)) _models = _models.Where (d => d.AllGroup || d.Groups.Any (d1 => authUser.Groups.Contains (d1))).ToList (); _logger.LogInformation (LoggingEvents.GetItems, "Get all database data suucceeded"); return LoggingEvents.GetItems; } public static object GetPropValue (object src, string propName) { return src.GetType ().GetProperty (propName).GetValue (src, null); } public void Validate () { } } } */<file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { AuthenticationStore } from './authentication.store'; import { Login } from './authentication.model'; import { Observable } from 'rxjs'; import { User } from '../../user/state/user.model'; @Injectable({ providedIn: 'root' }) export class AuthenticationService { constructor(private authenticationStore: AuthenticationStore, private http: HttpClient) { } public login(account: string, model: Login): Observable<User> { return this.http.post<User>(`api/${account}/security/auth/login`, model) } public logout(account: string): Observable<null> { return this.http.post<null>(`api/${account}/security/auth/logout`, null) } public getAuthUser(account: string): Observable<User> { return this.http.get<User>(`api/${account}/security/auth/user`) } } <file_sep>/* import { Component, forwardRef, ViewChild, Input, OnInit } from "@angular/core"; import { ControlValueAccessor, NG_VALUE_ACCESSOR, FormControl, NG_VALIDATORS, NgModel, Validator } from "@angular/forms"; import { FieldAttribute, FieldType } from "../../../models/field"; @Component({ selector: "app-account-data-db-data-number-control", templateUrl: "./account-data-db-data-number-control.component.html", styleUrls: ["./account-data-db-data-number-control.component.sass"], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => AccountDataDbDataNumberControlComponent), multi: true }, { provide: NG_VALIDATORS, useExisting: forwardRef(() => AccountDataDbDataNumberControlComponent), multi: true } ] }) export class AccountDataDbDataNumberControlComponent implements ControlValueAccessor, Validator, OnInit { public ngOnInit(): void { this.integer = this.fieldAttribute.field.column == FieldType.Integer; this.type = this.integer ? "integer" : "decimal"; } @ViewChild("ngModel", { static: false }) ngModel: NgModel; @Input() fieldAttribute: FieldAttribute; private _model: any; public integer: boolean; public type: "integer" | "decimal"; public set model(value: any) { this._model = value; this.onChange(value); this.onTouched(); } public get model() { return this._model; } constructor() {} onChange: any = () => {}; onTouched: any = () => {}; registerOnChange(fn) { this.onChange = fn; } writeValue(value) { this.model = value; } registerOnTouched(fn) { this.onTouched = fn; } validate(_: FormControl) { return this.ngModel.valid ? null : { textControl: { valid: false } }; } } */<file_sep>using System.Collections.Generic; using MiniS.Areas.Master.Models; namespace MiniS.Helpers { public class IDEqualityComparer<T>: IEqualityComparer<T> where T :Identificable { public bool Equals(T b1, T b2) { return b1.Id == b2.Id; } public int GetHashCode(T obj) { return this.GetHashCode(); } } }<file_sep>// using MiniS.Areas.Data.Models; // using MiniS.Areas.Identity.Data; // using MiniS.Areas.Identity.Models; // using MiniS.Areas.Master; // using MiniS.Areas.Master.Enums; // namespace MiniS.Areas.Data.Repositories // { // public class ListRepository: AccountGroupRepository<List,long, Folder> // { // public ListRepository(AppDbContext dbContext) : base(dbContext) // { // } // protected override Table _table => Table.List; // } // }<file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore.Metadata.Builders; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Data.Models { public class Database : Groupable<Folder> { public List<Form> Forms { get; set; } = new List<Form> (); public List<Field> Fields { get; set; } = new List<Field> (); [InverseProperty("Parent")] public List<DatabaseData> DatabaseData { get; set; } } public class DatabaseConfiguration : GroupableConfiguration<Database,Folder> { } }<file_sep>import { Directive, Input } from '@angular/core'; import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms'; @Directive({ selector: '[numeric]', providers: [{ provide: NG_VALIDATORS, useExisting: NumericValidatorDirective, multi: true }] }) export class NumericValidatorDirective implements Validator { @Input('numeric') integer: boolean; validate(control: AbstractControl): { [key: string]: any } | null { if (!control.value) return null if(isNaN(control.value)) return { numeric: true } return !this.integer || (this.integer && Number.isInteger(parseFloat(control.value)))? null : { numeric: true } } } <file_sep>using System; using MiniS.Areas.Master.Enums; namespace MiniS.Areas.Master.Models { public abstract class Parentable<P> : Accountable, IParentable<P> { public virtual long ParentId { get; set; } public P Parent { get; set; } public Table ParentTable { get => (Table)Enum.Parse(typeof(Table), ParentType.Name); } public System.Type ParentType { get => typeof(P); } } public interface IParentable<P> : IAccountable { long ParentId { get; set; } P Parent { get; set; } Table ParentTable { get; } System.Type ParentType { get; } } public abstract class ParentableConfiguration<T, P> : IdentificableConfiguration<T> where T : Parentable<P> where P : Accountable { } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { AccountDataFolderableService } from '../account-data-folder/account-data-folder.service'; import { Table } from 'src/app/enums/table.enum'; import { ParentableService } from '../../account.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-account-data-db', templateUrl: './account-data-db.component.html', styleUrls: ['./account-data-db.component.scss'] }) export class AccountDataDbComponent { constructor(private folderService: AccountDataFolderableService, private accountService: ParentableService, private router: Router) { } Table = Table public type:Table = Table.Database /* ngOnInit() { this.folderService.getFolderTreeView(-1, Table.Database).subscribe() this.account = this.accountService.account.normalizedName } public account: string get items(): TreeviewItem[] { return this.folderService.folderTreeView } goToFolder(id:number) { this.router.navigateByUrl(`${this.account}/data/database/folder/${id}`) // this.isListItem = false } = get parents(): Folder[] { return this.folderService.parents } get children(): TreeviewItem { return this.folderService.children } */ } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { AccountUser } from './account-user.model'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AccountUserService { constructor(private http:HttpClient) { } accountUsers : AccountUser[] = [] getUsers(account:string):Observable<AccountUser[]>{ return this.http.get<AccountUser[]>(`api/${account}/security/-1/user`).pipe(tap( resp => this.accountUsers = resp )) } createUser(account:string, body: AccountUser):Observable<AccountUser>{ return this.http.post<AccountUser>(`api/${account}/security/user`, body ).pipe( tap(resp=>this.accountUsers.push(resp)) ) } update(account: string, body: AccountUser): Observable<AccountUser> { return this.http.put<AccountUser>(`api/${account}/security/user/${body.id}`, body).pipe( tap(resp => this.accountUsers[this.accountUsers.findIndex(g => g.id == body.id)] = resp) ) } delete(account: string, id: string): Observable<{}> { return this.http.delete(`api/${account}/security/user/${id}`).pipe( tap(resp => this.accountUsers.splice(this.accountUsers.findIndex(a => a.id == id), 1)) ) } } <file_sep>import { Injectable } from '@angular/core'; import { ID } from '@datorama/akita'; import { HttpClient } from '@angular/common/http'; import { FieldAttributeStore } from './field-attribute.store'; import { FieldAttribute } from './field-attribute.model'; import { tap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class FieldAttributeService { constructor(private fieldAttributeStore: FieldAttributeStore, private http: HttpClient) { } get() { return this.http.get<FieldAttribute[]>('https://api.com').pipe(tap(entities => { this.fieldAttributeStore.set(entities); })); } add(fieldAttribute: FieldAttribute) { this.fieldAttributeStore.add(fieldAttribute); } update(id, fieldAttribute: Partial<FieldAttribute>) { this.fieldAttributeStore.update(id, fieldAttribute); } remove(id: ID) { this.fieldAttributeStore.remove(id); } } <file_sep>using System; using System.Globalization; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SpaServices.AngularCli; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Identity.Services; using MiniS.Areas.Master; [assembly: ApiController] [assembly: ApiConventionType(typeof(DefaultApiConventions))] namespace MiniS { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("fr-FR"), new CultureInfo("es-ES") }; services.AddLocalization(options => options.ResourcesPath = "Resources"); services.Configure<RequestLocalizationOptions>(options => { options.DefaultRequestCulture = new RequestCulture("en-US"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); services.AddControllers() .AddNewtonsoftJson(o => o.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore) .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResource)); }); // services.AddHttpContextAccessor(); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); services.AddIdentity<AccountUser, Role>() .AddEntityFrameworkStores<AppDbContext>(); //cookies configurations services.ConfigureApplicationCookie(options => { options.AccessDeniedPath = "/Identity/Account/AccessDenied"; options.Cookie.Name = "MiniSCookies"; options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromMinutes(60); options.LoginPath = "/42647d41-090c-4275-b2ba-8f88a94bbf48"; // ReturnUrlParameter requires //using Microsoft.AspNetCore.Authentication.Cookies; options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter; options.SlidingExpiration = true; }); //services.AddTransient<AuthorizationService> (); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped(typeof(IParentableStore<,>), typeof(ParentableStore<,>)); // services.AddTransient<DatabaseRepository> (); services.AddTransient<DatabaseService>(); // services.AddTransient<FolderRepository> (); services.AddTransient<FolderService>(); //services.AddTransient<DatabaseFieldRepository> (); // services.AddTransient<FormRepository> (); services.AddTransient<FormService>(); //services.AddTransient<StepperRepository> (); // services.AddTransient<ListRepository> (); services.AddTransient<ListService>(); // services.AddTransient<ListItemRepository> (); services.AddTransient<ListItemService>(); services.AddTransient<AuthorizationService>(); services.AddTransient<FieldService>(); // services.AddTransient<FieldRepository> (); services.AddTransient<FormService>(); // services.AddTransient<FormRepository> (); services.AddTransient<GroupService>(); services.AddTransient<AccountUserService>(); //services.AddTransient<DatabaseFieldAttributeRepository> (); // services.AddDbContext<AppDbContext>(options => // options.UseSqlite(Configuration.GetConnectionString("AppContext"))); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } loggerFactory.AddFile("Logs/myapp-{Date}.txt"); // Localization & Globalization var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("fr-FR"), new CultureInfo("es-ES") }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), // Formatting numbers, dates, etc. SupportedCultures = supportedCultures, // UI strings that we have localized. SupportedUICultures = supportedCultures }); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSpaStaticFiles(); // Use Cookie Policy Middleware to conform to EU General Data // Protection Regulation (GDPR) regulations. // app.UseCookiePolicy(); app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{area:exists}/{controller}/{action=Index}/{id?}"); }); /* app.UseMvc(routes => { routes.MapRoute( name: "area", template: "{area:exists}/{controller}/{action=Index}/{id?}" ); routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); */ app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); } } }<file_sep>import { Injectable } from '@angular/core'; import { ParentableService } from 'src/app/account/account.service'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { Stepper } from '../models/stepper'; import { FieldAttribute, FieldType } from '../models/field'; @Injectable({ providedIn: 'root' }) export class AccountDataDbFormService { public constructor( private accountService: ParentableService, private http: HttpClient ) { } public loading = false public account: string = this.accountService.account.normalizedName editStepper(parent: Number, model: Stepper):Observable<Stepper> { return this.http.put<Stepper>(`api/${this.account}/data/${parent}/stepper/${model.id}`, model) } getSteppers(parent: Number): Observable<Array<Stepper>> { return this.http.get<Array<Stepper>>(`api/${this.account}/data/${parent}/stepper`) //.pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } createStepper(parent: Number, model: Stepper): Observable<Stepper> { return this.http.post<Stepper>(`api/${this.account}/data/${parent}/stepper`, model) //.pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } deleteStepper(parent: Number, id: number): Observable<Stepper> { return this.http.delete<Stepper>(`api/${this.account}/data/${parent}/stepper/${id}`) //.pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } updateStepperOrder(parent: number, ids: Array<number>): Observable<Array<Stepper>> { return this.http.post<Array<Stepper>>(`api/${this.account}/data/${parent}/stepper/order`, ids) //.pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } createFieldAttribute(parent: Number, model: FieldAttribute): Observable<FieldAttribute> { return this.http.post<FieldAttribute>(`api/${this.account}/data/${parent}/fieldAttribute`, model) //.pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } updateFieldAttribute(parent: Number, id: number, model: FieldAttribute): Observable<FieldAttribute> { return this.http.put<FieldAttribute>(`api/${this.account}/data/${parent}/fieldAttribute/${id}`, model) //.pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } deleteFieldAttribute(parent: Number, id: number): Observable<FieldAttribute> { return this.http.delete<FieldAttribute>(`api/${this.account}/data/${parent}/fieldAttribute/${id}`) //.pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } getFieldAttributes(parent: Number): Observable<Array<FieldAttribute>> { return this.http.get<Array<FieldAttribute>>(`api/${this.account}/data/${parent}/fieldAttribute`) //.pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } } <file_sep>import { Component, OnInit, Output, Input, EventEmitter, ViewChild, ElementRef } from '@angular/core'; import { Db } from '../../models/db'; import { Field, FieldType } from '../../models/field'; import { AccountDataDbService } from '../../account-data-db.service'; import { ScrollToService } from 'src/app/widgets/ngx-scroll-to/scroll-to.service'; import { AccountDataFolderableService } from '../../../account-data-folder/account-data-folder.service'; import { Table } from 'src/app/enums/table.enum'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { ViewportScroller } from '@angular/common'; @Component({ selector: 'app-account-data-field-edit', templateUrl: './account-data-field-edit.component.html', styleUrls: ['./account-data-field-edit.component.sass'], providers: [AccountDataFolderableService] }) export class AccountDataFieldEditComponent implements OnInit { constructor( private dbService: AccountDataDbService, private _scrollToService: ScrollToService, private folderService: AccountDataFolderableService, private vpScroller : ViewportScroller ) { } @ViewChild('modal', {static: true}) modal: ElementRef @Input('database') model: Db @Output() close: EventEmitter<any> = new EventEmitter() currentTab: Number = 1 edit: boolean = false FieldType = FieldType ngOnInit() { this.dbService.getFields(this.model.id).subscribe(r=>this.model.fields = r) this.folderService.getFolderTreeView(0, Table.List).subscribe() } add(type: FieldType) { this.model.fieldProcessing = true let ndb = new Field(type) this.model.fields.push(ndb) /* let modal = this.modal.nativeElement let scrollTop = modal.scrollTop const h = setInterval(()=>{ scrollTop-=25 if(scrollTop<0){ modal.scrollTop = 0 clearInterval(h) } modal.scrollTop = scrollTop }, 10) */ } deleteField(index: number, field: Field) { this.model.fields.splice(index, 1) } get hasField(): boolean { return this.model.fields.length > 0 } cancel() { this.close.emit() } isStandard(field:Field): boolean { return [FieldType.TextArea, FieldType.Integer, FieldType.Text, FieldType.Decimal].some(t=>t==field.type) } get loading():boolean{ return false return this.dbService.loading || this.folderService.isLoading } /* isNumeric(field: Field, integer: boolean = false) { const a = integer ? [FieldType.Integer] : [FieldType.Integer, FieldType.Decimal] return a.indexOf(field.type) > -1 } */ get dListVisible(): boolean { return this.model.fields.some(f=> (f.type==FieldType.DependentList || f.type ==FieldType.List)) } get listTreeview(): Array<TreeviewItem>{ return this.folderService.folderTreeView } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { EntityItemComponent } from './entity-item.component'; import { IconModule } from '../icon/icon.module'; import { DatatableModule } from 'src/app/widgets/datatable/datatable.module'; import { ContextMenuModule } from 'src/app/widgets/ngx-contextmenu/ngx-contextmenu'; import { RouterModule } from '@angular/router'; @NgModule({ declarations: [EntityItemComponent], imports: [ CommonModule, IconModule, DatatableModule, ContextMenuModule.forRoot(), RouterModule, DatatableModule ], exports:[EntityItemComponent] }) export class EntityItemModule { } <file_sep>import { Component, Input, Output, EventEmitter } from '@angular/core'; import { FieldAttribute } from '../../../models/field'; import { getObjectCopy } from 'src/app/helpers/object.helper'; import { Form } from '../../../models/form'; import { AccountDataDbFormService } from '../../account-data-db-form.service'; @Component({ selector: 'app-account-data-db-form-field-attribute-card', templateUrl: './account-data-db-form-field-attribute-card.component.html', styleUrls: ['./account-data-db-form-field-attribute-card.component.sass'] }) export class AccountDataDbFormFieldAttributeCardComponent { constructor( private formService: AccountDataDbFormService ) { } @Input() public model: FieldAttribute @Input() public modelCopy: FieldAttribute @Input() public form: Form @Input() public isValid: boolean @Input() public ngValue: any @Output() public edit: EventEmitter<FieldAttribute> = new EventEmitter<FieldAttribute>() @Output() public remove: EventEmitter<any> = new EventEmitter<any>() @Output() public modelCopyChange: EventEmitter<FieldAttribute> = new EventEmitter<FieldAttribute>() deleteField(force: boolean = false) { if (force) this.formService.deleteFieldAttribute(this.form.id, this.model.id).subscribe(r => this.remove.emit()) this.model.created ? this.model.updated = true : this.remove.emit() } updateField() { const observable = this.model.created ? this.formService.updateFieldAttribute(this.form.id, this.model.id, this.modelCopy) : this.formService.createFieldAttribute(this.form.id, this.modelCopy) observable.subscribe(r => { this.edit.emit(r) }) } public editField(){ this.model.updated = false this.modelCopyChange.emit(getObjectCopy(this.model)) } } <file_sep>using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Controllers; namespace MiniS.Areas.Data.Controllers { [Route("api/{account}/data/{parentId}/listitem")] public class ListItemController : GroupableController<ListItem,List, ListItemService > { /* protected override ListItemService _service => new ListItemService (_authService.GetAuthUser ()); protected override ListService _parentService => new ListService (_authService.GetAuthUser ()); */ const string PLISTITEMSQUERY = "pListItems"; public ListItemController(ListItemService service, AuthorizationService authService) : base(service, authService) { } protected override Access _access => Access.ListItem; [HttpGet] public override async Task<ActionResult<List<ListItem>>> GetAllAsync(long parentId) { // return forbidden response if the user has not read rights on databases if (!_service.HasRight(Right.Read)) return Forbid(); var models = await _service.FetchModels(parentId, Request.Query[PLISTITEMSQUERY].ToArray()); // fetch all Database data the authenticated has access and return a 404 response if an error occurs if (_service.Fails()) return BadRequest(_service.ModelState); // return all Database data the authenticated has access return models; } } }<file_sep>import { Injectable } from '@angular/core'; import { Store, StoreConfig, ActiveState } from '@datorama/akita'; import { AccountUser } from '../../account-security-user/account-user.model'; export interface AuthenticationState extends ActiveState<AccountUser> { active: AccountUser; } export function createInitialState(): AuthenticationState { return { active: null }; } @Injectable({ providedIn: 'root' }) @StoreConfig({ name: 'authentication' }) export class AuthenticationStore extends Store<AuthenticationState> { constructor() { super(createInitialState()); } } <file_sep>import { Account } from 'src/app/admin/admin-account/account'; import { UserLevel } from './user-level.enum'; import { UserGroup } from './user-group.model' import { Group } from '../group/state/group.model'; export class AccountUser { constructor( public id: string, public userName: string, public email: string, public password: string, public confirmPassword: string, public account: Account, public accountId: number = 0, public accesses: any = {}, public userLevel: UserLevel = UserLevel.Regular, public groups: Group[] = null, public showEdit: boolean = false, public userGroup: UserGroup[] = [], public firstName?: string, public lastName?: string, ) { } } <file_sep>import { Component, OnInit, Input, EventEmitter, Output } from "@angular/core"; import { FieldAttribute, Field } from "../../../models/field"; import { Form, NgModel } from "@angular/forms"; import { getObjectCopy } from "src/app/helpers/object.helper"; @Component({ selector: "[app-account-data-db-form-field-attribute-text]", templateUrl: "./account-data-db-form-field-attribute-text.component.html", styleUrls: ["./account-data-db-form-field-attribute-text.component.sass"] }) export class AccountDataDbFormFieldAttributeTextComponent implements OnInit { constructor() {} @Input() public model: FieldAttribute; @Input() public field: Array<Field> = []; @Input() public form: Form; @Input() public listDefaults: any; @Output() public edit: EventEmitter<FieldAttribute> = new EventEmitter< FieldAttribute >(); @Output() public remove: EventEmitter<any> = new EventEmitter<any>(); public modelCopy: FieldAttribute; ngOnInit() { this.modelCopy = getObjectCopy(this.model); this.maskPatternMessage = "must be valid pattern"; } public maskPattern: string; public updateRegex(event:string, ngModel:NgModel){ if(ngModel.valid) this.modelCopy.options.text.regex.value = event } public maskPatternMessage: string; regexMessage(message: string, actual: string, required: string) { message = message || "regular expression error" return message.replace(":value", actual).replace(":regex", required); } } <file_sep>import { Table } from 'src/app/enums/table.enum'; import { Groupable } from 'src/app/master/base-model/groupable.model'; import { List } from '../../list/state/list.model'; export class Listitem extends Groupable<List>{ public static create(obj){ return Object.assign(new Listitem(), obj) } set parentListitem(value:Listitem){ this._parentListitem = value this.parentListItemId = value.id } get parentListitem(){ return this._parentListitem } public parentListId: number = null public dependant: boolean = false private _parentListitem: Listitem public listId: number public parentListItemId : number }<file_sep>using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using MiniS.Areas.Admin.Models; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Controllers; namespace MiniS.Areas.Data.Controllers { [Route("api/{account}/data/{parentId}/database")] [Authorize] [Account] public class DatabaseController : GroupableController<Database, Folder, DatabaseService> { public DatabaseController(DatabaseService service, AuthorizationService authService) : base(service, authService) { } protected override Access _access => Access.Database; } }<file_sep>// export interface Field { // id: number | string; // } export function createField(params: Partial<Field>) { return { } as Field; } import { Database } from '../../database/state/database.model'; import { List } from '../../list/state/list.model'; import { Parentable } from 'src/app/master/base-model/parentable.model'; export class Field extends Parentable<Database> { private _relatedField: Field; constructor(public type?: FieldType, ) { super() } public static get(obj: Field): Field { let klass = new Field(obj.type) klass.list = obj.list klass.name = obj.name klass.relatedField = obj.relatedField return klass } public guid: string private _list: List = null; public get relatedField() { return this._relatedField; } public set relatedField(value: Field) { this._relatedField = value if (value) this.relatedFieldId = value.id; } public listParentId: number public get list() { return this._list } public set list(value: List) { this._list = value; if (value) { this.listId = value.id; this.listParentId = value.parentId; } } public listId: number; public relatedFieldId: number; public inputType: string; public updated: boolean = false public created: boolean = false } export enum FieldType { bigint, numeric, varchar, text, date, datetime, time, //advanced type list, dependentList, Address } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ListitemEditComponent } from './components/listitem-edit.component'; import { ContextMenuModule } from 'src/app/widgets/ngx-contextmenu/ngx-contextmenu'; import { IconModule } from 'src/app/master/components/icon/icon.module'; import { EditModalModule } from 'src/app/master/components/edit-modal/edit-modal.module'; import { InfoFormControlModule } from 'src/app/master/components/form-control/info-form-control/info-form-control.module'; import { FormsModule } from '@angular/forms'; import { DatatableModule } from 'src/app/widgets/datatable/datatable.module'; import { NgSelectModule } from 'src/app/widgets/ng-select/ng-select.module'; import { ListitemItemComponent } from './components/listitem-item.component'; import { ListitemDisplayPageComponent } from './components/listitem-display-page.component'; import { GroupModule } from '../../security/group/group.module'; @NgModule({ declarations: [ListitemEditComponent, ListitemItemComponent, ListitemDisplayPageComponent], imports: [ CommonModule, FormsModule, EditModalModule, InfoFormControlModule, IconModule, ContextMenuModule.forRoot({ useBootstrap4: true, }), DatatableModule, NgSelectModule ], exports: [ListitemEditComponent, ListitemItemComponent] }) export class ListitemModule { } <file_sep> export const contextmenu = [ { icon: "folder-plus", action: (item) => item.entity.showAdd = true, text: "Create Folder", visible: (item)=> true }, { icon: "folder-edit", action: (item) => item.entity.showEdit = true, text: "Edit Folder", visible: (item)=> true }, { icon: "folder-remove", action: (item) => item.entity.showEdit = true, text: "Delete Folder", visible: (item)=> true } , { icon: "folder-pound", action: (item) => item.entity.showEdit = true, text: "Rename Folder", visible: (item)=> true } ]<file_sep>import { Component, OnInit } from '@angular/core'; import { Table } from 'src/app/enums/table.enum'; import { Observable } from 'rxjs'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { ListService } from '../state/list.service'; @Component({ selector: 'app-list', templateUrl: './list.component.html', styleUrls: ['./list.component.sass'] }) export class ListComponent implements OnInit { constructor( private listService: ListService ) { } public type : Table = Table.List ngOnInit() { this.listService.getTreeview().subscribe() } get loading(){ return this.listService.store.loading$ } get treeview(): Observable<TreeviewItem[]>{ return this.listService.treeview$ } } <file_sep>export function isBetween (value: number, min:number, max: number){ return value >= min && value <= max }<file_sep> using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using MiniS.Areas.Identity.Data; [assembly: HostingStartup(typeof(MiniS.Areas.Identity.IdentityHostingStartup))] namespace MiniS.Areas.Identity { public class IdentityHostingStartup : IHostingStartup { public void Configure(IWebHostBuilder builder) { builder.ConfigureServices((context, services) => { services.AddDbContext<AppDbContext>(options => options.UseSqlite( context.Configuration.GetConnectionString("AppContext")) ); }); } } }<file_sep>using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using MiniS.Areas.Identity.Models; using MiniS.Areas.Models; using MiniS.Areas.Master.Enums; namespace MiniS.Areas.Identity.Data { public static class AppDbContextExtension { public static AppDbContext UpdateManyToMany<T> ( this AppDbContext db, IEnumerable<T> newItems, IEnumerable<T> currentItems = null) where T : class { if (currentItems != null) db.Set<T> ().RemoveRange (currentItems); db.Set<T> ().AddRange (newItems); return db; } public static async Task<List<Group>> GetGroups (this AppDbContext db, long id, Table table) { List<EntityGroup> entityGroups = await db.EntityGroups.Where (eg => eg.EntityId == id && eg.Table == table) .Include (eg => eg.Group).ToListAsync (); return entityGroups.Select (eg => eg.Group).ToList (); } public static Task<List<EntityGroup>> GetEntityGroups (this AppDbContext db, long id, Table table) { return db.EntityGroups.Where (eg => eg.EntityId == id && eg.Table == table).ToListAsync (); } public static IQueryable Queryable (this AppDbContext db, Table table) { switch (table) { case Table.Database: return db.Databases; case Table.Folder: return db.Folders; case Table.Group: return db.Groups; case Table.User: return db.AccountUsers; default: return null; } } } }<file_sep>import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core'; import { AccountUserService } from '../account-user.service'; import { AccountUser } from '../account-user.model'; import { AccountSecurityAccessTemplateService } from '../../account-security-access-template/account-security-access-template.service'; import { Observable } from 'rxjs'; import { AccessTemplate } from '../../account-security-access-template/access-template'; import { Access, accessByModule } from '../../account-security-access-template/access.enum'; import { Right } from '../../account-security-access-template/right.enum'; import { UserLevel } from '../user-level.enum'; import { GroupService } from '../../group/state/group.service'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; @Component({ selector: 'app-account-security-edit-user', templateUrl: './account-security-edit-user.component.html', styleUrls: ['./account-security-edit-user.component.scss'] }) export class AccountSecurityEditUserComponent implements OnInit { constructor( private accountUserService: AccountUserService, private accountAccessTemplateService: AccountSecurityAccessTemplateService, private groupService: GroupService ) { } public access = Object.keys(Access).filter(a => isNaN(Number(a))) public right = Object.keys(Right).filter(r => isNaN(Number(r))) public Right = Right public UserLevel = UserLevel public accessByModule = accessByModule() @Output() close: EventEmitter<any> = new EventEmitter() @Input() account: string @Input() model: AccountUser = new AccountUser(null, null,null, null, null, null) public accessTemplates: Observable<AccessTemplate[]> public selectedAccess: AccessTemplate public currentTab: number = 1 public groups: Observable<TreeviewItem[]> ngOnInit() { this.model.accesses = this.model.accesses || {} this.access.forEach(a => { if (!this.model.accesses.hasOwnProperty(a)) this.model.accesses[a] = 0 }) this.model.groups = this.model.groups || this.model.userGroup.map(u => u.group) this.accessTemplates = this.accountAccessTemplateService.getAll(this.account) this.groups = this.groupService.getTreeview() } create() { let action = this.model.showEdit ? this.accountUserService.update : this.accountUserService.createUser action.call(this.accountUserService, this.account, this.model).subscribe() this.cancel() } copyTemplate() { Object.assign(this.model.accesses, this.selectedAccess.accesses) } cancel() { this.close.emit() } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ListEditComponent } from './components/list-edit.component'; import { ListDisplayPageComponent } from './components/list-display-page.component'; import { ListComponent } from './components/list.component'; import { ListItemComponent } from './components/list-item.component'; import { IconModule } from 'src/app/master/components/icon/icon.module'; import { TreeviewFolderableModule } from 'src/app/master/components/treeview-template/treeview-folderable.module'; import { FormsModule } from '@angular/forms'; import { EditModalModule } from 'src/app/master/components/edit-modal/edit-modal.module'; import { InfoFormControlModule } from 'src/app/master/components/form-control/info-form-control/info-form-control.module'; import { RouterModule } from '@angular/router'; import { ContextMenuModule } from 'src/app/widgets/ngx-contextmenu/ngx-contextmenu'; import { FolderModule } from '../folder/folder.module'; import { TreeviewControlModule } from 'src/app/master/components/treeview-control/treeview-control.module'; import { DatatableModule } from 'src/app/widgets/datatable/datatable.module'; import { ListitemModule } from '../listitem/listitem.module'; import { GroupModule } from '../../security/group/group.module'; @NgModule({ declarations: [ListEditComponent, ListDisplayPageComponent, ListComponent, ListItemComponent], imports: [ CommonModule, FormsModule, EditModalModule, InfoFormControlModule, TreeviewFolderableModule, FolderModule, ListitemModule, IconModule, RouterModule, ContextMenuModule.forRoot({ useBootstrap4: true, }), TreeviewControlModule, DatatableModule, ] }) export class ListModule { } <file_sep>// using System; // using System.Linq; // using System.Threading.Tasks; // using Microsoft.EntityFrameworkCore; // using MiniS.Areas.Identity.Data; // using MiniS.Areas.Identity.Models; // using MiniS.Areas.Master.Enums; // using MiniS.Areas.Master.Models; // using Unity; // namespace MiniS.Areas.Master // { // public interface IAccountRepository<Model, ParentId, Parent> // { // IQueryable<Model> GetModel(long Id); // IQueryable<Model> GetModels(ParentId parentId, params object[] param); // Task<Model> SaveUpdateAsync(Model model); // Task<Model> SaveCreateAsync(Model model); // Task Delete(Model model); // void SetAuthUser(AccountUser authUser); // //void SetTable (Table table); // } // public abstract class AccountRepository<Model, ParentId, Parent> : IAccountRepository<Model, ParentId> // where Model : AccountableTrackable<ParentId, Parent> // { // protected readonly AppDbContext _dbContext; // protected AccountUser _authUser; // protected abstract Table _table { get; } // public AccountRepository(AppDbContext dbContext) // { // _dbContext = dbContext; // } // public void SetAuthUser(AccountUser authUser) // { // _authUser = authUser; // } // /* public void SetTable (Table table) { // _table = table; // } */ // public virtual async Task<Model> SaveUpdateAsync(Model model) // { // _dbContext.Update<Model>(model); // await _dbContext.SaveChangesAsync(_authUser); // return model; // } // public virtual async Task<Model> SaveCreateAsync(Model model) // { // await _dbContext.Set<Model>().AddAsync(model); // await _dbContext.SaveChangesAsync(_authUser); // return model; // } // public virtual IQueryable<Model> GetModel(long id) // { // return _dbContext.Set<Model>().Where(Model => Model.Id == id && Model.AccountId == _authUser.AccountId); // } // public virtual IQueryable<Model> GetModels(ParentId parentId, params object[] param) // { // return _dbContext.Set<Model>().Where<Model>(Model => Model.AccountId == _authUser.AccountId) // .Where(Model => parentId.Equals(Model.ParentId)); // } // public Task Delete(Model model) // { // _dbContext.Set<Model>().Remove(model); // _dbContext.SaveChangesAsync(); // return Task.CompletedTask; // } // public virtual IQueryable<Model> GetParent(IIdentificable model) // { // Parent parent = (Parent) model; // return _dbContext.Set<Parent>().Where(Model => Model.Id == id && Model.AccountId == _authUser.AccountId); // } // } // }<file_sep> using System; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Master.Extensions{ public static class EntityExtensions { public static object GetPropertyValue(this Entity entity, string prop) { try{ return entity.GetType().GetProperty(prop).GetValue(entity, null); }catch(Exception e){ return null; } } public static Type GetPropertyType(this Entity entity, string prop) { try{ return entity.GetType().GetProperty(prop).PropertyType; }catch(Exception e){ return null; } } } } <file_sep>using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using MiniS.Areas.Data.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; using MiniS; using MiniS.Areas.Services; namespace MiniS.Areas.Data.Services { public class ListService : AccountGroupService<List, Folder> { public ListService( AppDbContext dbContext, ILogger<ListService> logger, IStringLocalizer<SharedResource> localizer, IParentableStore<List, Folder> parentableStore, FolderService folderService) : base(dbContext, logger, localizer, parentableStore, folderService) { } protected override Table _table => Table.List; protected override List PopulateCreateModel(List model) { base.PopulateCreateModel(model); MODEL.Dependant = model.Dependant; MODEL.ParentListId = model.ParentListId; return MODEL; } } }<file_sep>import { Stepper } from '../stepper/stepper.model'; import { Form } from '../form/form.model'; import { Field } from '../../../account-data-db/models/field'; export function createFieldAttribute(params: Partial<FieldAttribute>) { return { } as FieldAttribute; } export class FieldAttribute { public get stepper(): Stepper { return this._stepper; } public set stepper(value: Stepper) { this._stepper = value; this.stepperId = value.id; } constructor( public name?: string, public field?: Field, public form?: Form, private _stepper?: Stepper, public order: number = 0 ) { this.fieldId = this.field.id; this.formId = this.form.id; this.stepperId = _stepper.id; } public stepperId: number = 0; public fieldId: number; public id: number = 0; public formId: number = 0; public options: FieldAttributeOptions = { text: { mask: {}, regex: {} }, integer: { mask: {}, regex: {} }, decimal: { mask: {}, regex: {} }, select: {}, multiSelect: {} }; public updated: boolean = false; public created: boolean = false; } export interface Mask { content?: string; prefix?: string; suffix?: string; dropSpecialCharacter?: boolean; showMask?: boolean; clearIfNotMatch?: boolean; } export interface Regex { value?: string; message?: string; } export interface FieldAttributeOptions { text?: TextOptions; integer?: NumberOptions; decimal?: NumberOptions; select?: SelectOptions; multiSelect?: MultiSelectOptions; } export interface TextOptions extends NumberTextOptions { default?: string; } export interface NumberOptions extends NumberTextOptions { min?: number; max?: number; } export interface SelectOptions extends BaseOptions { default?: number; } export interface MultiSelectOptions extends BaseOptions { default?: Array<number>; } export interface NumberTextOptions extends BaseOptions { maxLength?: number; minlength?: number; regex?: Regex; mask?: Mask; } export interface BaseOptions { default?: any; placeholder?: string; required?: boolean; hidden?: boolean; readonly?: boolean; } <file_sep>import { Component, OnInit, Input, TemplateRef } from '@angular/core'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { icon } from 'src/app/master/components/icon/icon.component'; import { DisplayView } from 'src/app/master/components/display-view/nav-view.component'; import { contextmenu } from './folder-contextmenu.const'; import { VOLUMEICON, SERVERICON } from 'src/app/master/components/icon/icon.const'; import { Table } from 'src/app/enums/table.enum'; @Component({ selector: 'app-folder-item', templateUrl: './folder-item.component.html', styleUrls: ['./folder-item.component.sass'] }) export class FolderItemComponent implements OnInit { constructor() { } @Input() public item: TreeviewItem @Input() vColumns: any[] = [] @Input() type: Table @Input() public template: TemplateRef<{ item: TreeviewItem }>; @Input() display: DisplayView = DisplayView.inline public DisplayView = DisplayView private _contextmenu = contextmenu @Input() public set contextmenu(v: any) { this._contextmenu = this._contextmenu.concat(v) } public get contextmenu() { return this._contextmenu } @Input() public link: string public folderIcon: icon = { name: 'folder', class: 'yellow-text text-darken-1' } ngOnInit(): void { this.item.pEntity && this.item.pEntity.id || (this.folderIcon = VOLUMEICON) this.item.entity && this.item.entity.id || (this.folderIcon = SERVERICON) } } <file_sep>import { Injectable } from '@angular/core'; import { ID } from '@datorama/akita'; import { HttpClient } from '@angular/common/http'; import { FormStore } from './form.store'; import { Form } from './form.model'; import { tap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class FormService { constructor(private formStore: FormStore, private http: HttpClient) { } get() { return this.http.get<Form[]>('https://api.com').pipe(tap(entities => { this.formStore.set(entities); })); } add(form: Form) { this.formStore.add(form); } update(id, form: Partial<Form>) { this.formStore.update(id, form); } remove(id: ID) { this.formStore.remove(id); } } <file_sep>/* using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using MiniS.Areas.Admin.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Models; using MiniS.Areas.Master.Enums; using SignInResult = Microsoft.AspNetCore.Identity.SignInResult; namespace MiniS.Areas.Identity.Controllers { [Authorize] public class AccountUserControllerc: ControllerBase { public AccountUserControllerc( UserManager<AccountUser> userManager, SignInManager<AccountUser> signInManager, AppDbContext dbContext, ILogger<AccountUserController> logger) { _userManager = userManager; _signInManager = signInManager; _dbContext = dbContext; _logger = logger; } [HttpGet("{username}", Name = "GetUserAccount")] [Account] public async Task<ActionResult<AccountUser>> GetUser(string username) { AccountUser accountUser = await _userManager.FindByNameAsync(username); if (accountUser == null) return NotFound(); accountUser.Groups = await _dbContext.GetGroups(accountUser.Id, Table.User); return accountUser; } [HttpGet] [Account] public ActionResult<List<AccountUser>> GetUsers() { Account account = (Account)HttpContext.Items["account"]; return _dbContext.AccountUsers.Where(at => at.AccountId == account.Id) .Select( delegate(AccountUser au){ au.Groups = _dbContext.GetGroups(au.Id, Table.User).Result; return au; }).ToList(); } [HttpPost("login")] [AllowAnonymous] public async Task<ActionResult<AccountUser>> OnPostAsync([FromBody] Login login) { // Try to find the account user by userName AccountUser user = await _userManager.FindByNameAsync(login.UserName); // Otherwise try to find the account user by email if (user == null) user = await _userManager.FindByEmailAsync(login.UserName); // If no account user was found return a 404 not found response if (user == null) return NotFound(new { Message = user }); // Sign in SignInResult result = await _signInManager.PasswordSignInAsync(user, login.Password, login.RememberMe, user.LockoutEnabled); // If sign in succeed, retur a 200 response withe signed in account user if (result.Succeeded) { _logger.LogInformation("User logged in."); return user; } // If user is lockedout return a 400 response if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); ModelState.AddModelError(string.Empty, "you are lockedout"); return BadRequest(ModelState); } // otherwise if other errors occured return 400 error response else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return BadRequest(ModelState); } } [HttpPost] [Account] public async Task<ActionResult<AccountUser>> CreateUser(AccountUser user) { // Update trackable account user properties user.Account = (Account)HttpContext.Items["account"]; AccountUser authUser = (AccountUser)HttpContext.Items["authUser"]; user.LastUpdatedBy = user.CreatedBy = authUser.UserName; user.LastUpdatedAt = user.CreatedAt = DateTime.Now; _dbContext.UpdateManyToMany(user.Groups.Select(g => new EntityGroup() { EntityId = user.Id, GroupId = g.Id, Table = Table.User }).ToList(), new List<EntityGroup>()); // Create and save the account User IdentityResult result = await _userManager.CreateAsync(user, user.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); return CreatedAtRoute("GetUserAccount", new { username = user.UserName }, user); } foreach (IdentityError error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return BadRequest(ModelState); } [HttpPut("{id}")] [Account] public async Task<ActionResult<AccountUser>> UpdateAsync(int id, AccountUser user) { // Check route Data id and body id matching if (id != user.Id) return BadRequest(new { Message = "mismatch user ID" }); // fetch the account user AccountUser trackedUser = await _userManager.FindByEmailAsync(user.Email); // Return not found in case no user was retrieved if (trackedUser == null) return NotFound(new { Message = "user not found" }); // #endregionupdate user properties trackedUser.UserName = user.UserName; trackedUser.Email = user.Email; trackedUser.FirstName = user.FirstName; trackedUser.LastName = user.LastName; trackedUser.UserLevel = user.UserLevel; trackedUser.Accesses = user.Accesses; trackedUser.Groups = user.Groups; // Update user trackable properties trackedUser.Account = (Account)HttpContext.Items["account"]; AccountUser authUser = (AccountUser)HttpContext.Items["authUser"]; trackedUser.LastUpdatedBy = authUser.UserName; trackedUser.LastUpdatedAt = DateTime.Now; // Includes UserGroup related data to use it for removing existing manytomany relationship // Upadate user-group many-to-many relationship _dbContext.UpdateManyToMany(user.Groups.Select(g => new EntityGroup() { EntityId = user.Id, GroupId = g.Id, Table = Table.User, AccountId = user.AccountId }).ToList<EntityGroup>(), await _dbContext.GetEntityGroups(trackedUser.Id, Table.User)); // update User Password if(user.Password != null) trackedUser.PasswordHash = _userManager.PasswordHasher.HashPassword(trackedUser, user.Password); // Save Changes IdentityResult result = await _userManager.UpdateAsync(trackedUser); if (result.Succeeded) { _logger.LogInformation("User updated."); return trackedUser; } foreach (IdentityError error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return BadRequest(ModelState); } private readonly UserManager<AccountUser> _userManager; private readonly ILogger<AccountUserController> _logger; private readonly SignInManager<AccountUser> _signInManager; public AppDbContext _dbContext { get; } } } */<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DatatableFilterComponent } from './components/datatable-filter.component'; import { DatatableFiltersComponent } from './components/datatable-filters.component'; import { DatatableComponent } from './components/datatable.component'; import { NgxPaginationModule } from '../ngx-pagination/ngx-pagination.module'; import { SortPipe } from './pipes/sort.pipe'; import { NgSelectModule } from '../ng-select/ng-select.module'; import { FormsModule } from '@angular/forms'; import { DatatableTdComponent } from './components/datatable-td.component'; import { IconModule } from 'src/app/master/components/icon/icon.module'; import { DatatableService } from './datatable.service'; import { DndModule } from '../ngx-darg-drop/dnd.module'; @NgModule({ declarations: [DatatableFilterComponent, DatatableFiltersComponent, DatatableComponent, SortPipe, DatatableTdComponent], imports: [ CommonModule, NgxPaginationModule, NgSelectModule, FormsModule, IconModule, DndModule, ], exports: [DatatableComponent, DatatableTdComponent], providers: [{ provide: DatatableService }] }) export class DatatableModule { } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FieldItemComponent } from './components/field-item.component'; import { FieldEditComponent } from './components/field-edit.component'; import { FormsModule } from '@angular/forms'; import { NgSelectModule } from 'src/app/widgets/ng-select/ng-select.module'; import { EditModalModule } from 'src/app/master/components/edit-modal/edit-modal.module'; import { IconModule } from 'src/app/master/components/icon/icon.module'; import { InfoFormControlModule } from 'src/app/master/components/form-control/info-form-control/info-form-control.module'; import { TreeviewControlModule } from 'src/app/master/components/treeview-control/treeview-control.module'; import { LoaderModule } from 'src/app/master/components/loader/loader.module'; import { NgbDropdownModule } from 'src/app/widgets/ngb-dropdown/dropdown.module'; @NgModule({ declarations: [FieldItemComponent, FieldEditComponent], imports: [ CommonModule, FormsModule, NgSelectModule, EditModalModule, IconModule, InfoFormControlModule, TreeviewControlModule, LoaderModule, NgbDropdownModule ], exports: [FieldEditComponent] }) export class FieldModule { } <file_sep>import { Directive, ElementRef, Renderer2, OnInit } from '@angular/core'; @Directive({ selector: '[appInputField]' }) export class InputFieldDirective implements OnInit { ngOnInit(): void { let element = this.el.nativeElement let label = element.previousSibling || element.nextSibling let onfocus= function(){ console.log("focus") if ( element.value.length > 0 || (element === document.activeElement && (element.type || element.href)) || !!element.placeholder ) { this.renderer.addClass(label, 'active'); } else if (element.validity) { element.validity.badInput === true ? this.renderer.addClass(label, 'active') : this.renderer.removeClass(label, 'active'); } else { this.renderer.removeClass(label,'active'); } } label.onfocus = onfocus.bind(this) element.onfocusout = onfocus.bind(this) } constructor(private el: ElementRef, private renderer: Renderer2) { } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AccountDataDbFormStepperTabComponent } from './account-data-db-form-stepper-tab.component'; describe('AccountDataDbFormStepperComponent', () => { let component: AccountDataDbFormStepperTabComponent; let fixture: ComponentFixture<AccountDataDbFormStepperTabComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AccountDataDbFormStepperTabComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AccountDataDbFormStepperTabComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HttpResponse } from '@angular/common/http'; import { Observable, of, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { AccountService } from '../account/account.service'; import { Router } from '@angular/router'; /** Pass untouched request through to the next request handler. */ @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private accountService: AccountService, private router: Router) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).pipe(catchError(e => { // if http 404 response with the url containing the specific uuid we know that the user is not authenticated // we set the authUser to null in order for the auth guard work well if (e.url && e.url.indexOf('42647d41-090c-4275-b2ba-8f88a94bbf48') > -1) { // unasign the authUser as The user is not authenticated this.accountService.authUser = null return throwError('you are not authenticated, sign in to access the page') } return throwError(e) } )) } }<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AccountSecurityAuthLoginComponent } from './account-security-auth-login.component'; describe('AccountLoginComponent', () => { let component: AccountSecurityAuthLoginComponent; let fixture: ComponentFixture<AccountSecurityAuthLoginComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AccountSecurityAuthLoginComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AccountSecurityAuthLoginComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { Observable } from 'rxjs'; import { Table } from 'src/app/enums/table.enum'; import { DatabaseService } from '../../state/database.service'; @Component({ selector: 'app-database', templateUrl: './database.component.html', styleUrls: ['./database.component.sass'] }) export class DatabaseComponent implements OnInit { constructor( private databaseService: DatabaseService ) { } public type : Table = Table.Database ngOnInit() { this.databaseService.getTreeview().subscribe() } get loading(){ return this.databaseService.store.loading$ } get treeview(): Observable<TreeviewItem[]>{ return this.databaseService.treeview$ } } <file_sep>import { Component, OnInit, Input, Renderer2 } from '@angular/core'; import { ITrackable } from '../../base-model/trackable.model'; import { ContextMenuComponent } from 'src/app/widgets/context-menu/context-menu.component'; import { icon } from '../icon/icon.component'; import { DisplayView } from '../display-view/nav-view.component'; import { ColDisplay } from 'src/app/widgets/datatable/datatable.interface'; @Component({ selector: 'app-entity-item', templateUrl: './entity-item.component.html', styleUrls: ['./entity-item.component.sass'] }) export class EntityItemComponent implements OnInit { constructor(private renderer: Renderer2) { } ngOnInit() { } public DisplayView = DisplayView @Input() contextmenu: ContextMenuComponent @Input() public item: ITrackable @Input() public display: DisplayView @Input() public link : string @Input() public icon: icon @Input() public vColumns: ColDisplay public onContext(event: Event){ this.renderer.addClass(event.target, 'bold-1') setTimeout(()=>this.renderer.removeClass(event.target,'bold-1'),1000) } } <file_sep> import { TreeviewStore } from './treeview.store'; import { TreeviewItem, TreeItem, TreeviewHelper } from 'src/app/widgets/ngx-treeview'; import { HttpClient } from '@angular/common/http'; import { map, tap, mapTo } from 'rxjs/operators'; import { Folder } from 'src/app/account/data/folder/folder.model'; import { Folder as Folder2 } from 'src/app/account/security/folder/folder.model'; import { ColDisplay } from 'src/app/widgets/datatable/datatable.interface'; import { IParentable } from '../base-model/parentable.model'; import { IAccountable } from '../base-model/accountable.model'; import { Table } from 'src/app/enums/table.enum'; import { Observable, of } from 'rxjs'; export abstract class FolderableService<Model extends IParentable<Folder>> { public store: TreeviewStore<Model> = new TreeviewStore(); protected parentId: Number = 0 protected abstract type: Table public treeview$ = this.store.treeview$ public currentItems$ = this.store.currentItems$ public parentEntity$ = this.store.parentEntity$ public parents$ = this.store.parents$ public columns$ = this.store.columns$ public selected: number[] = [] public currentEdit: string = null public setColumns(cols: ColDisplay[]) { this.store.columns = cols } public rootEntity$ = this.treeview$.pipe(map(t => TreeviewHelper.rootTreeview(t))) protected http: HttpClient public getTreeview(): Observable<TreeviewItem[]> { if (this.getHasCache()) return of(this.store.treeview); this.store.loading = true return this.http.get<TreeItem[]>(this.getUrl('treeview')) .pipe( map((r: TreeItem[]) => r.map(f => new TreeviewItem(f))), tap( r => this.store.set(r, this.selected, this.type), console.log, () => this.store.loading = false ) ) } public getCurrentItems(parentId: number): Observable<TreeviewItem[]> { this.updateParentId(parentId) return this.getTreeview().pipe(tap( r => { this.store.setCurrentItems(parentId) this.store.setCurrentParents(parentId) } )) } protected abstract getUrl(path?: string) updateParentId(parentId: number) { this.parentId = parentId } getHasCache(): boolean { return this.store._cache().value; } add(model: Model) { return this.http.post<Model>(this.getUrl(), model).pipe(tap(model => { this.store.add(model); })) } update(id, model: Partial<Model>) { return this.http.put<Model>(this.getUrl(id), model).pipe(tap(model => { this.store.update(model); })) } addFolder(model: Folder | Folder2) { return this.http.post<Model>(this.getFolderUrl(), model).pipe(tap(model => { this.store.add(model); //this.displayItemsStore.add(model); })) } protected abstract getFolderUrl(path?: string) updateFolder(id, model: Partial<Model>) { return this.http.put<Model>(this.getFolderUrl(id), model).pipe(tap(model => { this.store.update(model); //this.displayItemsStore.update(model); })) } // remove(id: ID) { // this.treview.remove(id); // } } <file_sep>using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using MiniS.Areas.Data.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master; using MiniS.Areas.Master.Enums; using MiniS; using MiniS.Areas.Services; namespace MiniS.Areas.Data.Services { public class FormService : AccountGroupService<Form, Database> { public FormService ( AppDbContext dbContext, ILogger<FormService> logger, IStringLocalizer<SharedResource> localizer, IParentableStore<Form, Database> parentableStore, DatabaseService databaseService) : base (dbContext,logger, localizer, parentableStore, databaseService) { } protected override Table _table => Table.Form; } }<file_sep>import { Directive, HostBinding, Input } from '@angular/core'; import { icon } from './icon.component'; @Directive({ selector: '[appIcon]' }) export class IconDirective { constructor() { } private primaryIcon: string = '' private primaryClass: string = '' @Input() set appIcon(value: string | icon) { if (typeof value === 'string') this.primaryIcon = value else { this.primaryIcon = value.name this.primaryClass = value.class } } @Input('klass') set klass(value: string) { this.primaryClass = value } @HostBinding('class') get class(){ return `fas fa-${this.primaryIcon} ${this.primaryClass}` } } <file_sep>import { trigger, transition, style, query, animateChild, group, animate, state } from '@angular/animations'; export const slideInAnimation = trigger('routeAnimations', [ transition('*=>*', [ style({transform: 'translateY(100%)'}), animate(300) ]), ]);<file_sep> namespace MiniS { public class SharedResource { } } <file_sep>import { BehaviorSubject } from 'rxjs'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { ColDisplay } from 'src/app/widgets/datatable/datatable.interface'; import { remove } from "lodash" import { IIdentificable } from '../base-model/identificable.model'; export class EntityStore { // - We set the initial state in BehaviorSubject's constructor // - Nobody outside the Store should have access to the BehaviorSubject // because it has the write rights // - Writing to state should be handled by specialized Store methods (ex: addTodo, removeTodo, etc) // - Create one BehaviorSubject per store entity, for example if you have TodoGroups // create a new BehaviorSubject for it, as well as the observable$, and getters/setters private readonly _entities = new BehaviorSubject<IIdentificable[]>([]); private readonly _parentEntity = new BehaviorSubject<IIdentificable>(null); private readonly _parents = new BehaviorSubject<TreeviewItem[]>(null); private readonly _columns = new BehaviorSubject<ColDisplay[]>(null); // Expose the observable$ part of the _todos subject (read only stream) readonly entities$ = this._entities.asObservable(); readonly parentEntity$ = this._parentEntity.asObservable(); readonly parents$ = this._parents.asObservable(); readonly columns$ = this._columns.asObservable(); // we'll compose the todos$ observable with map operator to create a stream of only completed todos /* readonly completedTodos$ = this.treeview$.pipe( map(todos => todos.filter(todo => todo.isCompleted)) ) */ // the getter will return the last value emitted in _todos subject public get entities(): IIdentificable[] { return this._entities.getValue(); } // assigning a value to this.todos will push it onto the observable // and down to all of its subsribers (ex: this.todos = []) // assigning a value to this.todos will push it onto the observable // and down to all of its subsribers (ex: this.todos = []) public set entities(val: IIdentificable[]) { this._entities.next(val); } public set parentEntity(val: IIdentificable) { this._parentEntity.next(val); } public get parentEntity(): IIdentificable { return this._parentEntity.getValue(); } public set parents(val: TreeviewItem[]) { this._parents.next(val); } public get parents(): TreeviewItem[] { return this._parents.getValue(); } public set columns(val: ColDisplay[]) { this._columns.next(val); } public get columns(): ColDisplay[] { return this._columns.getValue(); } add(entity: IIdentificable) { // we assaign a new copy of todos by adding a new todo to it // with automatically assigned ID ( don't do this at home, use uuid() ) this.entities = [...this.entities, entity]; } update(entity: IIdentificable) { // we assaign a new copy of todos by adding a new todo to it // with automatically assigned ID ( don't do this at home, use uuid() ) const index = this.entities.findIndex(i => i.id == entity.id) this.entities[index] = entity } remove(id:number) { remove(this.entities, e => e.id == id) /* const parent = TreeviewHelper.findItemInList(this.treeview, entity.parentId, entity.parentTable); parent.children = parent.children.filter(c => c.value != entity.id) this.treeview = [...this.treeview]; */ } /* setCompleted(id: number, isCompleted: boolean) { let todo = this.todos.find(todo => todo.id === id); if (todo) { // we need to make a new copy of todos array, and the todo as well // remember, our state must always remain immutable // otherwise, on push change detection won't work, and won't update its view const index = this.todos.indexOf(todo); this.todos[index] = { ...todo, isCompleted } this.todos = [...this.todos]; } } */ }<file_sep> using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Data.Models { public class Stepper : Parentable<Form> { [Column(TypeName = "smallInt")] public int Order {get; set;} = 0; public List<FieldAttribute> FieldAttributes {get; set;} } public class StepperConfiguration : ParentableConfiguration<Stepper,Form> { } }<file_sep>import { Folder } from 'src/app/account/data/folder/folder.model'; import { Parentable } from 'src/app/master/base-model/parentable.model'; export class Group extends Parentable<Folder> { } <file_sep>import { Pipe, PipeTransform } from '@angular/core'; import { ITrackable } from 'src/app/master/base-model/trackable.model'; import { ColDisplay } from '../datatable.interface'; const sort = function (item1: ITrackable, item2: ITrackable) { if (item1[this.key] > item2[this.key]) return this.sort if (item1[this.key] < item2[this.key]) return -this.sort return 0 } @Pipe({ name: 'sort' }) export class SortPipe implements PipeTransform { transform(value: ITrackable[], args?: ColDisplay[]): any { args.forEach(cd => { if (cd.sort !== 0) value = value.sort(sort.bind(cd)) }) return value } } <file_sep> export enum UserLevel { Regular=10, Group = 100 | Regular, Access=1000 | Regular, Admin=10000 | Group | Access, Super=100000 | Admin, } <file_sep>import { Component, OnInit } from '@angular/core'; import { ListitemService } from '../state/listitem.service'; import { InputType } from 'src/app/enums/input-type.enum'; import { ActivatedRoute } from '@angular/router'; import { Table } from 'src/app/enums/table.enum'; import { Columns } from 'src/app/master/base-model/groupable.model'; @Component({ selector: 'app-listitem-display-page', templateUrl: './listitem-display-page.component.html', styleUrls: ['./listitem-display-page.component.sass'] }) export class ListitemDisplayPageComponent implements OnInit { constructor( private route: ActivatedRoute, private listitemService: ListitemService, ) { } public showDT = false public columns = [...Columns, {key: "parentListItem", display: "parent List", items:[], show: true, sort:0, inputType: InputType.Select}] public ngOnInit() { this.route.params.subscribe(routeParams => { this.listitemService.updateParentId(routeParams.id); this.listitemService.getCurrentItems(routeParams.id).subscribe() // this.listitemService.getParents().subscribe(); }); } public Table = Table get items() { return this.listitemService.currentItems$ } get parent() { return this.listitemService.parentEntity$ } get parents() { return this.listitemService.parents$ } /* get parentsLoading() { return this.listitemService.loader.setParents$ } get displayItemsLoading() { return this.listitemService.loader.set$ } */ } <file_sep>import { Component, OnInit, Input, Output, EventEmitter, HostListener, ViewChild, ElementRef } from '@angular/core'; import { Stepper } from '../../../models/stepper'; import { AccountDataDbFormService } from '../../account-data-db-form.service'; import { Form } from '../../../models/form'; import { NgModel } from '@angular/forms'; import { ToastrService } from 'src/app/widgets/ngx-toastr/public_api'; @Component({ selector: 'app-account-data-db-form-stepper-tab', templateUrl: './account-data-db-form-stepper-tab.component.html', styleUrls: ['./account-data-db-form-stepper-tab.component.sass'] }) export class AccountDataDbFormStepperTabComponent implements OnInit { constructor(private formService: AccountDataDbFormService, private toastrService: ToastrService) { } @Input() model: Stepper @Input() form: Form @Output() add: EventEmitter<Stepper> = new EventEmitter<Stepper>() @Output() select: EventEmitter<Stepper> = new EventEmitter<Stepper>() @Output() delete: EventEmitter<any> = new EventEmitter<any>() @ViewChild('input', { static: true }) input: ElementRef @ViewChild('control', { static: true }) control: NgModel public showDelete: boolean = false @HostListener('click') onClick() { this.select.emit(this.model) } @HostListener('dblclick') onDblClick() { this.model.updated = false this.selectRange() } public ngOnInit() { if (!this.model.created) this.selectRange() } private selectRange() { setTimeout(() => { this.input.nativeElement.focus() this.input.nativeElement.setSelectionRange(0, this.input.nativeElement.value.length) }, 100) } public createStepper() { if (this.control.invalid) this.model.created ? this.model.updated = true : this.delete.emit() else if (!this.model.updated) { const txt = this.model.created ? "updated" : "added" this.model.name = this.input.nativeElement.value; (this.model.created ? this.formService.editStepper(this.form.id, this.model) : this.formService.createStepper(this.form.id, this.model)).subscribe(r => { { this.model = r this.add.emit(r) this.toastrService.success(`the stepper<a>${r.name}</a> was successefully ${txt} in the database`, `Stepper ${txt}`) } }) } } public cancel(event: any) { if (event.relatedTarget.classList.contains('stepper-send')) return this.model.created ? (this.model.updated = true) : this.delete.emit() } public deleteStepper() { this.formService.deleteStepper(this.form.id, this.model.id).subscribe(r => { this.delete.emit() this.showDelete = false this.toastrService.warning(`the stepper<a>${this.model.name}</a> was successefully deleted and updatedto the database`, "Stepper deleted") }) } } <file_sep>import { Injectable } from '@angular/core'; import { AccessTemplate } from './access-template'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { tap, map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AccountSecurityAccessTemplateService { constructor(private http: HttpClient) { } public accessTemplates: Array<AccessTemplate> = [] getAll(account:string): Observable<Array<AccessTemplate>>{ return this.http.get<Array<AccessTemplate>>(`api/${account}/security/access-template`).pipe( map(r=>r), tap( resp=>this.accessTemplates = resp ) ) } create(account:string, body: AccessTemplate): Observable<AccessTemplate> { return this.http.post<AccessTemplate>(`api/${account}/security/access-template`, body).pipe( tap(resp=>this.accessTemplates.push(resp)) ) } update(account: string, body: AccessTemplate): Observable<AccessTemplate> { return this.http.put<AccessTemplate>(`api/${account}/security/access-template/${body.id}`, body).pipe( tap(resp => this.accessTemplates[this.accessTemplates.findIndex(g => g.id == body.id)] = resp) ) } delete(account: string, id: number): Observable<{}> { return this.http.delete(`api/${account}/security/access-template/${id}`).pipe( tap(resp => this.accessTemplates.splice(this.accessTemplates.findIndex(g => g.id == id), 1)) ) } } <file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore.Metadata.Builders; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Data.Models { public class DataAddress : Groupable<DatabaseData> { public long DatabaseId { get; set; } public Database Database { get; set; } public long FieldId { get; set; } public Field Field { get; set; } public long? Country { get; set; } public long? State { get; set; } public long? City { get; set; } public long? Street { get; set; } public string Zone { get; set; } public long? StreetNumber { get; set; } public string Appartment { get; set; } public decimal? Longitude { get; set; } public decimal? Lattitude { get; set; } } public class DataAddressConfiguration : GroupableConfiguration<DataAddress, DatabaseData> { } }<file_sep>import { Component, OnInit } from '@angular/core'; import { Table } from 'src/app/enums/table.enum'; import { GroupService } from '../state/group.service'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { Observable } from 'rxjs'; @Component({ selector: 'app-group', templateUrl: './group.component.html', styleUrls: ['./group.component.sass'] }) export class GroupComponent implements OnInit { constructor( private groupService: GroupService ) { } ngOnInit() { this.groupService.getTreeview().subscribe() } get loading(){ return this.groupService.store.loading$ } get treeview$(): Observable<TreeviewItem[]>{ return this.groupService.treeview$ } } <file_sep>import { Component, OnInit, EventEmitter, Input, Output } from '@angular/core'; import { Database } from '../../state/database.model'; import { DatabaseService } from '../../state/database.service'; import { Folder } from '../../../folder/folder.model'; import { InfoFormControlComponent } from 'src/app/master/components/form-control/info-form-control/info-form-control.component'; import { GroupFormControlComponent } from 'src/app/account/security/group/components/group-form-control.component'; @Component({ selector: 'app-database-edit', templateUrl: './database-edit.component.html', styleUrls: ['./database-edit.component.sass'] }) export class DatabaseEditComponent implements OnInit { constructor(private dbService: DatabaseService) {} @Input() parent: Folder; @Input("model") oModel: Database = new Database(); @Output() close: EventEmitter<any> = new EventEmitter(); public edit: boolean = false; public showFields: boolean = false; public created: boolean = false; public model: Database; public ngOnInit() { this.model = new Database().clone(this.oModel); this.dbService.updateParentId(this.parent.id) this.created = this.edit = this.model.showEdit; } create(info: InfoFormControlComponent, group:GroupFormControlComponent) { (this.edit ? this.dbService.update(this.model.id, this.model) :this.dbService.add(this.model) ).subscribe(r => { this.created = r.showEdit = true; this.oModel = this.model = r; this.showFields = !this.edit; info.infoForm.control.markAsPristine() group.groupForm.control.markAsPristine() }); } } <file_sep> import { ITrackable } from 'src/app/master/base-model/trackable.model'; import { TreeviewItem } from '../ngx-treeview'; export interface DatatableItemTemplateContext { item: TreeviewItem, columns: any[] } <file_sep>import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; import { Observable, of, concat, merge, combineLatest, forkJoin } from 'rxjs'; import { AccountService } from '../account.service'; import { map, switchMap, combineAll } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AccountGuard implements CanActivate { constructor( private accountService: AccountService ) { } canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { let account = next.paramMap.get('account') console.log("onaccpuntaut", this.accountService.authUser) return forkJoin(this.accountService.getAccount(account), this.accountService.currentLang()).pipe(switchMap(a => of(true))) } } <file_sep>import { Component, OnInit, Input, Output, EventEmitter, Injector } from '@angular/core'; import { getObjectCopy } from 'src/app/helpers/object.helper'; import { FactoryService } from 'src/app/master/states/factory.service'; import { Table } from 'src/app/enums/table.enum'; import { Folder } from './folder.model'; import {isNil} from 'lodash' import { FolderableEditComponent } from 'src/app/master/states/folderable-edit.component'; @Component({ selector: 'app-folder-edit', templateUrl: './folder-edit.component.html', styleUrls: ['./folder-edit.component.sass'] }) export class FolderEditComponent extends FolderableEditComponent<Folder,Folder> implements OnInit { @Input() type: Table @Input() parent: Folder; @Input("model") oModel: Folder @Output() close: EventEmitter<any> = new EventEmitter(); public created: boolean = false; public model: Folder; public ngOnInit() { this.model = new Folder().clone(this.oModel); super.ngOnInit() } create() { (this.isEdit ? this.service.updateFolder(this.model.id, this.model) : this.service.addFolder(this.model) ).subscribe(r => this.close.emit() ); } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; // import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ResizableDirective } from './widgets/resizable.directive'; import { ContextMenuDirective } from './widgets/context-menu/context-menu.directive'; import { ContextMenuComponent } from './widgets/context-menu/context-menu.component'; import { AdminAccountAddComponent } from './admin/admin-account/admin-account-add/admin-account-add.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; import { SecurityComponent } from './account/security/security.component'; import { AccountSecurityUserComponent } from './account/security/account-security-user/account-security-user.component'; import { AccountSecurityEditUserComponent } from './account/security/account-security-user/account-security-edit-user/account-security-edit-user.component'; import { AccountSecurityAccessTemplateComponent } from './account/security/account-security-access-template/account-security-access-template.component'; import { AccountSecurityEditAccessTemplateComponent } from './account/security/account-security-access-template/account-security-edit-access-template/account-security-edit-access-template.component'; //widget import { AccountSecurityAuthLoginComponent } from './account/security/account-security-auth/account-security-auth-login/account-security-auth-login.component'; import { AccountHomeComponent } from './account/account-home/account-home.component'; import { httpInterceptorProviders } from './interceptors.ts'; import { TreeviewModule } from './widgets/ngx-treeview/treeview.module'; // import { BsDropdownModule } from './widgets/dropdown/bs-dropdown.module'; import { MinValidatorDirective } from './validators/min-validator.directive'; import { MaxValidatorDirective } from './validators/max-validator.directive'; import { NumericValidatorDirective } from './validators/numeric-validator.directive'; import { NgxMaskModule } from './widgets/ngx-mask'; import { DndModule } from './widgets/ngx-darg-drop/dnd.module'; import { ContextMenuModule } from './widgets/ngx-contextmenu/ngx-contextmenu'; import { FontAwesomeModule, FaIconLibrary } from '@fortawesome/angular-fontawesome'; import { fas } from '@fortawesome/free-solid-svg-icons'; import { ScrollToModule } from './widgets/ngx-scroll-to/scroll-to.module'; import { ToastrModule } from './widgets/ngx-toastr/toastr/toastr.module'; import { ItemAlreadyExistsDirective } from './validators/item-already-exists-validator.directive'; import { RegexValidatorDirective } from './validators/regex-validator.directive'; import { DatabaseModule } from './account/data/database/database.module'; import { SecurityModule } from './account/security/security.module'; import { EditModalModule } from './master/components/edit-modal/edit-modal.module'; import { ListModule } from './account/data/list/list.module'; import { DataComponent } from './account/data/data.component'; import { FolderModule } from './account/data/folder/folder.module'; import { TreeviewControlModule } from './master/components/treeview-control/treeview-control.module'; import { GroupModule } from './account/security/group/group.module'; import { UserModule } from './account/security/user/user.module'; import { Folder2Module } from './account/security/folder/folder.module'; import { TranslocoRootModule } from './transloco-root.module'; import { NgSelectModule } from './widgets/ng-select/ng-select.module'; import { AccountModule } from './account/account.module'; @NgModule({ declarations: [ AppComponent, ResizableDirective, ContextMenuDirective, ContextMenuComponent, // ModalDirective, AdminAccountAddComponent, PageNotFoundComponent, AccountSecurityUserComponent, AccountSecurityEditUserComponent, AccountSecurityAuthLoginComponent, AccountSecurityAccessTemplateComponent, AccountSecurityEditAccessTemplateComponent, AccountHomeComponent, MinValidatorDirective, MaxValidatorDirective, NumericValidatorDirective, ItemAlreadyExistsDirective, /* AccountGroupTabComponent, AccountInfoTabComponent, */ // EditModalComponent, RegexValidatorDirective, DataComponent, // AccountDataDbDataListControlComponent, // AccountDataDbDataAddressControlComponent, // AccountDataDbDataNumberControlComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule, ReactiveFormsModule, BrowserAnimationsModule, // GroupModule, // DatabaseModule, // FolderModule, // Folder2Module, // ListModule, SecurityModule, EditModalModule, // UserModule, // NgSelectModule, DndModule, TreeviewModule.forRoot(), // BsDatepickerModule.forRoot(), // BsDropdownModule.forRoot(), NgxMaskModule.forRoot(), ContextMenuModule.forRoot({ useBootstrap4: true, }), AccountModule, FontAwesomeModule, ScrollToModule.forRoot(), ToastrModule.forRoot({ positionClass: 'toast-bottom-center', enableHtml: true }), TranslocoRootModule, NgSelectModule // FontAwesomeModule ], providers: [ httpInterceptorProviders ], bootstrap: [AppComponent] }) export class AppModule { constructor(library: FaIconLibrary) { library.addIconPacks(fas); } } <file_sep>import { TestBed, async, inject } from '@angular/core/testing'; import { AccountGroupGuard } from './account-group.guard'; describe('AccountGroupGuard', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [AccountGroupGuard] }); }); it('should ...', inject([AccountGroupGuard], (guard: AccountGroupGuard) => { expect(guard).toBeTruthy(); })); }); <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AccountDataDbDataTextControlComponent } from './account-data-db-data-text-control.component'; describe('AccountDataDbDataTextControlComponent', () => { let component: AccountDataDbDataTextControlComponent; let fixture: ComponentFixture<AccountDataDbDataTextControlComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AccountDataDbDataTextControlComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AccountDataDbDataTextControlComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using MiniS.Areas.Admin.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Identity.Services; using MiniS.Helpers; using SignInResult = Microsoft.AspNetCore.Identity.SignInResult; namespace MiniS.Areas.Identity.Controllers { [Route("api/{account}/security/auth")] public class AuthController : ControllerBase { public AuthController( UserManager<AccountUser> userManager, SignInManager<AccountUser> signInManager, AccountUserService service, ILogger<AccountUserController> logger) { _userManager = userManager; _signInManager = signInManager; _service = service; _logger = logger; } [HttpGet("user")] [Account] [Authorize] public ActionResult<AccountUser> GetUser(string account) { // Get the current user from HttpContext when the accountAttribute authorization executed return (AccountUser) HttpContext.Items["authUser"]; // If no authenticated user found return a 404 not found response // if (authUser == null) return NotFound(new { Message = "No authenticated user found" }); // If an authenticated user found return it with a 200 Http response } [HttpPost("login")] [AllowAnonymous] public async Task<ActionResult<AccountUser>> OnPostAsync([FromBody] Login login) { var user = await _service.Login(login); if(_service.Fails()){ if(_service.NotFound) return NotFound(_service.ModelState); else return BadRequest(_service.ModelState); } return user; } [HttpPost("logout")] [AllowAnonymous] public async Task<IActionResult> Logout() { await _signInManager.SignOutAsync(); _logger.LogInformation("User logged out."); return Ok(new {Message="user logged out"}); } private readonly UserManager<AccountUser> _userManager; private readonly ILogger<AccountUserController> _logger; private readonly SignInManager<AccountUser> _signInManager; private readonly AccountUserService _service; public AppDbContext _dbContext { get; } } }<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AccountDataDbFormDisplayComponent } from './account-data-db-form-display.component'; describe('AccountDataDbFormDisplayComponent', () => { let component: AccountDataDbFormDisplayComponent; let fixture: ComponentFixture<AccountDataDbFormDisplayComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AccountDataDbFormDisplayComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AccountDataDbFormDisplayComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/* import { Component, Input, forwardRef, ViewChild, OnChanges, Output, EventEmitter } from "@angular/core"; import { NG_VALUE_ACCESSOR, NG_VALIDATORS, ControlValueAccessor, Validator, FormControl, NgModel } from "@angular/forms"; import { ListItem } from "src/app/account/data/models/list-item"; import { FieldAttribute, FieldType } from "../../../models/field"; @Component({ selector: "app-account-data-db-data-list-control", templateUrl: "./account-data-db-data-list-control.component.html", styleUrls: ["./account-data-db-data-list-control.component.sass"], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => AccountDataDbDataListControlComponent), multi: true }, { provide: NG_VALIDATORS, useExisting: forwardRef(() => AccountDataDbDataListControlComponent), multi: true } ] }) export class AccountDataDbDataListControlComponent implements ControlValueAccessor, Validator, OnChanges { ngOnChanges(changes: import("@angular/core").SimpleChanges): void { if (changes.detect) { this.currItems = this._currItems(); this.model = null; this.itemsLength = this.currItems.length; console.log("detection"); } } constructor() {} @Input() public items: { [key: string]: Array<ListItem> }; @Input() public baseModel: any; @Input() public detect: number; @Output() public detectChange: EventEmitter<any> = new EventEmitter<any>(); public currItems: Array<ListItem>; public itemsLength: number; public type: "select" | "multiSelect" ngOnInit() { this.type = this.model.field.multi ? "multiSelect" : "select"; this.model = this.fieldAttribute.options[this.type].default; this.currItems = this._currItems(); this.itemsLength = this.currItems.length; } @ViewChild("ngModel", { static: false }) ngModel: NgModel; @Input() fieldAttribute: FieldAttribute; private _model: any; public set model(value: any) { this._model = value; this.onChange(value); this.onTouched(); } public get model() { return this._model; } onChange: any = () => {}; onTouched: any = () => {}; registerOnChange(fn) { this.onChange = fn; } writeValue(value) { console.log(value); this.model = value; } registerOnTouched(fn) { this.onTouched = fn; } validate(_: FormControl) { return this.ngModel.valid ? null : { textControl: { valid: false } }; } private _currItems(): Array<ListItem> { const columnName = this.fieldAttribute.field.columnName; if (this.fieldAttribute.field.column == FieldType.DependentList) { const pli: number = this.baseModel[ this.fieldAttribute.field.relatedField.columnName ]; console.log("parent", pli, "basmodel", this.baseModel); return this.items[columnName].filter(i => i.parentListItemId == pli); } else return this.items[columnName]; } } */<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Data.Models { public class DatabaseData : Groupable<Database> { public long DatabaseId { get; set; } public Database Database { get; set; } public bool IsActive { get; set; } = true; public DateTime? ActiveUntil { get; set; } public DateTime? ActiveBy { get; set; } [InverseProperty("Parent")] public List<DataAddress> DataAddresses{get; set;} /* public List<DataContact> DataContacts {get; set;} */ public List<ListItem> ListItems {get; set;} public long Integer0 { get; set; } public long Integer1 { get; set; } public long Integer2 { get; set; } public long Integer3 { get; set; } public long Integer4 { get; set; } public long Integer5 { get; set; } public long Integer6 { get; set; } public long Integer7 { get; set; } public long Integer8 { get; set; } public long Integer9 { get; set; } public decimal Decimal0 { get; set; } public decimal Decimal1 { get; set; } public decimal Decimal2 { get; set; } public decimal Decimal3 { get; set; } public decimal Decimal4 { get; set; } public decimal Decimal5 { get; set; } public decimal Decimal6 { get; set; } public decimal Decimal7 { get; set; } public decimal Decimal8 { get; set; } public decimal Decimal9 { get; set; } //text field public string Text0 { get; set; } public string Text1 { get; set; } public string Text2 { get; set; } public string Text3 { get; set; } public string Text4 { get; set; } public string Text5 { get; set; } public string Text6 { get; set; } public string Text7 { get; set; } public string Text8 { get; set; } public string Text9 { get; set; } public bool CheckBox0 {get; set;} public bool CheckBox1 {get; set;} public bool CheckBox2 {get; set;} public bool CheckBox3 {get; set;} public bool CheckBox4 {get; set;} public bool CheckBox5 {get; set;} public bool CheckBox6 {get; set;} public bool CheckBox7 {get; set;} public bool CheckBox8 {get; set;} public bool CheckBox9 {get; set;} } public class DataConfiguration : GroupableConfiguration<DatabaseData, Database> { } /* public enum FieldType { Integer = 10, Decimal = 20, Text = 30, TextArea = 40, List = 50, DList = 60, } */ }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using MiniS.Areas.Admin.Models; using MiniS.Areas.Data.Models; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Identity.Models { public class AccessTemplate : Parentable<Folder> { [Required] public Dictionary<Access, Right> Accesses { get; set; } } public class AccessTemplateConfiguration : ParentableConfiguration<AccessTemplate,Folder> { } public enum Access { // security User = 10, UserTemplate = 20, AcccesTemplate = 30, Group = 40, // Data Form = 110, View = 120, List = 130, ListItem = 135, Record = 140, Filter = 150, Folder = 160, Database = 170, DatabaseField = 180, DatabaseFieldAttribute = 190, DatabaseData = 200, // Library Directory = 510, Files = 520 } public enum Right { None = 0, Read = 10, Create = 20, Modify = 30, Delete = 40, Admin = 50 } }<file_sep>import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core'; import { ListitemService } from '../state/listitem.service'; import { List } from '../../list/state/list.model'; import { Listitem } from '../state/listitem.model'; import { Observable } from 'rxjs'; @Component({ selector: 'app-listitem-edit', templateUrl: './listitem-edit.component.html', styleUrls: ['./listitem-edit.component.sass'] }) export class ListitemEditComponent implements OnInit { constructor(private listitemService: ListitemService) {} @Input() parent: List; @Input("model") oModel: Listitem = new Listitem(); @Output() close: EventEmitter<any> = new EventEmitter(); public edit: boolean = false; public model: Listitem; public ngOnInit() { this.oModel.dependant = this.parent.dependant this.model = Listitem.create(this.oModel); this.model.parentListId = this.parent.parentListId this.listitemService.updateParentId(this.parent.id) if(this.parent.dependant) this.listitemService.getParentListitem(this.parent.parentListId).subscribe() this.edit = this.model.showEdit; } create() { (this.edit ? this.listitemService.update(this.model.id, this.model) :this.listitemService.add(this.model) ).subscribe(r => { this.oModel = this.model = r; }); } get parentListitems$(): Observable<Array<Listitem>> { return this.listitemService.pListitems$; } } <file_sep> import { Groupable } from 'src/app/master/base-model/groupable.model'; import { Folder } from '../../folder/folder.model'; import { Listitem } from '../../listitem/state/listitem.model'; export class List extends Groupable<Folder> { public dependant: boolean = false public parentListId?: number public listChildren : Array<List> public listItems: Array<Listitem> private _parentList?: List set parentList(value:List){ this._parentList = value if(value) this.parentListId = value.id } get parentList(){ return this._parentList } public showAddListitem: boolean = false }<file_sep>import { Directive } from "@angular/core"; import { NG_VALIDATORS, AbstractControl, Validator } from "@angular/forms"; @Directive({ selector: "[regex]", providers: [ { provide: NG_VALIDATORS, useExisting: RegexValidatorDirective, multi: true } ] }) export class RegexValidatorDirective implements Validator { validate(control: AbstractControl): { [key: string]: any } | null { try { new RegExp(control.value); return null; } catch (e) { return { regex: { actualRegex: control.value } }; } } } <file_sep>import { NgModule } from '@angular/core'; import { UserItemComponent } from './components/user-item.component'; import { UserComponent } from './components/user.component'; import { FormsModule } from '@angular/forms'; import { EditModalModule } from 'src/app/master/components/edit-modal/edit-modal.module'; import { InfoFormControlModule } from 'src/app/master/components/form-control/info-form-control/info-form-control.module'; import { TreeviewFolderableModule } from 'src/app/master/components/treeview-template/treeview-folderable.module'; import { IconModule } from 'src/app/master/components/icon/icon.module'; import { ContextMenuModule } from 'src/app/widgets/ngx-contextmenu/ngx-contextmenu'; import { TreeviewControlModule } from 'src/app/master/components/treeview-control/treeview-control.module'; import { DatatableModule } from 'src/app/widgets/datatable/datatable.module'; import { RouterModule } from '@angular/router'; import { LoaderModule } from 'src/app/master/components/loader/loader.module'; import { EntityItemModule } from 'src/app/master/components/entity-item/entity-item.module'; import { DisplayViewModule } from 'src/app/master/components/display-view/display-view.module'; import { CommonModule } from '@angular/common'; import { UserEditComponent } from './components/user-edit.component'; import { NgSelectModule } from 'src/app/widgets/ng-select/ng-select.module'; import { Folder2Module } from '../folder/folder.module'; import { GroupModule } from '../group/group.module'; import { UserTreeviewComponent } from './components/user-treeview.component'; import { UserDisplayPageComponent } from './components/user-display-page.component'; import { ValidatorsModule } from 'src/app/validators/validators.module'; import { UserService } from './state/user.service'; @NgModule({ declarations: [UserItemComponent, UserComponent, UserEditComponent, UserTreeviewComponent, UserDisplayPageComponent], imports: [ CommonModule, FormsModule, EditModalModule, InfoFormControlModule, TreeviewFolderableModule, Folder2Module, IconModule, ContextMenuModule.forRoot(), TreeviewControlModule, DatatableModule, RouterModule, LoaderModule, EntityItemModule, DisplayViewModule, NgSelectModule, GroupModule, ValidatorsModule ], exports: [UserItemComponent, UserComponent], providers: [UserService] }) export class UserModule { } <file_sep>/* using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using MiniS.Areas.Admin.Models; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Repositories; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Models; using MiniS.Helpers; namespace MiniS.Areas.Data.Controllers { [Route ("api/{account}/data/{parent}/stepper")] [Authorize] [Account] public class StepperController : ControllerBase { public AuthorizationService _authService { get; } public FormRepository _formRepo { get; } public StepperRepository _stepperRepo { get; } public StepperController ( FormRepository formRepo, StepperRepository stepperRepo ) { _formRepo = formRepo; _stepperRepo = stepperRepo; _authService = new AuthorizationService (HttpContext, Access.Form); } [HttpGet] public async Task<ActionResult<List<Stepper>>> GetAllAsync (long parent) { if (_authService.HasRight (Right.Read)) return Forbid (); /* Get the current authenticated User AccountUser authUser = _authService.GetAuthUser (); Form form = await _formRepo.GetForm (parent, authUser.AccountId); if (_authService.CanAccess (form)) return Forbid (); return await _stepperRepo.GetSteppers (parent, authUser); } [HttpGet ("{id}", Name = "GetStepper")] public async Task<ActionResult<Stepper>> GetAsync (long id) { if (_authService.HasRight (Right.Read)) return Forbid (); return await _stepperRepo.GetStepper (id, _authService.GetAccountId ()); } [HttpPost] public async Task<ActionResult<Form>> CreateAsync (long parent, Stepper model) { if (_authService.HasRight (Right.Create)) return Forbid (); //if (!listItem.AllGroup && listItem.Groups.Count < 1) return BadRequest(new { Message = "you must specify a group" }); //Get the parent folder and if there is, we do intersection chile parent of their attached group // if(_authService.AuthorizeResource(HttpContext, list.PList).Fails()) return Forbid(_authService.GetMessage()); Form form = await _formRepo.GetForm (parent, _authService.GetAccountId ()); if (form == null) return BadRequest (new { Message = "your list has no related form" }); if (_authService.CanAccess (form)) return Forbid (); Stepper stepper = new Stepper (); await _stepperRepo.Create (stepper, model, parent, _authService.GetAuthUser ()); return CreatedAtRoute ("GetStepper", new { parent = parent, id = stepper.Id, account = _authService.GetAccount ().NormalizedName }, stepper); } [HttpPut ("{id}")] public async Task<ActionResult<Stepper>> updateAsync (long parent, long id, Stepper model) { if (_authService.HasRight (Right.Create)) return Forbid (); Form form = await _formRepo.GetForm (parent, _authService.GetAccountId ()); if (form == null) return BadRequest (new { Message = "your stepper has no related form" }); if (_authService.CanAccess (form)) return Forbid (); Stepper stepper = await _stepperRepo.GetStepper (id, _authService.GetAccountId ()); if (stepper == null) return NotFound (); return await _stepperRepo.Update (stepper, model, parent, _authService.GetAuthUser ()); } [HttpDelete ("{id}")] public async Task<IActionResult> DeleteTodoItem (long parent, long id) { if (_authService.HasRight (Right.Create)) return Forbid (); Form form = await _formRepo.GetForm (parent, _authService.GetAccountId ()); if (form == null) return BadRequest (new { Message = "your stepper has no related form" }); if (_authService.CanAccess (form)) return Forbid (); Stepper stepper = await _stepperRepo.GetStepper (id, _authService.GetAccountId ()); if (stepper == null) return NotFound (); if (stepper.FormId != form.Id) return BadRequest (new { Message = "the stepper does not bélonf=g to this form" }); await _stepperRepo.Delete (stepper); return NoContent (); } [HttpPost ("order")] public async Task<ActionResult<Stepper[]>> Order (long parent, long[] orders) { if (_authService.HasRight (Right.Create)) return Forbid (); /* Get the current authenticated User AccountUser authUser = _authService.GetAuthUser (); Form form = await _formRepo.GetForm (parent, authUser.AccountId); if (_authService.CanAccess (form)) return Forbid (); return await _stepperRepo.UpdateOrder (parent, authUser.AccountId, orders); } } } */<file_sep>export function isNotEmpty(value: any): boolean { if (!value) return false typeof value == 'string' && (value = value.trim()) console.log(value.length > 0) return value.length > 0 } export function equals(str1: string, str2: string, caseSensitive: boolean = false): boolean { str1 = str1.trim() str2 = str2.trim() if (caseSensitive) return str1 == str2 return str1.toLocaleLowerCase() == str2.toLocaleLowerCase() } export function pathJoin(parts:any[], separator = '/') { var replace = new RegExp(separator + '{1,}', 'g'); return parts.join(separator).replace(replace, separator); } <file_sep>/* using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using MiniS.Areas.Data.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Models; using MiniS.Areas.Master.Enums; namespace MiniS.Areas.Data.Repositories { public class DatabaseDataRepository { private AppDbContext _dbContext; public DatabaseDataRepository ( AppDbContext dbContext ) { _dbContext = dbContext; } public Task<DatabaseData> GetDatabaseData (long id, long accountId) { return _dbContext.DatabaseData.Where (l => l.Id == id && l.AccountId == accountId).FirstOrDefaultAsync (); } public List<Group> GetGroups (DatabaseData databaseData) { return _dbContext.GetGroups (databaseData.Id, Table.DatabaseData).Result; } public async Task<List<DatabaseData>> GetAllDatabaseData (long databaseId, AccountUser authUser) { /* Fetch all folders belonging to the current account and child of the parent folder return await _dbContext.DatabaseData .Where (f => f.Account.Id == authUser.AccountId && f.DatabaseId == databaseId) .Include (dd => dd.DataAddresses).Include (dd => dd.DataContacts) .Include (dd => dd.ListItems) .ToListAsync (); } public async Task<DatabaseData> Update (DatabaseData database, Database model, long AccountId, bool edit = false) { database.Name = model.Name; database.Description = model.Description; _dbContext.Update (database); await _dbContext.SaveChangesAsync (); List<EntityGroup> currentEG = await _dbContext.GetEntityGroups (database.Id, Table.Database); if (!database.AllGroup) { _dbContext.UpdateManyToMany (database.Groups.Select (g => new EntityGroup () { EntityId = database.Id, Table = Table.Database, GroupId = g.Id, AccountId = AccountId }).ToList (), currentEG); } else { _dbContext.UpdateManyToMany (new List<EntityGroup> (), currentEG); } await _dbContext.SaveChangesAsync (); return database; } public async Task<Database> Create (Database database, Database model, long parentId, AccountUser authUser) { database.ParentId = parentId; database.Name = model.Name; database.Description = model.Description; //database.StandardData = new StandardData(); await _dbContext.Databases.AddAsync (database); await _dbContext.SaveChangesAsync (authUser); if (!database.AllGroup) { _dbContext.UpdateManyToMany (database.Groups.Select (g => new EntityGroup () { EntityId = database.Id, Table = Table.Database, GroupId = g.Id }).ToList (), new List<EntityGroup> ()); } await _dbContext.SaveChangesAsync (); return database; } } } */<file_sep>import { TestBed } from '@angular/core/testing'; import { AccountUserService } from './account-user.service'; describe('AccountUserService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: AccountUserService = TestBed.get(AccountUserService); expect(service).toBeTruthy(); }); }); <file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { Access, accessByModule } from '../access.enum'; import { Right } from '../right.enum'; import { AccessTemplate } from '../access-template'; import { ActivatedRoute } from '@angular/router'; import { AccountSecurityAccessTemplateService } from '../account-security-access-template.service'; @Component({ selector: 'app-account-security-edit-access-template', templateUrl: './account-security-edit-access-template.component.html', styleUrls: ['./account-security-edit-access-template.component.scss'] }) export class AccountSecurityEditAccessTemplateComponent implements OnInit { constructor(private accessTemplateService: AccountSecurityAccessTemplateService) { } public accessByModule = accessByModule() public access = Object.keys(Access).filter(a => isNaN(Number(a))) public right = Object.keys(Right).filter(r => isNaN(Number(r))) public Right = Right public currentTab:number = 1 @Input() model: AccessTemplate = new AccessTemplate(0, null,null, {}) @Output() close: EventEmitter<any> = new EventEmitter() @Input() account: string ngOnInit() { //if some accesses are not right assigned we asign the none right by default this.access.forEach(a => { if (!this.model.accesses.hasOwnProperty(a)) this.model.accesses[a] = 0 }) } create() { let action = this.model.showEdit ? this.accessTemplateService.update : this.accessTemplateService.create action.call(this.accessTemplateService, this.account, this.model).subscribe() this.cancel() } cancel() { this.close.emit() } } <file_sep>import { Input, Output, EventEmitter, Directive, ViewChild, ElementRef, OnInit } from "@angular/core"; import { Field, FieldType } from "../models/field"; import { Db } from "../models/db"; import { AccountDataDbService } from "../account-data-db.service"; import { Observable } from "rxjs"; import { tap } from "rxjs/operators"; @Directive() export class AccountDataFieldBase implements OnInit { public constructor(protected dbService: AccountDataDbService) { } public FieldType = FieldType; @Output() delete: EventEmitter<any> = new EventEmitter(); @Output() edit: EventEmitter<any> = new EventEmitter(); public ngOnInit() { this.goTo.nativeElement.scrollIntoView({ behavior: "smooth" }); } @Input() field: Field; @Input() database: Db; @ViewChild("goTo", { static: true }) goTo: ElementRef; deleteField(force: boolean = false) { this.database.fieldProcessing = false; if (force) this.dbService .deleteField(this.database.id, this.field.id) .subscribe(r => this.delete.emit()); this.field.created ? (this.field.updated = true) : this.delete.emit(); } protected getUpdateObservable(value: any): Observable<Field> { return (this.field.created ? this.dbService.updateField(this.database.id, value.id, value) : this.dbService.createField(this.database.id, value) ).pipe( tap(r => { this.edit.emit(r); this.database.fieldProcessing = false; }) ); } editField() { this.field.updated = false; this.database.fieldProcessing = true; } get fieldNames(): Array<string> { return this.database.fields.map(f => f.name); } } <file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { Table } from 'src/app/enums/table.enum'; import { ITrackable } from 'src/app/master/base-model/trackable.model'; import { GroupService } from '../state/group.service'; import { Identificable } from 'src/app/master/base-model/identificable.model'; @Component({ selector: 'app-group-treeview', templateUrl: './group-treeview.component.html', styleUrls: ['./group-treeview.component.sass'] }) export class GroupTreeviewComponent implements OnInit { constructor(private groupService: GroupService) { } @Input() public items: TreeviewItem[] @Input() public loading: boolean @Input() public multi:boolean =true @Input() public checkbox: boolean = false @Input() public noLink: boolean = false @Output() public selectedChange: EventEmitter<ITrackable[]> = new EventEmitter() public onSelect = (selected: Identificable[]) => { this.selectedChange.emit(selected) this.groupService.selected = selected.map(s=>s.id) } public type: Table = Table.Group ngOnInit(): void { } } <file_sep>import { Table } from "src/app/enums/table.enum"; import { Groupable } from 'src/app/master/base-model/groupable.model'; export class Folder extends Groupable <Folder> { public type: Table } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TreeviewSelectComponent } from './treeview-select.component'; import { TreeviewControlComponent } from './treeview-control.component'; import { TreeviewModule } from 'src/app/widgets/ngx-treeview'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { IconModule } from '../icon/icon.module'; import { TableToIconPipe } from '../../pipes/table-to-icon.pipe'; import { EditModalModule } from '../edit-modal/edit-modal.module'; @NgModule({ declarations: [TreeviewSelectComponent, TreeviewControlComponent, TableToIconPipe], imports: [ CommonModule, TreeviewModule.forRoot(), FormsModule, ReactiveFormsModule, IconModule, EditModalModule ], exports: [TreeviewControlComponent, TreeviewSelectComponent] }) export class TreeviewControlModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { AccountSecurityAccessTemplateService } from './account-security-access-template.service'; import { AccessTemplate } from './access-template'; import { AccountService } from '../../account.service'; import { isEmpty } from 'src/app/helpers/object.helper'; @Component({ selector: 'app-account-security-access-template', templateUrl: './account-security-access-template.component.html', styleUrls: ['./account-security-access-template.component.scss'] }) export class AccountSecurityAccessTemplateComponent implements OnInit { constructor(private accountService: AccountService, private accessTemplateService: AccountSecurityAccessTemplateService) { } public account: string public showAccess:boolean = false public selected: { [s: number]: boolean; } = {} ngOnInit() { //assign the account string from the route data this.account = this.accountService.account.normalizedName this.accessTemplateService.getAll(this.account).subscribe() } get accessTemplates(): Array<AccessTemplate> { return this.accessTemplateService.accessTemplates } delete(id: number) { this.accessTemplateService.delete(this.account, id).subscribe() } editSelected() { let id = +Object.keys(this.selected).find(s => this.selected[s]) if(id) this.accessTemplates.some(a => { if (a.id == id) { a.showEdit = true return true } }) } deleteSelected() { let id = +Object.keys(this.selected).find(s => this.selected[s]) if(id) this.accessTemplates.some(a => { if (a.id == id) { a.showEdit = true return true } }) } get selectedIsEmpty(): boolean { return isEmpty(this.selected) } } <file_sep>using System; using Microsoft.EntityFrameworkCore.Migrations; namespace MiniS.Migrations { public partial class first : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Accounts", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), NormalizedName = table.Column<string>(maxLength: 70, nullable: false), Timestamp = table.Column<byte[]>(rowVersion: true, nullable: true) }, constraints: table => { table.PrimaryKey("PK_Accounts", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "Folders", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), AccountId = table.Column<long>(nullable: false), ParentId = table.Column<long>(nullable: false), AllGroup = table.Column<bool>(nullable: false), Type = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Folders", x => x.Id); table.ForeignKey( name: "FK_Folders_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Folders_Folders_ParentId", column: x => x.ParentId, principalTable: "Folders", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), RoleId = table.Column<long>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AccessTemplates", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), AccountId = table.Column<long>(nullable: false), ParentId = table.Column<long>(nullable: false), Accesses = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AccessTemplates", x => x.Id); table.ForeignKey( name: "FK_AccessTemplates_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AccessTemplates_Folders_ParentId", column: x => x.ParentId, principalTable: "Folders", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), UserName = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), PasswordHash = table.Column<string>(nullable: true), SecurityStamp = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), TwoFactorEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), LockoutEnabled = table.Column<bool>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), LastName = table.Column<string>(nullable: false), FirstName = table.Column<string>(nullable: true), AccountId = table.Column<long>(nullable: false), UserLevel = table.Column<string>(nullable: false, defaultValue: "Regular"), Accesses = table.Column<string>(nullable: true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), AllGroup = table.Column<bool>(nullable: false), Description = table.Column<string>(nullable: true), ParentId = table.Column<long>(nullable: false), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); table.ForeignKey( name: "FK_AspNetUsers_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUsers_Folders_ParentId", column: x => x.ParentId, principalTable: "Folders", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Databases", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), AccountId = table.Column<long>(nullable: false), ParentId = table.Column<long>(nullable: false), AllGroup = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Databases", x => x.Id); table.ForeignKey( name: "FK_Databases_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Databases_Folders_ParentId", column: x => x.ParentId, principalTable: "Folders", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Groups", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), AccountId = table.Column<long>(nullable: false), ParentId = table.Column<long>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Groups", x => x.Id); table.ForeignKey( name: "FK_Groups_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Groups_Folders_ParentId", column: x => x.ParentId, principalTable: "Folders", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Lists", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), AccountId = table.Column<long>(nullable: false), ParentId = table.Column<long>(nullable: false), AllGroup = table.Column<bool>(nullable: false), ParentListId = table.Column<long>(nullable: true), Dependant = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Lists", x => x.Id); table.ForeignKey( name: "FK_Lists_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Lists_Folders_ParentId", column: x => x.ParentId, principalTable: "Folders", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Lists_Lists_ParentListId", column: x => x.ParentListId, principalTable: "Lists", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), UserId = table.Column<long>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<long>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<long>(nullable: false), RoleId = table.Column<long>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<long>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "DatabaseData", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), AccountId = table.Column<long>(nullable: false), ParentId = table.Column<long>(nullable: false), AllGroup = table.Column<bool>(nullable: false), DatabaseId = table.Column<long>(nullable: false), IsActive = table.Column<bool>(nullable: false), ActiveUntil = table.Column<DateTime>(nullable: true), ActiveBy = table.Column<DateTime>(nullable: true), Integer0 = table.Column<long>(nullable: false), Integer1 = table.Column<long>(nullable: false), Integer2 = table.Column<long>(nullable: false), Integer3 = table.Column<long>(nullable: false), Integer4 = table.Column<long>(nullable: false), Integer5 = table.Column<long>(nullable: false), Integer6 = table.Column<long>(nullable: false), Integer7 = table.Column<long>(nullable: false), Integer8 = table.Column<long>(nullable: false), Integer9 = table.Column<long>(nullable: false), Decimal0 = table.Column<decimal>(nullable: false), Decimal1 = table.Column<decimal>(nullable: false), Decimal2 = table.Column<decimal>(nullable: false), Decimal3 = table.Column<decimal>(nullable: false), Decimal4 = table.Column<decimal>(nullable: false), Decimal5 = table.Column<decimal>(nullable: false), Decimal6 = table.Column<decimal>(nullable: false), Decimal7 = table.Column<decimal>(nullable: false), Decimal8 = table.Column<decimal>(nullable: false), Decimal9 = table.Column<decimal>(nullable: false), Text0 = table.Column<string>(nullable: true), Text1 = table.Column<string>(nullable: true), Text2 = table.Column<string>(nullable: true), Text3 = table.Column<string>(nullable: true), Text4 = table.Column<string>(nullable: true), Text5 = table.Column<string>(nullable: true), Text6 = table.Column<string>(nullable: true), Text7 = table.Column<string>(nullable: true), Text8 = table.Column<string>(nullable: true), Text9 = table.Column<string>(nullable: true), CheckBox0 = table.Column<bool>(nullable: false), CheckBox1 = table.Column<bool>(nullable: false), CheckBox2 = table.Column<bool>(nullable: false), CheckBox3 = table.Column<bool>(nullable: false), CheckBox4 = table.Column<bool>(nullable: false), CheckBox5 = table.Column<bool>(nullable: false), CheckBox6 = table.Column<bool>(nullable: false), CheckBox7 = table.Column<bool>(nullable: false), CheckBox8 = table.Column<bool>(nullable: false), CheckBox9 = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_DatabaseData", x => x.Id); table.ForeignKey( name: "FK_DatabaseData_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_DatabaseData_Databases_DatabaseId", column: x => x.DatabaseId, principalTable: "Databases", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_DatabaseData_Databases_ParentId", column: x => x.ParentId, principalTable: "Databases", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Forms", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), AccountId = table.Column<long>(nullable: false), ParentId = table.Column<long>(nullable: false), AllGroup = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Forms", x => x.Id); table.ForeignKey( name: "FK_Forms_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Forms_Databases_ParentId", column: x => x.ParentId, principalTable: "Databases", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "EntityGroups", columns: table => new { GroupId = table.Column<long>(nullable: false), Table = table.Column<string>(nullable: false), EntityId = table.Column<long>(nullable: false), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), AccountId = table.Column<long>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_EntityGroups", x => new { x.GroupId, x.EntityId, x.Table }); table.ForeignKey( name: "FK_EntityGroups_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_EntityGroups_Groups_GroupId", column: x => x.GroupId, principalTable: "Groups", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Fields", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), AccountId = table.Column<long>(nullable: false), ParentId = table.Column<long>(nullable: false), Guid = table.Column<Guid>(nullable: false, defaultValueSql: "hex( randomblob(4)) || '-' || hex( randomblob(2))|| '-' || '4' || substr( hex( randomblob(2)), 2) || '-'|| substr('AB89', 1 + (abs(random()) % 4) , 1) ||substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6))"), Type = table.Column<int>(nullable: false), ListId = table.Column<long>(nullable: true), RelatedFieldId = table.Column<long>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Fields", x => x.Id); table.ForeignKey( name: "FK_Fields_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Fields_Lists_ListId", column: x => x.ListId, principalTable: "Lists", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Fields_Databases_ParentId", column: x => x.ParentId, principalTable: "Databases", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Fields_Fields_RelatedFieldId", column: x => x.RelatedFieldId, principalTable: "Fields", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "ListItems", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), AccountId = table.Column<long>(nullable: false), ParentId = table.Column<long>(nullable: false), AllGroup = table.Column<bool>(nullable: false), Dependant = table.Column<bool>(nullable: false), ParentListId = table.Column<long>(nullable: true), ParentListItemId = table.Column<long>(nullable: true), DatabaseDataId = table.Column<long>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_ListItems", x => x.Id); table.ForeignKey( name: "FK_ListItems_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_ListItems_DatabaseData_DatabaseDataId", column: x => x.DatabaseDataId, principalTable: "DatabaseData", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_ListItems_Lists_ParentId", column: x => x.ParentId, principalTable: "Lists", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_ListItems_ListItems_ParentListItemId", column: x => x.ParentListItemId, principalTable: "ListItems", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Steppers", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), AccountId = table.Column<long>(nullable: false), ParentId = table.Column<long>(nullable: false), Order = table.Column<int>(type: "smallInt", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Steppers", x => x.Id); table.ForeignKey( name: "FK_Steppers_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Steppers_Forms_ParentId", column: x => x.ParentId, principalTable: "Forms", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "DataAddresses", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), AccountId = table.Column<long>(nullable: false), ParentId = table.Column<long>(nullable: false), AllGroup = table.Column<bool>(nullable: false), DatabaseId = table.Column<long>(nullable: false), FieldId = table.Column<long>(nullable: false), Country = table.Column<long>(nullable: true), State = table.Column<long>(nullable: true), City = table.Column<long>(nullable: true), Street = table.Column<long>(nullable: true), Zone = table.Column<string>(nullable: true), StreetNumber = table.Column<long>(nullable: true), Appartment = table.Column<string>(nullable: true), Longitude = table.Column<decimal>(nullable: true), Lattitude = table.Column<decimal>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_DataAddresses", x => x.Id); table.ForeignKey( name: "FK_DataAddresses_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_DataAddresses_Databases_DatabaseId", column: x => x.DatabaseId, principalTable: "Databases", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_DataAddresses_Fields_FieldId", column: x => x.FieldId, principalTable: "Fields", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_DataAddresses_DatabaseData_ParentId", column: x => x.ParentId, principalTable: "DatabaseData", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "FieldAttributes", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CreatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), CreatedBy = table.Column<string>(nullable: true), LastUpdatedAt = table.Column<DateTime>(nullable: false, defaultValueSql: "datetime('now')"), LastUpdatedBy = table.Column<string>(nullable: true), Deleted = table.Column<DateTime>(nullable: true), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(type: "text", nullable: true), AccountId = table.Column<long>(nullable: false), ParentId = table.Column<long>(nullable: false), Order = table.Column<int>(type: "smallInt", nullable: false), FieldId = table.Column<long>(nullable: false), StepperId = table.Column<long>(nullable: false), Options = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_FieldAttributes", x => x.Id); table.ForeignKey( name: "FK_FieldAttributes_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_FieldAttributes_Fields_FieldId", column: x => x.FieldId, principalTable: "Fields", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_FieldAttributes_Forms_ParentId", column: x => x.ParentId, principalTable: "Forms", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_FieldAttributes_Steppers_StepperId", column: x => x.StepperId, principalTable: "Steppers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.InsertData( table: "Accounts", columns: new[] { "Id", "CreatedBy", "Description", "LastUpdatedBy", "Name", "NormalizedName" }, values: new object[] { 1L, "9ecf7ds07-ca4f-459a-b202-189f076c8d02", "first account", "9ecf7d07-ca4f-459a-b202-189f076c8d02", "victo", "Victo" }); migrationBuilder.InsertData( table: "Accounts", columns: new[] { "Id", "CreatedBy", "Description", "LastUpdatedBy", "Name", "NormalizedName" }, values: new object[] { -1L, "mahdic", "0 account", "mahdic", "acoount0", "a0" }); migrationBuilder.InsertData( table: "Folders", columns: new[] { "Id", "AccountId", "AllGroup", "CreatedBy", "Description", "LastUpdatedBy", "Name", "ParentId", "Type" }, values: new object[] { -1L, -1L, false, "mahdic", null, "mahdic", "for relation", -1L, "None" }); migrationBuilder.InsertData( table: "AspNetUsers", columns: new[] { "Id", "AccessFailedCount", "Accesses", "AccountId", "AllGroup", "ConcurrencyStamp", "CreatedBy", "Description", "Email", "EmailConfirmed", "FirstName", "LastName", "LastUpdatedBy", "LockoutEnabled", "LockoutEnd", "Name", "NormalizedEmail", "NormalizedUserName", "ParentId", "PasswordHash", "PhoneNumber", "PhoneNumberConfirmed", "SecurityStamp", "TwoFactorEnabled", "UserName" }, values: new object[] { 1L, 0, null, 1L, false, "73dc9a56-cd1a-4beb-a278-a7edcbcd93d5", "mahdic", null, "<EMAIL>", false, "Mahdi", "Choyekh", "mahdic", false, null, "<NAME>", "<EMAIL>", "MAHDIC", -1L, "AQAAAAEAACcQAAAAEKguzP0mKra1zpYNy5qlF3QUVodxux00LPBEI4aMH2hV6TfV4yJqERaIvqqr7PZ23A==", null, false, "5UURQWYBHEBO7TBRGR6I6Q2GOURQRBHD", false, "mahdic" }); migrationBuilder.InsertData( table: "Folders", columns: new[] { "Id", "AccountId", "AllGroup", "CreatedBy", "Description", "LastUpdatedBy", "Name", "ParentId", "Type" }, values: new object[] { 1L, 1L, false, "mahdic", null, "mahdic", "userContainer", -1L, "User" }); migrationBuilder.CreateIndex( name: "IX_AccessTemplates_AccountId", table: "AccessTemplates", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_AccessTemplates_ParentId", table: "AccessTemplates", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUsers_AccountId", table: "AspNetUsers", column: "AccountId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true); migrationBuilder.CreateIndex( name: "IX_AspNetUsers_ParentId", table: "AspNetUsers", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_DataAddresses_AccountId", table: "DataAddresses", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_DataAddresses_DatabaseId", table: "DataAddresses", column: "DatabaseId"); migrationBuilder.CreateIndex( name: "IX_DataAddresses_FieldId", table: "DataAddresses", column: "FieldId"); migrationBuilder.CreateIndex( name: "IX_DataAddresses_ParentId", table: "DataAddresses", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_DatabaseData_AccountId", table: "DatabaseData", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_DatabaseData_DatabaseId", table: "DatabaseData", column: "DatabaseId"); migrationBuilder.CreateIndex( name: "IX_DatabaseData_ParentId", table: "DatabaseData", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_Databases_AccountId", table: "Databases", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_Databases_ParentId", table: "Databases", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_EntityGroups_AccountId", table: "EntityGroups", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_FieldAttributes_AccountId", table: "FieldAttributes", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_FieldAttributes_FieldId", table: "FieldAttributes", column: "FieldId"); migrationBuilder.CreateIndex( name: "IX_FieldAttributes_ParentId", table: "FieldAttributes", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_FieldAttributes_StepperId", table: "FieldAttributes", column: "StepperId"); migrationBuilder.CreateIndex( name: "IX_Fields_AccountId", table: "Fields", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_Fields_ListId", table: "Fields", column: "ListId"); migrationBuilder.CreateIndex( name: "IX_Fields_ParentId", table: "Fields", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_Fields_RelatedFieldId", table: "Fields", column: "RelatedFieldId"); migrationBuilder.CreateIndex( name: "IX_Folders_AccountId", table: "Folders", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_Folders_ParentId", table: "Folders", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_Forms_AccountId", table: "Forms", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_Forms_ParentId", table: "Forms", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_Groups_AccountId", table: "Groups", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_Groups_ParentId", table: "Groups", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_ListItems_AccountId", table: "ListItems", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_ListItems_DatabaseDataId", table: "ListItems", column: "DatabaseDataId"); migrationBuilder.CreateIndex( name: "IX_ListItems_ParentId", table: "ListItems", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_ListItems_ParentListItemId", table: "ListItems", column: "ParentListItemId"); migrationBuilder.CreateIndex( name: "IX_Lists_AccountId", table: "Lists", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_Lists_ParentId", table: "Lists", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_Lists_ParentListId", table: "Lists", column: "ParentListId"); migrationBuilder.CreateIndex( name: "IX_Steppers_AccountId", table: "Steppers", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_Steppers_ParentId", table: "Steppers", column: "ParentId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AccessTemplates"); migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "DataAddresses"); migrationBuilder.DropTable( name: "EntityGroups"); migrationBuilder.DropTable( name: "FieldAttributes"); migrationBuilder.DropTable( name: "ListItems"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); migrationBuilder.DropTable( name: "Groups"); migrationBuilder.DropTable( name: "Fields"); migrationBuilder.DropTable( name: "Steppers"); migrationBuilder.DropTable( name: "DatabaseData"); migrationBuilder.DropTable( name: "Lists"); migrationBuilder.DropTable( name: "Forms"); migrationBuilder.DropTable( name: "Databases"); migrationBuilder.DropTable( name: "Folders"); migrationBuilder.DropTable( name: "Accounts"); } } } <file_sep>import { AccountDataFieldBase } from './account-data-field-base'; describe('AccountDataFieldBase', () => { it('should create an instance', () => { expect(new AccountDataFieldBase()).toBeTruthy(); }); }); <file_sep>using System; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace MiniS.Areas.Master.Models { public abstract class Trackable: Entity,ITrackable { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public DateTime CreatedAt { get; set; } public string CreatedBy { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public DateTime LastUpdatedAt { get; set; } public string LastUpdatedBy { get; set; } public DateTime? Deleted { get; set; } } public interface ITrackable { DateTime CreatedAt { get; set; } string CreatedBy { get; set; } DateTime LastUpdatedAt { get; set; } string LastUpdatedBy { get; set; } DateTime? Deleted {get; set;} } public interface Entity{} public abstract class TrackableConfiguration<T> : IEntityTypeConfiguration<T> where T : Trackable { public virtual void Configure(EntityTypeBuilder<T> builder) { builder.Property(e => e.CreatedAt).HasDefaultValueSql("datetime('now')"); //replace by getdate for sql server builder.Property(e => e.LastUpdatedAt).HasDefaultValueSql("datetime('now')"); //replace by getdate for sql server builder.Property(e=>e.Deleted).HasDefaultValue(null); // Set delete flag to null by default builder.HasQueryFilter(t => t.Deleted == null); //soft delete } } } <file_sep>import { Component, OnInit, Input, TemplateRef, ComponentRef, ViewChild, Output, EventEmitter } from '@angular/core'; import { ITrackable } from 'src/app/master/base-model/trackable.model'; import { DatatableItemTemplateContext } from '../datatable-item-template-context'; import { InputType } from 'src/app/enums/input-type.enum'; import { isNotEmpty } from 'src/app/helpers/string.helper'; import { DatatableService } from '../datatable.service'; import { ColDisplay, Expression } from '../datatable.interface'; import { DndDropEvent } from '../../ngx-darg-drop/public_api'; import { NgSelectComponent } from '../../ng-select/ng-select.component'; import { ContextMenuComponent } from '../../ngx-contextmenu/contextMenu.component'; import { ContextMenuService } from '../../ngx-contextmenu/contextMenu.service'; import { find } from "lodash"; import { TreeviewItem } from '../../ngx-treeview'; import { uniqBy, flatten, compact } from "lodash" @Component({ selector: 'app-datatable, [app-datatable]', templateUrl: './datatable.component.html', styleUrls: ['./datatable.component.sass'] }) export class DatatableComponent implements OnInit { showCD: boolean = true constructor(private datatableService: DatatableService, private contextMenuService: ContextMenuService) { } ngOnInit() { } @Input() componentsTemplate: TemplateRef<DatatableItemTemplateContext> @Input() datatableCM: ContextMenuComponent private _items: Array<TreeviewItem> = [] @Input() set items(value: Array<TreeviewItem>) { this._items = value this.columns.forEach(col => { if (col.inputType == InputType.MultiSelect || col.inputType == InputType.Select) { col.items = uniqBy(compact(flatten(this._items.map(item => item.entity[col.key]))), 'id') } }) } get items(): Array<TreeviewItem> { return this._items; } @Input() columns: ColDisplay[] = [] @Input() filters: Array<{ [key: string]: Expression }> = [] /* public get columns(): any { return this._columns } */ @ViewChild('selectcol', { static: true }) selectcol: NgSelectComponent keys = Object.keys inputType = InputType selections: { [key: number]: boolean } = {} page = 1 private filterItem(item: ITrackable, keys: Array<string>, filter: any): boolean { return keys.every(k => { const col = find(this.columns, { key: k }) if (col.inputType === InputType.Text || col.inputType === InputType.Textarea) { const values: Array<string> = filter[k].value.trim().toLowerCase().split(';') switch (filter[k].equality) { case 'contains': return values.some(v => isNotEmpty(v) && isNotEmpty(item[k]) && item[k].toLowerCase().indexOf(v.trim()) >= 0) case 'startsWith': return values.some(v => isNotEmpty(v) && isNotEmpty(item[k]) && item[k].toLowerCase().indexOf(v.trim()) == 0) case 'endsWith': return values.some(v => isNotEmpty(v) && isNotEmpty(item[k]) && item[k].toLowerCase().endsWith(v.trim())) case 'notContains': return values.every(v => isNotEmpty(v) && isNotEmpty(item[k]) && item[k].toLowerCase().indexOf(v.trim()) < 0) case 'notEquals': return values.every(v => isNotEmpty(v) && isNotEmpty(item[k]) && item[k].toLowerCase() != v.trim()) case 'equals': return values.some(v => isNotEmpty(v) && isNotEmpty(item[k]) && item[k].toLowerCase() == v.trim()) default: return true } } else if (col.inputType === InputType.Select) { if (item[k]) { switch (filter[k].equality) { case 'in': return filter[k].value.indexOf(item[k].id) >= 0 case 'notIn': return filter[k].value.indexOf(item[k].id) < 0 } } else return false } else if (col.inputType === InputType.MultiSelect) { if (!isNotEmpty(filter[k].value)) return true switch (filter[k].equality) { case 'in': return filter[k].value.some(v => item[k].find(i => i.id == v)) case 'notIn': return filter[k].value.some(v => !item[k].find(i => i.id == v)) case 'inAll': return filter[k].value.every(v => item[k].find(i => i.id == v)) } } }) } get filteredItems(): Array<TreeviewItem> { console.log(this.filters) let fItems = [] this.filters.forEach((filter) => { const filteredKeys: Array<string> = Object.keys(filter).filter(k => isNotEmpty(filter[k].value)) const items = filteredKeys.length > 0 ? this.items.filter(i => this.filterItem(i.entity, filteredKeys, filter)) : this.filters.length > 1 ? [] : this.items fItems = fItems.concat(items) }) fItems = fItems.filter((item, index) => fItems.findIndex(fi => fi.entity.id == item.entity.id) == index) return fItems } onDragStart(event: DragEvent) { } onDragged(item: ColDisplay) { const index = this.columns.indexOf(item); this.columns.splice(index, 1); } onDrop(event: DndDropEvent, list?: any[]) { let index = event.index; if (typeof index === "undefined") { index = list.length; } let i = -1, j = 0 this.columns.every(l => { i++ if (l.show) j++ return j <= (index - 3) }) this.columns.splice(i, 0, event.data) this.showCD = false setTimeout(a => this.showCD = true) } onDragEnd(event: DragEvent) { } sorting(index: number) { if (this.columns[index].sort == 0) { this.columns.forEach(cd => { cd.sort = 0 }) this.columns[index].sort = 1 } else this.columns[index].sort = - this.columns[index].sort } } <file_sep>import { Component, OnInit, EventEmitter, Output, Input } from '@angular/core'; import { List } from '../../models/list.model'; import { AccountDataListService } from '../account-data-list.service'; import { Folder } from '../../models/folder.model'; import { Table } from 'src/app/enums/table.enum'; import { getObjectCopy } from 'src/app/helpers/object.helper'; import { AccountDataFolderableService } from '../../account-data-folder/account-data-folder.service'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; @Component({ selector: 'app-account-data-list-edit', templateUrl: './account-data-list-edit.component.html', styleUrls: ['./account-data-list-edit.component.sass'], providers: [AccountDataFolderableService] }) export class AccountDataListEditComponent implements OnInit { constructor( private listService: AccountDataListService, private folderService: AccountDataFolderableService ) { } @Input() parent: Folder = null @Input('model') oModel: List = new List() @Input() dependant: boolean = false @Output() close: EventEmitter<any> = new EventEmitter() Table = Table public model: List public items: TreeviewItem[] = [] public edit: boolean created: boolean ngOnInit() { this.model = getObjectCopy(this.oModel) this.edit = this.created = this.model.showEdit if (!this.edit) this.model.dependant = this.dependant this.folderService.getFolderTreeView(-1, Table.List).subscribe(r=>this.items = r) this.model.parent = this.parent } create() { (this.edit ? this.listService.editList(this.parent.id, this.model) : this.listService.createList(this.parent.id, this.model)).subscribe(r => this.cancel()) } cancel() { this.close.emit() } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using MiniS.Areas.Data.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master; using MiniS.Areas.Master.Enums; using MiniS; using MiniS.Areas.Services; using MiniS.Helpers; namespace MiniS.Areas.Data.Services { public class DatabaseService : AccountGroupService<Database, Folder> { public DatabaseService(AppDbContext dbContext, ILogger<DatabaseService> logger, IStringLocalizer<SharedResource> localizer, IParentableStore<Database, Folder> parentableStore, FolderService folderService) : base(dbContext, logger, localizer, parentableStore, folderService) { } protected override Table _table => Table.Database; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using MiniS.Areas.Data.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master; using MiniS.Areas.Master.Enums; using MiniS; using MiniS.Areas.Services; using MiniS.Helpers; namespace MiniS.Areas.Data.Services { public class FieldService : ParentableService<Field, Database> { public FieldService(AppDbContext dbContext, ILogger<FieldService> logger, IStringLocalizer<SharedResource> localizer, IParentableStore<Field,Database> parentableStore, DatabaseService databaseService) : base(dbContext,logger, localizer, parentableStore, databaseService) { } protected override Table _table => Table.Field; protected override Field PopulateCreateModel(Field model) { base.PopulateCreateModel(model); MODEL.Type = model.Type; MODEL.RelatedFieldId = model.RelatedFieldId; MODEL.ListId = model.ListId; return MODEL; } /* private int GetFirstNotIn(List<Field> fields, int start = 0) { return fields.Any(f => f.ColumnId == start) ? GetFirstNotIn(fields, start + 1) : start; } */ } }<file_sep>using Microsoft.AspNetCore.Mvc; using MiniS.Areas.Services; namespace MiniS.Areas.Master { public abstract class ValidationAction : IValidationAction{ public bool Failed {get; set;} = true; public IActionResult Result {get; set;} public abstract IActionResult Validate<P>(IParentableService<P> service, ControllerBase controller); } public interface IValidationAction { IActionResult Result { get; set; } bool Failed { get; set; } IActionResult Validate<P>(IParentableService<P> service, ControllerBase controller); } public class ValidationActionFacade<P> : IValidationActionFacade{ private readonly IParentableService _service; private readonly ControllerBase _controller; public ValidationActionFacade(IParentableService service, ControllerBase controller){ _service = service; _controller = controller; } public IActionResult Validate(){ return null; } } public interface IValidationActionFacade { } }<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { Table } from 'src/app/enums/table.enum'; import { ITrackable } from '../../base-model/trackable.model'; @Component({ selector: 'app-treeview-select', templateUrl: './treeview-select.component.html', styleUrls: ['./treeview-select.component.sass'] }) export class TreeviewSelectComponent implements OnInit { constructor() { } public Table = Table @Input() items: Array<TreeviewItem> @Input() multi: boolean = false @Output() selectedChange: EventEmitter<any> = new EventEmitter() public onSelect = (selected: ITrackable[]) => this.selectedChange.emit(selected) ngOnInit() { } toggleCheck(item: TreeviewItem, event: any) { event.preventDefault() if (!this.multi) this.items = this.items.map(item => { item.setCheckedRecursive(false) return item }) item.checked = !item.checked; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Folder } from '../../models/folder.model'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { Table } from 'src/app/enums/table.enum'; import { AccountDataFolderableService } from '../../account-data-folder/account-data-folder.service'; @Component({ selector: 'app-account-data-list-folder-display', templateUrl: './account-data-list-folder-display.component.html', styleUrls: ['./account-data-list-folder-display.component.sass'] }) export class AccountDataListFolderDisplayComponent implements OnInit { constructor(private route: ActivatedRoute, private folderService: AccountDataFolderableService, private router: Router) { } public parents: Folder[] public children: TreeviewItem public account: string public Table = Table public ngOnInit() { this.account = this.folderService.account this.route.params.subscribe(routeParams => { this.folderService.goTo(routeParams.id, Table.List).subscribe(r => { this.parents = r[1] this.children = r[0] }) } ) } public goTo(id: number, to: 'form' | 'folder' = 'folder') { this.router.navigateByUrl(`/${this.account}/data/list/${to}/${id}`) } } <file_sep>/* using System.Linq; using System.Threading.Tasks; using MiniS.Areas.Data.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using Microsoft.EntityFrameworkCore; using MiniS.Areas.Master.Enums; using System.Collections.Generic; using MiniS.Areas.Identity.Models; using MiniS.Areas.Models; namespace MiniS.Areas.Data.Repositories { public class StepperRepository { private AppDbContext _dbContext; public StepperRepository( AppDbContext dbContext ) { _dbContext = dbContext; } public Task<Stepper> GetStepper(long id, long accountId) { return _dbContext.Steppers.Where(f => f.Id == id && f.AccountId == accountId).FirstOrDefaultAsync(); } public Task<List<Stepper>> GetSteppers(long parent, AccountUser authUser) { /* Fetch all folders belonging to the current account and child of the parent folder return _dbContext.Steppers.Where(f => f.Account.Id == authUser.AccountId && f.FormId == parent).ToListAsync(); } public async Task<Stepper> Create(Stepper stepper, Stepper model, long formId, AccountUser authUser) { stepper.FormId = formId; stepper.Name = model.Name; stepper.Order = model.Order; await _dbContext.Steppers.AddAsync(stepper); await _dbContext.SaveChangesAsync(authUser); await _dbContext.SaveChangesAsync(); return stepper; } public async Task<Stepper> Update(Stepper stepper, Stepper model, long formId, AccountUser authUser) { stepper.Name = model.Name; stepper.Order = model.Order; _dbContext.Steppers.Update(stepper); await _dbContext.SaveChangesAsync(authUser); await _dbContext.SaveChangesAsync(); return stepper; } public Task Delete(Stepper stepper) { _dbContext.Steppers.Remove(stepper); return _dbContext.SaveChangesAsync(); } public async Task<Stepper[]> UpdateOrder(long parent, long accountId, long[] ids) { Stepper[] steppers = new Stepper[ids.Length]; Stepper stepper = null; for (int i = 0; i < ids.Length; i++) { stepper = await GetStepper(ids[i], accountId); stepper.Order = i; _dbContext.Update(stepper); steppers[i] = stepper; } await _dbContext.SaveChangesAsync(); return steppers; } } } */<file_sep>import { Component, OnInit, Input } from '@angular/core'; import { AccountService } from 'src/app/account/account.service'; import { Table } from 'src/app/enums/table.enum'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { ColDisplay } from 'src/app/widgets/datatable/datatable.interface'; @Component({ selector: 'app-list-item, [app-list-item]', templateUrl: './list-item.component.html', styleUrls: ['./list-item.component.sass'] }) export class ListItemComponent implements OnInit { constructor(private accountService: AccountService) { } @Input() item: TreeviewItem @Input() columns: any[] get vColumns(): ColDisplay[] { return this.columns.filter(c => c.show) } @Input('datatable') datatable = false public account: string public Table = Table ngOnInit() { this.account = this.accountService.account.normalizedName; } } <file_sep>import { Injectable } from '@angular/core'; import { Database } from './database.model'; import { AccountService } from 'src/app/account/account.service'; import { HttpClient } from '@angular/common/http'; import { FolderableService } from 'src/app/master/states/folderable.service'; import { Folder } from '../../folder/folder.model'; import { Table } from 'src/app/enums/table.enum'; @Injectable({ providedIn: 'root' }) export class DatabaseService extends FolderableService<Database> { protected type = Table.Database protected getFolderUrl(path?: string) { let url = [`api/${this.accountService.account.normalizedName}/data/database/${this.parentId}/folder`] if (path) url.push(path) return url.join('/') } public constructor(protected http: HttpClient, private accountService: AccountService) { super() } protected getUrl(path?: string) { let url = [`api/${this.accountService.account.normalizedName}/data/${this.parentId}/database`] if (path) url.push(path) return url.join('/') } // remove(id: ID) { // this.treview.remove(id); // } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using MiniS.Areas.Master.Models; using MiniS.Areas.Master.Validators; namespace MiniS.Areas.Data.Models { public class Field : Parentable<Database> { public List<FieldAttribute> FieldAttributes { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Guid { get; set; } [ValidEnum] public FieldType Type { get; set; } public long? ListId { get; set; } public List List { get; set; } public long? RelatedFieldId { get; set; } public Field RelatedField { get; set; } [InverseProperty("RelatedField")] public List<Field> RelatedFields { get; set; } [NotMapped] public long ListParentId {get;set;} } public class ListField : Field { } public class AddressField : Field { public long? CountryListId { get; set; } public List CountryList { get; set; } public long? StateListId { get; set; } public List StateList { get; set; } public long? CityListId { get; set; } public List CityList { get; set; } public long? StreetListId { get; set; } public List StreetList { get; set; } public bool Primary { get; set; } } public class FieldConfiguration : ParentableConfiguration<Field, Database> { public override void Configure(EntityTypeBuilder<Field> builder) { base.Configure(builder); builder.Property(e => e.Guid).HasDefaultValueSql("hex( randomblob(4)) || '-' || hex( randomblob(2))|| '-' || '4' || substr( hex( randomblob(2)), 2) || '-'|| substr('AB89', 1 + (abs(random()) % 4) , 1) ||substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6))"); //replace by NEWID in sql server } } } public enum FieldType { // Standat type bigint, numeric, varchar, text, date, datetime, time, //advanced type list, dependentList, Address = 100, Contact = 110 }<file_sep> using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Controllers; using MiniS.Areas.Master.Enums; namespace MiniS.Areas.Data.Controllers { [Route("api/{account}/data/{parentId}/List")] public class ListController : GroupableController<List,Folder, ListService> { /* protected override ListService _service => new ListService (_authService.GetAuthUser ()); protected override FolderableService _parentService => new FolderableService (_authService.GetAuthUser (), Table.List); */ public ListController(ListService service, FolderService parentService, AuthorizationService authService) : base(service, authService) { } protected override Access _access => Access.List; } }<file_sep>import { InputType } from 'src/app/enums/input-type.enum'; import { ITrackable } from 'src/app/master/base-model/trackable.model'; export interface Expression { value: any, equality: string } export interface Filter{ [id:string]: Expression } export interface ColDisplay { key: string, display: string, show: boolean, sort: number, inputType: InputType, items: ITrackable[] } export interface Column { show: boolean, inputType: InputType, items: ITrackable[] } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { AccountService } from 'src/app/account/account.service'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { Table } from 'src/app/enums/table.enum'; import { contextmenu as contextmenu } from './group.const' import { icon } from 'src/app/master/components/icon/icon.component'; import { GROUPICON } from 'src/app/master/components/icon/icon.const'; import { DisplayView } from 'src/app/master/components/display-view/nav-view.component'; @Component({ selector: 'app-group-item, [app-group-item]', templateUrl: './group-item.component.html', styleUrls: ['./group-item.component.sass'] }) export class GroupItemComponent implements OnInit { constructor(private accountService: AccountService) { } @Input() item: TreeviewItem @Input() columns: any[] = [] @Input() display: DisplayView = DisplayView.inline public folderContextmenu = [ { icon: "account-multiple-plus", action: (item) => item.entity.showAddFile = true, text: "Add Group", visible: (item) => true } ] public contextmenu = contextmenu public account: string = this.accountService.account.normalizedName; public Table = Table public folderLink: string = `/${this.account}/security/group/folder` public itemLink: string = `/${this.account}/security/user` public icon: icon = GROUPICON ngOnInit() { } } <file_sep>import { Injectable, Input } from '@angular/core'; import { Filter, ColDisplay, Column } from './datatable.interface'; @Injectable({ providedIn: 'root' }) export class DatatableService { constructor() { } public filters: Array<Filter> = [{}] } <file_sep>import { Table } from "src/app/enums/table.enum"; import { Parentable } from 'src/app/master/base-model/parentable.model'; export class Folder extends Parentable<Folder> { public type: Table public allGroup: boolean = true } <file_sep>namespace MiniS.Areas.Master.Enums { public enum Table { None, Account, User, Group, AccessTemplate, Folder, Database, List, ListItem, Form, Field, DatabaseData } }<file_sep> export const contextmenu = [ { icon: "account-multiple-plus", action: (item) => item.entity.showAdd = true, text: "Create Group", visible: (item)=> true }, { icon: "account-multiple-pencil", action: (item) => item.entity.showEdit = true, text: "Edit Group", visible: (item)=> true }, { icon: "account-plus", action: (item) => item.entity.showAddFile = true, text: "Add User", visible: (item)=> true }, ] <file_sep>import { Component, OnInit } from '@angular/core'; import { Group } from '../state/group.model'; import { Folder } from 'src/app/account/data/folder/folder.model'; import { FolderableEditComponent } from 'src/app/master/states/folderable-edit.component'; import { Table } from 'src/app/enums/table.enum'; @Component({ selector: 'app-group-edit', templateUrl: './group-edit.component.html', styleUrls: ['./group-edit.component.sass'] }) export class GroupEditComponent extends FolderableEditComponent<Group, Folder> implements OnInit { ngOnInit() { this.type = Table.Group this.model = new Group().clone(this.oModel) super.ngOnInit() } } <file_sep>import { Injectable } from '@angular/core'; import { ID } from '@datorama/akita'; import { HttpClient } from '@angular/common/http'; import { StepperStore } from './stepper.store'; import { Stepper } from './stepper.model'; import { tap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class StepperService { constructor(private stepperStore: StepperStore, private http: HttpClient) { } get() { return this.http.get<Stepper[]>('https://api.com').pipe(tap(entities => { this.stepperStore.set(entities); })); } add(stepper: Stepper) { this.stepperStore.add(stepper); } update(id, stepper: Partial<Stepper>) { this.stepperStore.update(id, stepper); } remove(id: ID) { this.stepperStore.remove(id); } } <file_sep> using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Data.Models { public class List : Groupable<Folder> { public long? ParentListId { get; set; } public List ParentList { get; set; } [InverseProperty("ParentList")] public List<List> ListChildren { get; set; } [InverseProperty("Parent")] public List<ListItem> ListItems { get; set; } public bool Dependant { get; set; } } public class ListConfiguration : GroupableConfiguration<List,Folder> { } }<file_sep>import { Injectable } from '@angular/core'; import { Form } from './form.model'; import { EntityState, EntityStore, StoreConfig } from '@datorama/akita'; export interface FormState extends EntityState<Form> {} @Injectable({ providedIn: 'root' }) @StoreConfig({ name: 'form' }) export class FormStore extends EntityStore<FormState> { constructor() { super(); } } <file_sep>import { Injectable } from '@angular/core'; import { ParentableService } from '../../account.service'; import { AccountDataFolderableService } from '../account-data-folder/account-data-folder.service'; import { HttpClient } from '@angular/common/http'; import { Db } from './models/db'; import { tap } from 'rxjs/operators'; import { Table } from 'src/app/enums/table.enum'; import { Field } from './models/field'; import { Observable } from 'rxjs'; import { Form } from './models/form'; @Injectable({ providedIn: 'root' }) export class AccountDataDbService { constructor( private accountService: ParentableService, private folderService: AccountDataFolderableService, private http: HttpClient ) { } public loading = false public account: string = this.accountService.account.normalizedName createDatabase(parent: Number, model: Db): Observable<Db> { return this.http.post<Db>(`api/${this.account}/data/${parent}/database`, model) // .pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } editDatabase(parent: Number, model: Db): Observable<Db> { return this.http.put<Db>(`api/${this.account}/data/${parent}/database/${model.id}`, model) // .pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } editForm(parent: Number, model: Form):Observable<Form> { return this.http.put<Form>(`api/${this.account}/data/${parent}/form/${model.id}`, model) //.pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } getForms(parent: Number): Observable<Array<Form>> { return this.http.get<Array<Form>>(`api/${this.account}/data/${parent}/form`) //.pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } createForm(parent: Number, model: Form): Observable<Form> { return this.http.post<Form>(`api/${this.account}/data/${parent}/form`, model) //.pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.Database).subscribe())) } getFields(databaseId: Number): Observable<Array<Field>> { this.loading = true return this.http.get<Array<Field>>(`api/${this.account}/data/${databaseId}/field`) .pipe(tap(r => this.loading = false)) } createField(databaseId: Number, model: Field): Observable<Field> { this.loading = true return this.http.post<Field>(`api/${this.account}/data/${databaseId}/field`, model) .pipe(tap(r => this.loading = false)) } updateField(databaseId: Number, id: number, model: Field): Observable<Field> { this.loading = true return this.http.put<Field>(`api/${this.account}/data/${databaseId}/field/${id}`, model) .pipe(tap(r => this.loading = false)) } deleteField(databaseId: Number, id: number): Observable<Field> { this.loading = true return this.http.delete<Field>(`api/${this.account}/data/${databaseId}/field/${id}`) .pipe(tap(r => this.loading = false)) } } /* createList(parent: Number, model: List) { return this.http.post(`api/${this.account}/data/${parent}/list`, model).pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.List).subscribe())) } editList(parent: Number, model: List) { return this.http.put(`api/${this.account}/data/${parent}/list/${model.id}`, model).pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.List).subscribe())) } createListItem(listId: number, model: ListItem): Observable<ListItem> { return this.http.post<ListItem>(`api/${this.account}/data/${listId}/list-item`, model).pipe( tap(r => this.listItems.unshift(r))) } editListItem(listId: number, model: ListItem): Observable<ListItem> { return this.http.put<ListItem>(`api/${this.account}/data/${listId}/list-item/${model.id}`, model).pipe( tap(r => this.listItems[this.listItems.map(li => li.id).indexOf(model.id)] = r)) } goToList(listId: number = null, pListId: number = null) { this.listItems = this.pListItems = [] listId = listId == null ? this.list.id : listId pListId = pListId == null ? this.list.pListId : pListId return forkJoin( this.http.get<ListItem[]>(`api/${this.account}/data/${listId}/list-item`), this.list.dependant ? this.http.get<ListItem[]>(`api/${this.account}/data/${pListId}/list-item`) : of(undefined) ).pipe(tap( r => { this.listItems = r[0] this.pListItems = r[1] } )) } getListItems(listId: number, pListItem=null) { return this.http.get<ListItem[]>(`api/${this.account}/data/${listId}/list-item`, {params: {pListItem}}) .pipe(tap(r => this.listItems = r )) } */<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { Form } from '../../models/form'; import { Stepper } from '../../models/stepper'; import { AccountDataDbFormService } from '../account-data-db-form.service'; import { AccountDataDbService } from '../../account-data-db.service'; import { Field, FieldAttribute } from '../../models/field'; import { remove } from 'lodash' import { ToastrService } from 'src/app/widgets/ngx-toastr/public_api'; import { DndDropEvent } from 'src/app/widgets/ngx-darg-drop/dnd-dropzone.directive'; @Component({ selector: 'app-account-data-db-form-field-attribute', templateUrl: './account-data-db-form-field-attribute.component.html', styleUrls: ['./account-data-db-form-field-attribute.component.sass'] }) export class AccountDataDbFormFieldAttributeComponent implements OnInit { constructor(private formService: AccountDataDbFormService, private toastrService: ToastrService, private dbService: AccountDataDbService) { } @Input() public form: Form @Output() close: EventEmitter<any> = new EventEmitter<any>() public steppers: Array<Stepper> = [] public fields: Array<Field> = [] public fieldAttributes: Array<FieldAttribute> = [] public stepperOrder: Array<number> = [] public currentStepper: Stepper public selected: Array<number> = [] public index: number public ngOnInit() { this.formService.getSteppers(this.form.id).subscribe(r => { this.steppers = r.sort((a, b) => a.order - b.order) if (this.steppers.length > 0) this.currentStepper = this.steppers[0] }) this.formService.getFieldAttributes(this.form.id).subscribe(r => { this.fieldAttributes = r this.selected = r.map(fa => fa.field.id) }) this.dbService.getFields(this.form.parentId).subscribe(r => this.fields = r) } public addStepper() { this.currentStepper = new Stepper("stepper1", this.steppers.length) this.steppers.push(this.currentStepper) } public delete(i) { /* const index = this.steppers.findIndex(s => s.id = stepper.id) this.steppers.splice(index, 1) */ this.steppers.splice(i, 1) this.updateOrder(i) } public cancel() { this.close.emit() } private updateOrder(index: number) { this.formService.updateStepperOrder(this.form.id, this.steppers.map(s => s.id)) .subscribe(r => { this.steppers = r this.currentStepper = r[Math.min(index, this.steppers.length - 1)] this.toastrService.success("the steppers were successefuly ordrerd and updated to the database", "order succeeded") }) } public onAdd(stepper: Stepper) { this.steppers[this.steppers.length - 1] = this.currentStepper = stepper } public addToFieldAttributes(field: Field) { let fieldAttribute: FieldAttribute = new FieldAttribute(field.name, field, this.form, this.currentStepper) this.fieldAttributes.push(fieldAttribute) this.selected = this.fieldAttributes.map(fa => fa.field.id) } public removeFieldAttributes(index: number) { remove(this.selected, s => s == this.fieldAttributes[index].fieldId) this.selected = [...this.selected] this.fieldAttributes.splice(index, 1) } /* public notIn(field: Field){ if(this.fieldAttributes.length>0) return !this.fieldAttributes.findIndex(fa=>fa.fieldId==field.id) else return true } */ onDragStart(event: DragEvent) { } public onDragged(index: number) { this.steppers.splice(index, 1); this.updateOrder(index < this.index ? this.index - 1 : this.index) } onDrop(event: DndDropEvent) { this.index = event.index if (typeof this.index === "undefined") this.index = this.steppers.length this.steppers.splice(this.index, 0, event.data) } } <file_sep>import { TestBed } from '@angular/core/testing'; import { AccountSecurityAuthService } from './account-security-auth.service'; describe('AccountSecurityAuthService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: AccountSecurityAuthService = TestBed.get(AccountSecurityAuthService); expect(service).toBeTruthy(); }); }); <file_sep>using System; namespace MiniS.Areas.Master { public class ParentableStore<M, P> : IParentableStore<M, P> { public M Model { get; set; } = (M)Activator.CreateInstance(typeof(M)); public P Parent { get; set; } = default(P); } public interface IParentableStore<M, P> { M Model { get; set; } P Parent { get; set; } } }<file_sep>import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; import { Observable, of, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { ToastrService } from '../widgets/ngx-toastr/public_api'; /** Pass untouched request through to the next request handler. */ @Injectable() export class ToasterInterceptor implements HttpInterceptor { constructor(private toastr: ToastrService) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req) .pipe( catchError(e => { console.log("rrror2", e) switch (e.status) { case 500: { this.toastr.error("internal error <b>please contact Administrator</b>", 'Internal error', { enableHtml: true, positionClass: 'toast-bottom-center' }) break } default: { const errors = e.error.hasOwnProperty("errors") ? e.error.errors : e.error; const message = Object.values(errors).join('<br>') this.toastr.warning(message, 'bad entries', { enableHtml: true, positionClass: 'toast-bottom-center' }) break } } return throwError(e) })) } }<file_sep>import { TestBed } from '@angular/core/testing'; import { AccountDataDbService } from './account-data-db.service'; describe('AccountDataDbService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: AccountDataDbService = TestBed.get(AccountDataDbService); expect(service).toBeTruthy(); }); }); <file_sep>import { NullAstVisitor } from '@angular/compiler'; export { FieldTYPES } const FieldTYPES = { text: { SQLTYPE: 'text', DISPLAY: 'textarea', INPUT: 'textarea', }, nvarchar: { SQLTYPE: 'nvarchar', DISPLAY: 'text', INPUT: 'text', MINMAXTYPE: 'number', MASK: {content:"", prefix: "", suffix:"", dropSpecialCharacter:false, showMask: false, clearIfNotMatch: false}, MIN: 0, MAX: 400 }, tinyint: { SQLTYPE: 'tinyint', DISPLAY: 'Tiny Number (0 to 255)', INPUT: 'number', MINMAXTYPE: 'number', MIN: 0, MAX: 255 }, smallint: { SQLTYPE: 'smallint', DISPLAY: 'Small number (-32,768 to 32,767)', INPUT: 'number', MINMAXTYPE: 'number', MIN: -32768, MAX: 32767 }, int: { SQLTYPE: 'int', DISPLAY: 'Number (-2,147,483,648 to 2,147,483,647)', INPUT: 'number', MINMAXTYPE: 'number', MIN: -2147483648, MAX: 2147483647 }, bigint: { SQLTYPE: 'bigint', DISPLAY: 'Integer number', INPUT: 'number', STEP: 1, MIN: -9223372036854775808, MAX: 9223372036854775807, MASK: {content:"", prefix: "", suffix:"", dropSpecialCharacter:false, showMask: false}, }, decimal: { SQLTYPE: 'decimal', DISPLAY: 'decimal number', INPUT: 'number', STEP: 2, MIN: -9999999.9999999, MAX: 9999999.9999999, MASK: {content:"", prefix: "", suffix:"", dropSpecialCharacter:false, showMask: false, clearIfNotMatch: false}, }, list: { SQLTYPE: 'nvarchar', DISPLAY: 'List', INPUT: 'Select', STEP: 1, MIN: -9223372036854775808, MAX: 9223372036854775807, MASK: {content:"", prefix: "", suffix:"", dropSpecialCharacter:false, showMask: false}, }, dlist: { SQLTYPE: 'nvarchar', DISPLAY: 'List', INPUT: 'Select', STEP: 1, MIN: -9223372036854775808, MAX: 9223372036854775807, MASK: {content:"", prefix: "", suffix:"", dropSpecialCharacter:false, showMask: false}, }, DATE: { SQLTYPE: 'date', DISPLAY: 'Date', INPUT: 'date', KEY: 'DATE', MINMAXTYPE: 'date' }, TIME: { SQLTYPE: 'time', DISPLAY: 'Time', INPUT: 'time', KEY: 'TIME', MINMAXTYPE: 'time' }, DATETIMELOCAL: { SQLTYPE: 'datetime', DISPLAY: 'Locasl Date & Time', INPUT: 'datetime-local ', KEY: 'DATETIMELOCAL', MINMAXTYPE: 'datetime-local' }, CHECKBOX: { SQLTYPE: 'bit', DISPLAY: 'Checkbox', INPUT: 'checkbox', KEY: 'CHECKBOX', MINMAXTYPE: null }, COLOR: { SQLTYPE: 'color', DISPLAY: 'Color', INPUT: 'color', KEY: 'COLOR', MINMAXTYPE:'color' }, } <file_sep>using System; using System.Globalization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; namespace MiniS.Areas.Master.Controllers { [Route("api/language")] public class LanguageController : ControllerBase { // private readonly IOptions<RequestLocalizationOptions> _locOptions; public LanguageController( // IOptions<RequestLocalizationOptions> locOptions ) { // _locOptions = locOptions; } /* [HttpGet("all")] public List<SelectListItem> GetAll() { return _locOptions.Value.SupportedUICultures .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName, Selected = (c.Name == CultureInfo.CurrentCulture.Name) }) .ToList(); } */ [HttpGet] public SelectListItem Get() { var c = CultureInfo.CurrentCulture; return new SelectListItem { Value = c.Name, Text = c.DisplayName, Selected = true }; } [HttpPost] public ActionResult<SelectListItem> SetLanguage(SelectListItem culture) { Response.Cookies.Append( CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture.Value)), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) } ); return culture; } } }<file_sep>import { Component, OnInit, Input, Output, EventEmitter, Injector } from '@angular/core'; import { getObjectCopy } from 'src/app/helpers/object.helper'; import { FactoryService } from 'src/app/master/states/factory.service'; import { Table } from 'src/app/enums/table.enum'; import { Folder } from './folder.model'; import {isNil} from 'lodash' @Component({ selector: 'app-folder-edit', templateUrl: './folder-edit.component.html', styleUrls: ['./folder-edit.component.sass'] }) export class FolderEditComponent implements OnInit { constructor(private injector: Injector) { } @Input() type: Table @Input() parent: Folder; @Input("model") oModel: Folder @Output() close: EventEmitter<any> = new EventEmitter(); public edit: boolean = false; public created: boolean = false; public model: Folder; private service: any public ngOnInit() { console.log("type", this.type) console.log(this.parent) this.model = new Folder().clone(this.oModel); this.service = new FactoryService(this.injector).get(this.type) this.model.parent = this.parent console.log(this.model) this.service.updateParentId((this.parent && this.parent.id) || 0) this.edit = this.model.showEdit; } create() { (this.edit ? this.service.updateFolder(this.model.id, this.model) : this.service.addFolder(this.model) ).subscribe(r => { this.oModel = this.model = r; }); } } <file_sep>import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core'; import { getObjectCopy } from 'src/app/helpers/object.helper'; import { ListService } from '../state/list.service'; import { List } from '../state/list.model'; import { Folder } from '../../folder/folder.model'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { Observable } from 'rxjs'; @Component({ selector: 'app-list-edit', templateUrl: './list-edit.component.html', styleUrls: ['./list-edit.component.sass'] }) export class ListEditComponent implements OnInit { constructor( private listService: ListService ) { } @Input() parent: Folder @Input('model') oModel: List = new List() @Input() dependant: boolean = false @Output() close: EventEmitter<any> = new EventEmitter() public items: Observable<TreeviewItem[]> public model: List public edit: boolean created: boolean ngOnInit() { this.model = getObjectCopy(this.oModel) this.listService.updateParentId(this.parent.id) this.edit = this.created = this.model.showEdit if (!this.edit) this.model.dependant = this.dependant this.items = this.listService.treeview$ } create() { (this.edit ? this.listService.update(this.model.id, this.model) :this.listService.add(this.model) ).subscribe(r => { this.oModel = this.model = r; }); } } <file_sep> using Microsoft.AspNetCore.Identity; namespace MiniS.Areas.Identity.Models { public class Role : IdentityRole<long> { } }<file_sep>import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { ITrackable } from 'src/app/master/base-model/trackable.model'; import { Table } from 'src/app/enums/table.enum'; @Component({ selector: 'app-user-treeview', templateUrl: './user-treeview.component.html', styleUrls: ['./user-treeview.component.sass'] }) export class UserTreeviewComponent implements OnInit { constructor() { } @Input() public items: TreeviewItem[] @Input() public loading: boolean @Input() public multi:boolean =true @Input() public checkbox: boolean = false @Output() public selectedChange: EventEmitter<ITrackable[]> = new EventEmitter() public onSelect = (selected: ITrackable[]) => this.selectedChange.emit(selected) public type: Table = Table.User ngOnInit(): void { } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Table } from 'src/app/enums/table.enum'; import { ActivatedRoute } from '@angular/router'; import { ListService } from '../state/list.service'; import { InputType } from 'src/app/enums/input-type.enum'; import { Columns } from 'src/app/master/base-model/groupable.model'; @Component({ selector: 'app-list-display-page', templateUrl: './list-display-page.component.html', styleUrls: ['./list-display-page.component.sass'] }) export class ListDisplayPageComponent implements OnInit { constructor( private route: ActivatedRoute, private listService: ListService, ) { } public showDT = false public columns = [...Columns, {key: "parentList", display: "parent List", items:[], show: true, sort:0, inputType: InputType.Select}] public ngOnInit() { this.route.params.subscribe(routeParams => { this.listService.updateParentId(routeParams.id); this.listService.getCurrentItems(routeParams.id).subscribe() // this.listService.getParents().subscribe(); }); } public Table = Table get items() { return this.listService.currentItems$ } get parent() { return this.listService.parentEntity$ } get parents() { return this.listService.parents$ } /* get parentsLoading() { return this.listService.loader.setParents$ } get displayItemsLoading() { return this.listService.loader.set$ } */ } <file_sep>/* using System.Linq; using Microsoft.EntityFrameworkCore; using MiniS.Areas.Identity.Data; using MiniS.Areas.Master.Enums; namespace MiniS.Areas.Helpers { abstract class AbstractEntityCreator { public abstract IQueryable GetEntity (Table table); } class EntityCreator : AbstractEntityCreator { private readonly AppDbContext _dbContext; public EntityCreator(AppDbContext appDbContext){ _dbContext = appDbContext; } public override IQueryable GetEntity (Table table) { switch (table) { case Table.Database: return _dbContext.Databases; case Table.List: return _dbContext.Lists.Include (l => l.CList).Include (l => l.PList); default: return _dbContext.Databases; } } } } */<file_sep> import { Columns as cols } from './identificable.model' import { InputType } from 'src/app/enums/input-type.enum' import { Group } from 'src/app/account/security/group/state/group.model' import { Parentable, IParentable } from './parentable.model' import { IAccountable, Accountable } from './accountable.model' export abstract class Groupable<Parent extends Accountable> extends Parentable<Parent> implements IParentable<Parent> { public groups: Array<Group> public allGroup: boolean = false } export interface IGroupable<Parent extends IAccountable> extends IParentable<Parent> { groups: Array<Group> allGroup: boolean } let Columns = [ ...cols, { key: "groups", display: "Groups", sort: 0, show: true, items: [], inputType: InputType.MultiSelect }, ] export { Columns } <file_sep>using System; using System.Linq; using System.Linq.Expressions; namespace MiniS.Master.Extensions { public static class PredicateBuilder { public static Expression<Func<T, bool>> True<T>() { return f => true; } public static Expression<Func<T, bool>> False<T>() { return f => false; } public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>()); return Expression.Lambda<Func<T, bool>> (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters); } public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>()); return Expression.Lambda<Func<T, bool>> (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters); } static public Expression<Func<TSource, TDestination>> Combine<TSource, TDestination>( params Expression<Func<TSource, TDestination>>[] selectors) { var param = Expression.Parameter(typeof(TSource), "x"); return Expression.Lambda<Func<TSource, TDestination>>( Expression.MemberInit( Expression.New(typeof(TDestination).GetConstructor(Type.EmptyTypes)), from selector in selectors let replace = new ParameterReplaceVisitor( selector.Parameters[0], param) from binding in ((MemberInitExpression)selector.Body).Bindings .OfType<MemberAssignment>() select Expression.Bind(binding.Member, replace.VisitAndConvert(binding.Expression, "Combine"))) , param); } private class ParameterReplaceVisitor : ExpressionVisitor { private readonly ParameterExpression from, to; public ParameterReplaceVisitor(ParameterExpression from, ParameterExpression to) { this.from = from; this.to = to; } protected override Expression VisitParameter(ParameterExpression node) { return node == from ? to : base.VisitParameter(node); } } } }<file_sep>import { Component, OnInit, Input } from '@angular/core'; import { AccountDataListService } from '../account-data-list.service'; import { ListItem } from '../../models/list-item'; import { objectHasLess } from 'src/app/helpers/object.helper'; import { defaultColumns } from './default-columns.const'; import { InputType } from 'src/app/enums/input-type.enum'; import { ParentableService } from 'src/app/account/account.service'; import { AccountSecurityGroupService } from 'src/app/account/security/account-security-group/account-security-group.service'; import { Route, ActivatedRoute } from '@angular/router'; import { flatMap, tap } from 'rxjs/operators'; import { List } from '../../models/list.model'; import { forkJoin, of } from 'rxjs'; @Component({ selector: 'app-account-data-list-item', templateUrl: './account-data-list-item.component.html', styleUrls: ['./account-data-list-item.component.sass'] }) export class AccountDataListItemComponent implements OnInit { constructor(private listService: AccountDataListService, private groupService: AccountSecurityGroupService, private route: ActivatedRoute) { } isCreate = false selections: { [key: number]: boolean } = {} keys = Object.keys inputType = InputType public list: List public listItems: Array<ListItem> = [] public parentListItems: ListItem[] = [] public loading: boolean = true ngOnInit() { this.loading = true this.route.params.subscribe(routeParams => { this.loading = true this.listService.getList(routeParams.id, "true") .subscribe(l => { this.list = l forkJoin( this.listService.getListItems(l.id), (this.list.dependant ? this.listService.getListItems(l.parentListId) : of(undefined)) ).subscribe( r => { this.listItems = r[0] this.afterPLi(r[1]) } ) }) }) } public afterPLi(pli: Array<ListItem>) { this.parentListItems = pli this.defaultCol = Object.assign(defaultColumns, { parentListItem: { show: this.list.dependant, inputType: InputType.Select, items: this.parentListItems }, groups: { show: true, inputType: InputType.MultiSelect, items: this.groupService.groups } }) this.loading = false } public defaultCol: any = {} /* public editselections() { let id = Object.keys(this.selections).find(s => this.selections[s]) if (id) this.users.some(u => { if (u.id == id) { u.showEdit = true return true } }) } public deleteselections() { let id = Object.keys(this.selections).find(s => this.selections[s]) if (id) this.users.some(u => { if (u.id == id) { u.showEdit = true return true } }) } */ get selectionsIsEmpty(): boolean { return objectHasLess(this.selections, 0) } } <file_sep>export function isEmpty(obj) { for (var key in obj) { if (obj.hasOwnProperty(key) && obj[key]) return false; } return true; } export function objectHasLess(obj, count: number) { let i = 0 for (var key in obj) { if (obj.hasOwnProperty(key) && obj[key]) { i++; if (i > count) return false } } return true; } export function getObjectCopy(object: any){ return Object.assign(Object.create(object), object) } export function prop<T, K extends keyof T>(obj: T, key: K) { return obj[key]; } <file_sep>import { Component, OnInit, EventEmitter, Output } from '@angular/core'; import { AccountService } from 'src/app/account/account.service'; import { Router, ActivatedRoute } from '@angular/router'; import { Login } from '../../states/authentication/authentication.model'; import { AuthService } from '../state/auth.service'; @Component({ selector: 'app-auth', templateUrl: './auth.component.html', styleUrls: ['./auth.component.sass'] }) export class AuthComponent implements OnInit { public returnUrl: string; constructor( private route: ActivatedRoute, private router: Router, private authService: AuthService, private accountService: AccountService ) { } @Output() close: EventEmitter<any> = new EventEmitter() model = new Login() account: string ngOnInit() { console.log("queryParams",this.route.snapshot) this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || this.accountService.account.normalizedName; } login() { // login this.authService.login( this.accountService.account.normalizedName, this.model) .subscribe(r => { // Save the authenticated user if login succeed // this.accountService.authUser = r // And redirect the user to the attempted url this.router.navigateByUrl(this.returnUrl) }) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { UserService } from '../state/user.service'; import { Observable } from 'rxjs'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.sass'] }) export class UserComponent implements OnInit { constructor( private userService: UserService ) { } ngOnInit() { this.userService.getTreeview().subscribe() } get loading(){ return this.userService.store.loading$ } get treeview$(): Observable<TreeviewItem[]>{ return this.userService.treeview$ } } <file_sep>using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MiniS.Areas.Admin.Models; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Models { public class EntityGroup : Trackable, IOAccountable, IEquatable<EntityGroup> { public long GroupId { get; set; } public Group Group { get; set; } public Table Table { get; set; } public long EntityId { get; set; } public bool Equals (EntityGroup other) => this.GroupId == other.GroupId && this.Table == other.Table && this.EntityId == other.EntityId; public long AccountId { get; set; } public Account Account { get; set; } } public class EntityGroupConfiguration : TrackableConfiguration<EntityGroup> { public override void Configure (EntityTypeBuilder<EntityGroup> builder) { base.Configure (builder); builder.Property (eg => eg.Table).HasConversion (new EnumToStringConverter<Table> ()); builder.HasKey (t => new { t.GroupId, t.EntityId, t.Table }); builder.HasOne (eg => eg.Group) .WithMany (g => g.EntityGroup) .HasForeignKey (eg => eg.GroupId); } } }<file_sep>import { Component, OnInit } from '@angular/core'; import { Table } from 'src/app/enums/table.enum'; import { UserService } from '../state/user.service'; import { ActivatedRoute } from '@angular/router'; import { DisplayView } from 'src/app/master/components/display-view/nav-view.component'; import { Columns } from 'src/app/master/base-model/trackable.model'; @Component({ selector: 'app-user-display-page', templateUrl: './user-display-page.component.html', styleUrls: ['./user-display-page.component.sass'] }) export class UserDisplayPageComponent implements OnInit { constructor( private route: ActivatedRoute, private userService: UserService, ) { } public account: string public type = Table.User public columns = Columns public display: DisplayView = DisplayView.inline public DisplayView = DisplayView public ngOnInit() { this.account = this.userService.account this.route.params.subscribe(routeParams => { this.userService.updateParentId(routeParams.id); this.userService.getCurrentItems(routeParams.id).subscribe() // this.userService.getParents().subscribe(); }); } public Table = Table get items() { return this.userService.currentItems$ } get parent() { return this.userService.parentEntity$ } get parents() { return this.userService.parents$ } get root() { return this.userService.rootEntity$ } get loading() { return this.userService.store.loading$ } } <file_sep>import { Component, OnInit, EventEmitter, Output, Input, ViewChild, ElementRef } from '@angular/core'; import { FieldType, Field } from '../state/field.model'; import { Database } from '../../database/state/database.model'; import { FieldService } from '../state/field.service'; import { TreeviewItem, TreeviewHelper } from 'src/app/widgets/ngx-treeview'; import { List } from '../../list/state/list.model'; import { Table } from 'src/app/enums/table.enum'; import { InputType } from 'src/app/enums/input-type.enum'; @Component({ selector: 'app-field-item, [app-field-item]', templateUrl: './field-item.component.html', styleUrls: ['./field-item.component.sass'] }) export class FieldItemComponent implements OnInit { @Input() public listTreeView: Array<TreeviewItem>; public updated: boolean = true public relatedFields: Array<Field>; public relatedLists: Array<List> = []; public filteredListTreeview: Array<TreeviewItem>; public FieldType = FieldType; @Input() fields: Array<Field> = [] @Input() create: boolean = false @Output() delete: EventEmitter<any> = new EventEmitter(); @Output() edit: EventEmitter<any> = new EventEmitter(); @Output() close: EventEmitter<any> = new EventEmitter(); public constructor( private fieldService: FieldService ) { } @Input('field') oField: Field; @Input() database: Database; public field: Field public listAlike: boolean public isDList: boolean @Input() forceClose : boolean = false deleteField(force: boolean = false) { this.fieldService .remove(this.oField.id).subscribe() } get fieldNames(): Array<string> { return this.database.fields.map(f => f.name); } public ngOnInit() { this.cloneField() this.isDList = this.oField.type == FieldType.dependentList this.listAlike = this.oField.type == FieldType.list || this.isDList if (this.oField.type == FieldType.list) this.filteredListTreeview = TreeviewHelper.filterTreeviewItems(this.listTreeView, r => r.type == Table.List && !r.entity.dependant) else if (this.oField.type == FieldType.dependentList && !!this.oField.relatedField) this.onDFieldSelected(this.oField.relatedField) this.relatedFields = this.fields.filter( f => f.type == FieldType.dependentList || f.type == FieldType.list ); } public editField(){ this.edit.emit() this.cloneField() this.updated = false } public cloneField(){ this.field = new Field().clone(this.oField) } updateField() { const observable = this.create ? this.fieldService.add(this.field) : this.fieldService.update(this.field.id, this.field) observable.subscribe(r => { this.klose() // this.relatedFields = this.database.fields.filter(f => f.list && f.list.listChildren) }) } public onDFieldSelected(relatedField: Field) { this.filteredListTreeview = TreeviewHelper.filterTreeviewItems(this.listTreeView, r => r.type == Table.List && r.entity.parentListId == relatedField.listId) } public klose() { this.updated = true this.close.emit() } } <file_sep>import { Directive, ElementRef, ContentChild, AfterViewInit, Renderer2 } from '@angular/core'; import { ContextMenuComponent } from './context-menu.component'; @Directive({ selector: '[appContextMenu]' }) export class ContextMenuDirective implements AfterViewInit { ngAfterViewInit(): void { this.renderer.addClass(this.contextMenu.nativeElement, 'context-menu') this.renderer.setStyle(this.contextMenu.nativeElement, 'z-index', 99999 ) this.renderer.listen(this.contextArea.nativeElement, 'contextmenu', this.onContextMenu.bind(this)) this.renderer.listen(document, 'click', e => { this.renderer.removeClass(this.contextMenu.nativeElement, 'shown') }) } @ContentChild('contextMenu', {static:false}) contextMenu: ElementRef @ContentChild('contextArea',{static:false}) contextArea: ElementRef constructor(private elm: ElementRef, private renderer: Renderer2) { } onContextMenu(e: any) { let doc : HTMLElement = document.body as HTMLElement doc.click() e.preventDefault() this.renderer.addClass(this.contextMenu.nativeElement, 'shown') this.renderer.setStyle(this.contextMenu.nativeElement, 'top', e.clientY + 'px') this.renderer.setStyle(this.contextMenu.nativeElement, 'left', e.clientX + 'px') } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { DatabaseDisplayPageComponent } from './database-display-page.component'; describe('DatabaseDisplayPageComponent', () => { let component: DatabaseDisplayPageComponent; let fixture: ComponentFixture<DatabaseDisplayPageComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ DatabaseDisplayPageComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DatabaseDisplayPageComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TreeviewFolderableComponent } from './treeview-folderable.component'; import { TreeviewModule } from 'src/app/widgets/ngx-treeview'; import { RouterModule } from '@angular/router'; import { ContextMenuModule } from 'src/app/widgets/ngx-contextmenu/ngx-contextmenu'; import { IconModule } from '../icon/icon.module'; import { FolderModule } from 'src/app/account/data/folder/folder.module'; import { LoaderModule } from '../loader/loader.module'; import { Folder2Module } from 'src/app/account/security/folder/folder.module'; @NgModule({ declarations: [TreeviewFolderableComponent], imports: [ CommonModule,TreeviewModule.forRoot(),RouterModule, ContextMenuModule.forRoot(), IconModule, Folder2Module, LoaderModule ], exports: [TreeviewFolderableComponent], }) export class TreeviewFolderableModule { } <file_sep>// using System; // using System.Collections.Generic; // using System.Linq; // using System.Threading.Tasks; // using Microsoft.EntityFrameworkCore; // using MiniS.Areas.Data.Models; // using MiniS.Areas.Identity.Data; // using MiniS.Areas.Identity.Models; // using MiniS.Areas.Master; // using MiniS.Areas.Master.Enums; // namespace MiniS.Areas.Data.Repositories { // public class FieldRepository : AccountRepository<Field,long, Database> { // protected override Table _table => Table.Field; // public FieldRepository(AppDbContext dbContext) : base(dbContext) // { // } // public override IQueryable<Field> GetModels(long parentId, params object[] param) // { // return base.GetModels(parentId).Include(Field=>Field.List).ThenInclude(List=>List.ListChildren); // } // public override IQueryable<Field> GetModel(long id) // { // return base.GetModel(id).Include(Field=>Field.List).ThenInclude(List=>List.ListChildren); // } // } // }<file_sep>import { Directive, Input } from '@angular/core'; import { AbstractControl, ValidationErrors, NG_ASYNC_VALIDATORS, AsyncValidator } from '@angular/forms'; import { Observable, timer } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { delay, map, switchMap } from 'rxjs/operators'; import { pathJoin } from '../helpers/string.helper'; @Directive({ selector: '[appExistAsync]', providers: [{ provide: NG_ASYNC_VALIDATORS, useExisting: ExistAsyncDirective, multi: true }] }) export class ExistAsyncDirective implements AsyncValidator { constructor(private http: HttpClient) { } @Input() appExistAsync: string @Input() params: any[] = [] validate(control: AbstractControl): Promise<ValidationErrors> | Observable<ValidationErrors> { return timer(500).pipe( switchMap(() => this.http.get<ValidationErrors>( pathJoin([this.appExistAsync].concat(this.params)) ) ), map(r => r ? { appExistAsync: true } : null) ) } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using MiniS.Areas.Admin.Models; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; namespace MiniS.Areas.Admin { [Route("api/admin/[Controller]")] public class AccountController : ControllerBase { private AppDbContext _context; [HttpGet] public async Task<ActionResult<IEnumerable<Account>>> GetTodoItems() { return await _context.Accounts.ToListAsync(); } public AccountController(AppDbContext context) => _context = context; [HttpPost] public async Task<ActionResult<Account>> CreateAccount([FromBody] Account account) { Account model = new Account { Name= account.Name, NormalizedName = account.NormalizedName, Description = account.Description }; _context.Accounts.Add(model); await _context.SaveChangesAsync((AccountUser)HttpContext.Items["currentUser"]); return CreatedAtAction(nameof(GetAccount), new { id = model.Id }, model); } [HttpGet("{id}")] public async Task<ActionResult<Account>> GetAccount(string id) { Account account = await _context.Accounts.Where(a=>a.NormalizedName.Equals(id.Trim())).FirstOrDefaultAsync(); if(account == null) { try{ long id2= Convert.ToInt64(id); } catch (FormatException e){ return NotFound(new {Message=e.Message}); } account = await _context.Accounts.FindAsync(id); } if (account == null) { return NotFound(new {Message = "No Account Found"}); } return account; } } }<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core"; import { Db } from "../../models/db"; import { Group } from "src/app/account/security/account-security-group/group.model"; import { getObjectCopy } from "src/app/helpers/object.helper"; import { AccountDataDbService } from "../../account-data-db.service"; import { Form } from "../../models/form"; @Component({ selector: "app-account-data-db-form-edit", templateUrl: "./account-data-db-form-edit.component.html", styleUrls: ["./account-data-db-form-edit.component.sass"] }) export class AccountDataDbFormEditComponent implements OnInit { constructor(private dbService: AccountDataDbService) {} @Input() parent: Db; @Input("model") oModel: Form = new Form(); @Output() close: EventEmitter<any> = new EventEmitter(); public groups: Group[] = []; public currentTab: Number = 1; public edit: boolean = false; public created: boolean = false; public model: Form; public title: string; public showFieldAttribute: boolean = false; ngOnInit() { this.model = getObjectCopy(this.oModel); this.edit = this.created = this.model.showEdit; this.title = this.edit ? `Edit the form "${this.model.name}"` : "Add new form"; } create() { (this.edit ? this.dbService.editForm(this.parent.id, this.model) : this.dbService.createForm(this.parent.id, this.model) ).subscribe(r => { this.created = true; this.model = this.oModel = r; }); } public cancel() { this.close.emit(); } } <file_sep>import { Component, OnInit, Output, EventEmitter } from '@angular/core'; import { Account } from '../account'; import { AdminAccountService } from '../admin-account.service'; @Component({ selector: 'app-admin-account-add', templateUrl: './admin-account-add.component.html', styleUrls: ['./admin-account-add.component.scss'] }) export class AdminAccountAddComponent implements OnInit { constructor(private adminAccountService:AdminAccountService) { } account : Account = new Account(0,null, null) @Output() close : EventEmitter<any> = new EventEmitter<any>() ngOnInit() { } create() { this.adminAccountService.createAccount(this.account).subscribe() this.close.emit() } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Table } from 'src/app/enums/table.enum'; import { DatabaseService } from '../../state/database.service'; import { Database, Columns } from '../../state/database.model'; @Component({ selector: 'app-database-display-page', templateUrl: './database-display-page.component.html', styleUrls: ['./database-display-page.component.sass'] }) export class DatabaseDisplayPageComponent implements OnInit { constructor( private route: ActivatedRoute, private databaseService: DatabaseService, ) { } public showDT = false public ngOnInit() { let data = new Database(); console.log(Object.keys(data).map(k => k)) this.route.params.subscribe(routeParams => { this.databaseService.updateParentId(routeParams.id); this.databaseService.getCurrentItems(routeParams.id).subscribe() // this.databaseService.getParents().subscribe(); this.databaseService.setColumns(Columns) /* this.databaseService.loader.startLoading(LoadingState.setColumns); this.groupeService.getAll("Victo").subscribe(r => { this.databaseService.loader.stopLoading(LoadingState.setColumns); this.databaseService.setColumns( Columns.map(c => { if (c.key == "groups") return { key: "groups", display: "Groups", sort: 0, show: true, items: r, inputType: InputType.MultiSelect }; else return c }) )}) */ }); } public Table = Table get columns(){ return Columns } get items() { return this.databaseService.currentItems$ } get parent() { return this.databaseService.parentEntity$ } get parents() { return this.databaseService.parents$ } /* get parentsLoading() { return this.databaseService.loader.setParents$ } get displayItemsLoading() { return this.databaseService.loader.set$ } get columnsLoading() { return this.databaseService.loader.setColumns$ } */ } <file_sep>import { Directive, ElementRef, Renderer2, OnDestroy, Input } from '@angular/core'; @Directive({ selector: '[appModal]' }) export class ModalDirective implements OnDestroy{ @Input("appModal") closeScroll : boolean = false constructor(private elm: ElementRef, private renderer: Renderer2) { //add class show user for animation setTimeout(t=>renderer.addClass(elm.nativeElement, 'show'), 300) //kill the scroll on the body renderer.addClass(document.body, 'modal-open') renderer.appendChild(document.body,elm.nativeElement); } ngOnDestroy(){ if(!this.closeScroll) this.renderer.removeClass(document.body, 'modal-open') this.renderer.removeChild(document.body, this.elm.nativeElement) } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using MiniS.Areas.Models; using MiniS.Areas.Master.Models; using MiniS.Areas.Data.Models; using Microsoft.AspNetCore.Mvc; namespace MiniS.Areas.Identity.Models { public class Group : Parentable<Folder>, IEquatable<Group> { [Required] [Remote(action: "ExistById", controller: "GroupController", ErrorMessage="Cannot find Model")] public override long Id { get; set; } [Required] [Remote(action: "ExistByParentId", controller: "GroupController", ErrorMessage="Cannot find parent Model")] public override long ParentId { get; set; } public List<EntityGroup> EntityGroup { get; set; } public bool Equals(Group other) { return this.Id == other.Id; } } public class GroupConfiguration : ParentableConfiguration<Group, Folder> { } }<file_sep>namespace MiniS.Areas.Master.Enums { public enum Type { Disk = 10, Folder = 20, File = 30, Database=40, Filter = 50 } }<file_sep>import { Component, OnInit } from '@angular/core'; import { AccountSecurityAuthService } from '../account-security-auth.service'; import { Login } from './login.model'; import { AccountService } from 'src/app/account/account.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-account-security-auth-login', templateUrl: './account-security-auth-login.component.html', styleUrls: ['./account-security-auth-login.component.scss'] }) export class AccountSecurityAuthLoginComponent implements OnInit { constructor( private router: Router, private accountAuthService: AccountSecurityAuthService, private accountService: AccountService ) { } model = new Login(null, null) account: string ngOnInit() {} login() { // login this.accountAuthService.login( this.accountService.account.normalizedName, this.model) .subscribe(r=>{ // Save the authenticated user if login succeed // this.accountService.authUser = r // And redirect the user to the attempted url this.router.navigateByUrl(this.accountService.url || this.accountService.account.normalizedName ) }) } } <file_sep>import {AccountUser} from './account-user.model' import { Group } from '../group/state/group.model'; export class UserGroup { constructor( public group: Group, public groupId: number, public user: AccountUser, public userId: string ){ } } <file_sep>import { Trackable, ITrackable, Columns as cols } from './trackable.model'; import { Table } from 'src/app/enums/table.enum'; import { ColDisplay } from 'src/app/widgets/datatable/datatable.interface'; import { InputType } from 'src/app/enums/input-type.enum'; export abstract class Identificable extends Trackable implements IIdentificable { public id: number public name: string public description?: string public table: Table public showEdit: boolean = false public showAdd: boolean = false public showAddFile: boolean = false public static create(obj: any ={}){ return this.constructor().clone(obj) } public clone(obj: any = {}) { return Object.assign(this, obj) } } export interface IIdentificable extends ITrackable{ id: number name: string description?: string table: Table showEdit: boolean showAdd: boolean showAddFile: boolean } let Columns: ColDisplay[] = [ { key: "id", display: "id", sort: 0, show: true, items: [], inputType: InputType.Number }, { key: "name", display: "Name", sort: 0, show: true, items: [], inputType: InputType.Text }, { key: "description", display: "Description", sort: 0, show: true, items: [], inputType: InputType.Textarea }, ...cols ] export { Columns }<file_sep> import { Groupable, Columns } from 'src/app/master/base-model/groupable.model'; import { Field } from '../../field/state/field.model'; import { Folder } from '../../folder/folder.model'; import { DatabaseService } from './database.service'; export function createDatabase(params: Partial<Database>) { return new Database() } export class Database extends Groupable<Folder>{ /* public static create(obj){ return Object.assign(new Database(), obj) } */ public fields: Array<Field> = [] public showFields: boolean = false public showForm: boolean = false public fieldProcessing: boolean = false } export { Columns } <file_sep>using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using MiniS.Areas.Admin.Models; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Controllers; using MiniS.Areas.Master.Enums; namespace MiniS.Areas.Data.Controllers { [Route("api/{account}/data/{parentId}/form")] [Authorize] [Account] public class FormController : GroupableController<Form, Database,FormService> { public FormController(FormService service, AuthorizationService authService) : base(service, authService) { } protected override Access _access => Access.Form; /* [HttpGet] public override ActionResult<List<Form>> GetAllAsync(long parentId) { return base.GetAllAsync(parentId); } [HttpGet("{id}", Name = "GetForm")] public override Task<ActionResult<Form>> GetAsync(long id) { return base.GetAsync(id); } [HttpPost] public ActionResult<Form> CreateAsync(long? parentId, Form model) { var result = ValidateParent(parentId); if (result is OkResult) { var MODEL = _service.TryCreateModel(model, _parentService.GetModel()); return CreatedAtRoute("GetForm", new { id = MODEL.Id, parentId = parentId, account = _authService.GetAccount().NormalizedName }, MODEL); } return result; } [HttpPut("{Id}")] public override Task<ActionResult<Form>> UpdateAsync(long? parentId, long id, Form model) { return base.UpdateAsync(parentId, id, model); } protected override ActionResult<Form> CreatedAtRoute() { return CreatedAtRoute("GetForm", new { id = _service.GetModel().Id }, _service.GetModel()); } */ } }<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AccountSecurityAccessTemplateComponent } from './account-security-access-template.component'; describe('AccountSecurityAccessTemplateComponent', () => { let component: AccountSecurityAccessTemplateComponent; let fixture: ComponentFixture<AccountSecurityAccessTemplateComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AccountSecurityAccessTemplateComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AccountSecurityAccessTemplateComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Form } from './form' export class Stepper { public constructor( public name?: string, public order?: number ) { } public id: number = 0 public form: Form public formId:number public updated: boolean = false public created: boolean = false } <file_sep>export class Account { constructor( public id: number, public name: string, public normalizedName: string, public description?: string, public inserted?: Date, public lastUpdated?: Date ) { } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { NavViewComponent } from './nav-view.component'; import { IconModule } from '../icon/icon.module'; @NgModule({ declarations: [NavViewComponent], imports: [ CommonModule, IconModule ], exports: [NavViewComponent] }) export class DisplayViewModule { } <file_sep>import { Access } from './access.enum'; import { Right } from './right.enum'; export class AccessTemplate { constructor( public id:number, public name: string, public description: string, public accesses:any, public showEdit: boolean = false ){ } } <file_sep>import { BehaviorSubject } from 'rxjs'; import { TreeviewItem, TreeviewHelper } from 'src/app/widgets/ngx-treeview'; import { IAccountable } from '../base-model/accountable.model'; import { IParentable } from '../base-model/parentable.model'; import { Table } from 'src/app/enums/table.enum'; import { ColDisplay } from 'src/app/widgets/datatable/datatable.interface'; import { Folder } from 'src/app/account/data/folder/folder.model'; export class TreeviewStore<Entity extends IParentable<Folder>> { // - We set the initial state in BehaviorSubject's constructor // - Nobody outside the Store should have access to the BehaviorSubject // because it has the write rights // - Writing to state should be handled by specialized Store methods (ex: addTodo, removeTodo, etc) // - Create one BehaviorSubject per store entity, for example if you have TodoGroups // create a new BehaviorSubject for it, as well as the observable$, and getters/setters private readonly _treeview = new BehaviorSubject<TreeviewItem[]>([]); private readonly _isDirty = new BehaviorSubject<boolean>(false); protected cache: StoreCache = { active: new BehaviorSubject<boolean>(false), ttl: null }; // Expose the observable$ part of the _todos subject (read only stream) readonly treeview$ = this._treeview.asObservable(); // we'll compose the todos$ observable with map operator to create a stream of only completed todos /* readonly completedTodos$ = this.treeview$.pipe( map(todos => todos.filter(todo => todo.isCompleted)) ) */ // the getter will return the last value emitted in _todos subject public get treeview(): TreeviewItem[] { return this._treeview.getValue(); } // assigning a value to this.todos will push it onto the observable // and down to all of its subsribers (ex: this.todos = []) public set treeview(val: TreeviewItem[]) { this._treeview.next(val); } private readonly _currentItems = new BehaviorSubject<TreeviewItem[]>(null); //private readonly _currentItems = new BehaviorSubject<TreeviewItem[]>([]); private readonly _parentEntity = new BehaviorSubject<TreeviewItem>(null); private readonly _parents = new BehaviorSubject<TreeviewItem[]>(null); private readonly _columns = new BehaviorSubject<ColDisplay[]>(null); private readonly _loading = new BehaviorSubject<boolean>(false); // Expose the observable$ part of the _todos subject (read only stream) readonly currentItems$ = this._currentItems.asObservable(); readonly parentEntity$ = this._parentEntity.asObservable(); readonly parents$ = this._parents.asObservable(); readonly columns$ = this._columns.asObservable(); readonly loading$ = this._loading.asObservable(); // we'll compose the todos$ observable with map operator to create a stream of only completed todos /* readonly completedTodos$ = this.treeview$.pipe( map(todos => todos.filter(todo => todo.isCompleted)) ) */ // the getter will return the last value emitted in _todos subject /* public get currentItems(): TreeviewItem[] { return this._currentItems.getValue(); } */ public get currentItems(): TreeviewItem[] { return this._currentItems.getValue(); } // assigning a value to this.todos will push it onto the observable // and down to all of its subsribers (ex: this.todos = []) // assigning a value to this.todos will push it onto the observable // and down to all of its subsribers (ex: this.todos = []) public set currentItems(val: TreeviewItem[]) { this._currentItems.next(val); } /* public set currentItems(val: TreeviewItem[]) { this._currentItems.next(val); } */ public set parentEntity(val: TreeviewItem) { this._parentEntity.next(val); } public get parentEntity(): TreeviewItem { return this._parentEntity.getValue(); } public set parents(val: TreeviewItem[]) { this._parents.next(val); } public get parents(): TreeviewItem[] { return this._parents.getValue(); } public set columns(val: ColDisplay[]) { this._columns.next(val); } public get columns(): ColDisplay[] { return this._columns.getValue(); } public set loading(val: boolean) { this._loading.next(val); } public get loading(): boolean { return this._loading.getValue(); } public get isDirty(): boolean { return this._isDirty.getValue(); } // assigning a value to this.todos will push it onto the observable // and down to all of its subsribers (ex: this.todos = []) public set isDirty(val: boolean) { this._isDirty.next(val); } public set(val: TreeviewItem[], selected: number[], type: Table) { this.setHasCache(true, { restartTTL: true }) this.treeview = TreeviewHelper.setChecked(val, selected, type) } add(entity: Entity) { // we assaign a new copy of todos by adding a new todo to it // with automatically assigned ID ( don't do this at home, use uuid() ) console.log(this.treeview) const item = new TreeviewItem({ entity, value: entity.id, text: entity.name, type: entity.table, pEntity: null }) if (entity.parentId == 0) this.treeview.push(item) else { console.log(entity.parentId, entity.parentTable) const pItem = TreeviewHelper.findItemInList(this.treeview, entity.parentId, entity.parentTable) item.pEntity = pItem.entity pItem.children ? pItem.children.push(item) : pItem.children = [item] } } setHasCache(hasCache: boolean, options: { restartTTL: boolean } = { restartTTL: false }) { if (hasCache !== this.cache.active.value) { this.cache.active.next(hasCache); } if (options.restartTTL) { const ttlConfig = this.getCacheTTL(); if (ttlConfig) { if (this.cache.ttl !== null) { clearTimeout(this.cache.ttl); } this.cache.ttl = <any>setTimeout(() => this.setHasCache(false), ttlConfig); } } } getCacheTTL() { return 1000 * 5 } _cache(): BehaviorSubject<boolean> { return this.cache.active; } update(entity: Entity) { // we assaign a new copy of todos by adding a new todo to it // with automatically assigned ID ( don't do this at home, use uuid() ) const tvi = TreeviewHelper.findItemInList(this.treeview, entity.id, entity.table) tvi.entity = entity tvi.text = entity.name tvi.value = entity.id this.treeview = [...this.treeview]; } remove(entity: Entity) { const parent = TreeviewHelper.findItemInList(this.treeview, entity.parentId, entity.parentTable); parent.children = parent.children.filter(c => c.value != entity.id) this.treeview = [...this.treeview]; } public setCurrentItems(parentId: number) { this.parentEntity = parentId == 0 ? TreeviewHelper.rootTreeview(this.treeview) : TreeviewHelper.findItemInList(this.treeview, parentId, Table.Folder) this.currentItems = this.parentEntity.children } public setCurrentParents(parentId: number) { this.parents = TreeviewHelper .findParentsInList(this.treeview, parentId).reverse() this.parents.unshift(TreeviewHelper.rootTreeview(this.treeview)) this.parentEntity.entity.id && this.parents.push(this.parentEntity) // this.displayItemsStore.parents.push(this.displayItemsStore.displayItems) } /* setCompleted(id: number, isCompleted: boolean) { let todo = this.todos.find(todo => todo.id === id); if (todo) { // we need to make a new copy of todos array, and the todo as well // remember, our state must always remain immutable // otherwise, on push change detection won't work, and won't update its view const index = this.todos.indexOf(todo); this.todos[index] = { ...todo, isCompleted } this.todos = [...this.todos]; } } */ } export type StoreCache = { active: BehaviorSubject<boolean>; ttl: number; };<file_sep>import { Group } from 'src/app/account/security/account-security-group/group.model'; import { FieldAttribute } from './field'; import { Db } from './db'; import { Groupable } from 'src/app/master/base-model/groupable.model'; export class Form extends Groupable<Db> { public fieldAttributes: Array<FieldAttribute> = [] public showAdd: boolean = false public showFields: boolean = false public fieldProcessing: boolean = false public showDatabase: boolean = false } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; import { AccountComponent } from './account/account.component'; import { AccountSecurityAccessTemplateComponent } from './account/security/account-security-access-template/account-security-access-template.component'; import { SecurityComponent } from './account/security/security.component'; import { AccountGuard } from './account/guards/account.guard'; import { AuthGuard } from './account/guards/auth.guard'; import { AccountHomeComponent } from './account/account-home/account-home.component'; import { DatabaseComponent } from './account/data/database/components/database/database.component'; import { DatabaseDisplayPageComponent } from './account/data/database/components/database/database-display-page.component'; import { ListComponent } from './account/data/list/components/list.component'; import { ListDisplayPageComponent } from './account/data/list/components/list-display-page.component'; import { DataComponent } from './account/data/data.component'; import { ListitemDisplayPageComponent } from './account/data/listitem/components/listitem-display-page.component'; import { GroupComponent } from './account/security/group/components/group.component'; import { GroupDisplayPageComponent } from './account/security/group/components/group-display-page.component'; import { UserComponent } from './account/security/user/components/user.component'; import { UserDisplayPageComponent } from './account/security/user/components/user-display-page.component'; import { AuthComponent } from './account/security/auth/components/auth.component'; const routes: Routes = [ { path: ':account', component: AccountComponent, canActivate: [AccountGuard], canActivateChild: [AuthGuard], children: [ { path: '', component: AccountHomeComponent, pathMatch: 'full' }, { path: 'data', component: DataComponent, children: [ { path: 'list', component: ListComponent, children: [ { path: 'folder/:id', component: ListDisplayPageComponent }, { path: 'listitem/:id', component: ListitemDisplayPageComponent } ] }, { path: 'database', component: DatabaseComponent, children: [ { path: 'folder/:id', component: DatabaseDisplayPageComponent }, // {path: 'form/:id', component: AccountDataDbFormDisplayComponent}, // {path: 'data/:id', component: AccountDataDbDataComponent} ] }, // { path: 'folder/:id', component: AccountDataFolderComponent, outlet: 'folder' } ] }, { path: 'security/auth/login', component: AuthComponent }, { path: 'security', component: SecurityComponent, children: [ // { path: 'user', component: AccountSecurityUserComponent}, { path: 'access-template', component: AccountSecurityAccessTemplateComponent }, { path: 'group', component: GroupComponent, children: [ { path: 'folder/:id', component: GroupDisplayPageComponent }, ] }, { path: 'user', component: UserComponent, children: [ { path: 'folder/:id', component: UserDisplayPageComponent }, ] } ] }, ] }, { path: '**', component: PageNotFoundComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { ListitemDisplayPageComponent } from './listitem-display-page.component'; describe('ListitemDisplayPageComponent', () => { let component: ListitemDisplayPageComponent; let fixture: ComponentFixture<ListitemDisplayPageComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ListitemDisplayPageComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ListitemDisplayPageComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { EditModalModule } from 'src/app/master/components/edit-modal/edit-modal.module'; import { IconModule } from 'src/app/master/components/icon/icon.module'; import { TranslocoRootModule } from 'src/app/transloco-root.module'; import { GroupModule } from './group/group.module'; import { UserModule } from './user/user.module'; import { Folder2Module } from './folder/folder.module'; import { SecurityComponent } from './security.component'; import { RouterModule } from '@angular/router'; import { AuthModule } from './auth/auth.module'; @NgModule({ declarations: [SecurityComponent], imports: [ CommonModule, FormsModule, EditModalModule, IconModule, TranslocoRootModule, GroupModule, UserModule, Folder2Module, RouterModule, AuthModule ], exports: [] }) export class SecurityModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { AccountService } from './account.service'; import { AccountSecurityAuthService } from './security/account-security-auth/account-security-auth.service'; import { Router } from '@angular/router'; import { User } from './security/user/state/user.model'; @Component({ selector: 'app-account', templateUrl: './account.component.html', styleUrls: ['./account.component.scss'] }) export class AccountComponent implements OnInit { constructor(private accountService: AccountService, private accountAuthService: AccountSecurityAuthService, private router: Router) { } public normalizedAccount: string public ngOnInit() { this.normalizedAccount = this.accountService.account.normalizedName } get authUser(): User { return this.accountService.authUser } public languages = [ { "disabled": false, "group": null, "selected": false, "text": "English (United States)", "value": "en-US", flag: "us" }, { "disabled": false, "group": null, "selected": true, "text": "French (France)", "value": "fr-FR", flag: "fr" }, { "disabled": false, "group": null, "selected": false, "text": "Spanish (Spain)", "value": "es-ES", flag: "es" } ] get currLang() { return this.languages.find(l => l.value == this.accountService.currLang.value) } public logout() { this.accountAuthService.logout(this.normalizedAccount).subscribe(r => { // this.router.navigateByUrl(`/${this.normalizedAccount}/security/auth/login`) this.accountService.authUser = null this.router.navigate([`/${this.normalizedAccount}/security/auth/login`], { queryParams: { returnUrl: this.router.url } }) }) } public onLangChange(v: any) { this.accountService.setLanguage(v).subscribe() } public login() { this.accountService.redirectToLogin() } } <file_sep>import { isBetween } from 'src/app/helpers/number.helper'; export enum Access { // Security [0,99] User = 10, UserTemplate = 20, AcccesTemplate = 30, Group = 40, // Data [100, 499] Form = 110, View = 120, List = 130, ListItem = 135, Record = 140, Filter = 150, Folder = 160, Database = 170, DatabaseField =180, DatabaseFieldAttribute = 190, // Library [500, 700] Directory = 510, Files = 520 } export enum Module { Security = 10, Data = 20, Library = 30 } export function accessByModule(): Object { let range = { Security: [1, 100], Data: [100, 499], Library: [500, 700] } return Object.keys(range).map(r => { return { name: r, items: Object.keys(Access).filter(a => isNaN(Number(a)) && isBetween(Access[a], range[r][0], range[r][1])) } }); } <file_sep>import { Component, OnInit, Input, EventEmitter, Output } from "@angular/core"; import { FieldAttribute, FieldType, Field } from "../../../models/field"; import { Form } from "@angular/forms"; import { getObjectCopy } from "src/app/helpers/object.helper"; @Component({ selector: "[app-account-data-db-form-field-attribute-number]", templateUrl: "./account-data-db-form-field-attribute-number.component.html", styleUrls: ["./account-data-db-form-field-attribute-number.component.sass"] }) export class AccountDataDbFormFieldAttributeNumberComponent implements OnInit { constructor() {} @Input() public model: FieldAttribute; @Input() public field: Array<Field> = []; @Input() public form: Form; @Input() public listDefaults: any; @Output() public edit: EventEmitter<FieldAttribute> = new EventEmitter< FieldAttribute >(); @Output() public remove: EventEmitter<any> = new EventEmitter<any>(); public modelCopy: FieldAttribute; public type: string; ngOnInit() { this.modelCopy = getObjectCopy(this.model); this.isInteger = this.model.field.type == FieldType.Integer; this.maskPattern = this.isInteger ? "[90*N]+" : "[90*N.]+"; this.type = this.isInteger ? "integer" : "decimal"; this.maskPatternMessage = this.isInteger ? 'Mask value must only be a combination of the characters: "9", "0", "*", "N"' : 'Mask value must only be a combinations characters: "9", "0", "*", ".", "N" '; } public isInteger: boolean; public maskPattern: string; public maskPatternMessage: string; regexMessage(message: string, actual: string, required: string) { return message.replace(":value", actual).replace(":regexp", required); } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AccountDataDbFormFieldAttributeTextComponent } from './account-data-db-form-field-attribute-text.component'; describe('AcoountDataDbFormFieldAttributeTextComponent', () => { let component: AccountDataDbFormFieldAttributeTextComponent; let fixture: ComponentFixture<AccountDataDbFormFieldAttributeTextComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AccountDataDbFormFieldAttributeTextComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AccountDataDbFormFieldAttributeTextComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Injector } from '@angular/core'; import { Table } from 'src/app/enums/table.enum'; import { DatabaseService } from 'src/app/account/data/database/state/database.service'; import { FolderableService } from './folderable.service'; import { ListService } from 'src/app/account/data/list/state/list.service'; import { ListitemService } from 'src/app/account/data/listitem/state/listitem.service'; import { GroupService } from 'src/app/account/security/group/state/group.service'; import { UserService } from 'src/app/account/security/user/state/user.service'; import { AccountService } from 'src/app/account/account.service'; import { IAccountable } from '../base-model/accountable.model'; export class FactoryService{ public constructor(private injector: Injector){} public get(table: Table): FolderableService<any> { switch(table){ case Table.Database: return this.injector.get(DatabaseService) case Table.Folder: return this.injector.get(FolderableService) case Table.List: return this.injector.get(ListService) case Table.ListItem: return this.injector.get(ListitemService) case Table.Group: return this.injector.get(GroupService) case Table.User: return this.injector.get(UserService) // case Table.Account: return this.injector.get(AccountService) } } /* public class import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'; import { Component, Input, OnInit, forwardRef } from '@angular/core'; export const COMPONENT_NAME_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => ComponentNameComponent), multi: true }; @Component({ selector: 'selector-name', templateUrl: './name.component.html', styleUrls: ['./name.component.css'], providers: [COMPONENT_NAME_VALUE_ACCESSOR] }) export class ComponentNameComponent implements OnInit, ControlValueAccessor { private _value: any; set value(value: any) { this._value = value; this.notifyValueChange(); } get value(): any { return this._value; } onChange: (value) => {}; onTouched: () => {}; constructor() { } notifyValueChange(): void { if (this.onChange) { this.onChange(this.value); } } ngOnInit(): void { } writeValue(obj: any): void { this._value = obj; } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouched = fn; } setDisabledState(isDisabled: boolean): void { } } */ }<file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MiniS.Areas.Admin.Models; using MiniS.Areas.Data.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Models; using MiniS.Areas.Services; namespace MiniS.Areas.Master.Controllers { [Authorize] [Account] public abstract class GroupableController<Model, Parent, Service> : ControllerBase where Model : IParentable<Parent> where Parent : IAccountable where Service : IParentableService<Model, Parent> { protected Service _service; protected IParentableService<Parent> _parentService; protected abstract Access _access { get; } public GroupableController(Service service, AuthorizationService authService) { _service = service; _parentService = (IParentableService<Parent>)service.ParentService; authService.SetAccess(_access); _service.SetAuthService(authService); _parentService.SetAuthService(authService); } [HttpGet] public virtual async Task<ActionResult<List<Model>>> GetAllAsync(long parentId) { // return forbidden response if the user has not read rights on databases if (!_service.HasRight(Right.Read)) return Forbid(); var models = await _service.FetchModels(parentId); // fetch all Database data the authenticated has access and return a 404 response if an error occurs if (_service.Fails()) return BadRequest(_service.ModelState); // return all Database data the authenticated has access return models; } [HttpGet("{id:long}")] public async Task<ActionResult<Model>> GetAsync(long parentId, long id) { if (!_service.HasRight(Right.Read)) return Forbid(); var model = await _service.FetchModel(id); if (_service.NotFound) return NotFound(_service.ModelState); if (_service.Fails()) return BadRequest(_service.ModelState); if (model.ParentId != parentId) { _service.LogWarning(1, "parent model mismatch"); return BadRequest(_service.ModelState); } if (CannotAccessResource(model)) return Forbidden(); return model; } private bool CannotAccessResource(IAccountable model) => !(_service.CanAccessAccountResource(model) && _service.CanAccessGroupResouce(model as IOGroupable)); private ObjectResult Forbidden() => StatusCode(StatusCodes.Status403Forbidden, _service.ModelState); protected async Task<ActionResult<Parent>> ValidateParent(long parentId) { // Check if authenticated user has the right to create Items otherwise return a 403 http forbidden response if (!_service.HasRight(Right.Create)) return Forbidden(); Parent parentModel = default(Parent); if (parentId != 0) { parentModel = await _parentService.FetchModel(parentId); var modelState = _parentService.ModelState; if (parentModel == null) return NotFound(modelState); if (_parentService.Fails()) return BadRequest(modelState); if (CannotAccessResource(parentModel)) return Forbidden(); } return parentModel; } protected async Task<ActionResult<Model>> ValidateModel(long id) { // Check if authenticated user has the right to create Items otherwise return a 403 http forbidden response if (!_service.HasRight(Right.Create)) return Forbidden(); Model model = await _service.FetchModel(id); if (_service.NotFound) return NotFound(_service.ModelState); if (_service.Fails()) return BadRequest(_service.ModelState); if (CannotAccessResource(model)) return Forbidden(); return model; } public virtual async Task<ActionResult<Model>> CreateAsync(long parentId, Model model) { /* var result = await ValidateParent(parentId); if (_parentService.Fails()) return result.Result; */ _service.TryCreateModel(model).Wait(); if (_service.Fails()) return BadRequest(_service.ModelState); return Created(Request.Path + "/" + _service.MODEL.Id, _service.MODEL); } [HttpPut("{id:long}")] public async Task<ActionResult<ITrackable>> UpdateAsync(long parentId, long id, Model model) { /* var result1 = await ValidateParent(parentId); if (_parentService.Fails()) return result1.Result; var result2 = await ValidateModel(id); if (_service.Fails()) return result2.Result; */ _service.TryUpdateModel(model).Wait(); if (_service.Fails()) return BadRequest(_service.ModelState); return _service.MODEL; } [HttpGet("treeview")] public virtual ActionResult<List<Component>> GetTreeviews() { if (!_service.HasRight(Right.Read)) return Forbid(); return _service.GetTreeviews(); } [HttpGet("parents")] public virtual ActionResult<List<Leaf>> GetParents(long parentId) { if (!_service.HasRight(Right.Read)) return Forbid(); return _service.GetParents(parentId); } [HttpGet("display-page")] public virtual async Task<ActionResult<Component>> GetDisplayPage(long parentId) { if (!_service.HasRight(Right.Read)) return Forbidden(); var model = await _parentService.FetchModel(parentId); if (_service.NotFound) return NotFound(_service.ModelState); if (_service.Fails()) return BadRequest(_service.ModelState); return _service.GetTreeview(model, false); } [HttpDelete("{id:long}")] public async Task<ActionResult<Model>> Delete(long id) { var result = await ValidateModel(id); if (_service.Fails()) return result; return await _service.Delete(result.Value); } [HttpGet("existby/id/{id}")] public async Task<ActionResult<bool>> ExistById(long id) { if (id == 0) return true; _service._parentableStore.Model = await _service.FetchModel(id); if (_service._parentableStore.Model.Id == id) return true; return false; } [HttpGet("exist/byparentid/{id}")] public async Task<ActionResult<bool>> ExistByParentId(long id) { throw new Exception(id.ToString()); _service._parentableStore.Parent = await _parentService.FetchModel(id); if (_service._parentableStore.Parent.Id == id) return true; return false; } [HttpGet("existsby/name/{name?}/{current?}")] public async Task<ActionResult<bool>> ExistsByName(long parentId, string name = null, string current = null) { return await _service.ExistsByName(parentId, name, current); } } }<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { EditModalComponent } from './edit-modal.component'; import { ModalDirective } from 'src/app/widgets/modal.directive'; import { IconModule } from '../icon/icon.module'; @NgModule({ declarations: [EditModalComponent, ModalDirective], imports: [ CommonModule, IconModule ], exports: [EditModalComponent] }) export class EditModalModule { } <file_sep>import { Injectable } from '@angular/core'; import { ParentableService } from '../../account.service'; import { HttpClient } from '@angular/common/http'; import { tap } from 'rxjs/operators'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { forkJoin, Observable, of } from 'rxjs'; import { Table } from 'src/app/enums/table.enum'; import { AccountDataFolderableService } from '../account-data-folder/account-data-folder.service'; import { List } from '../models/list.model'; import { ListItem } from '../models/list-item'; import { getListItems } from 'src/app/widgets/ngx-pagination/testing/testing-helpers'; @Injectable({ providedIn: 'root' }) export class AccountDataListService { constructor( private accountService: ParentableService, private folderService: AccountDataFolderableService, private http: HttpClient ) { } public account: string = this.accountService.account.normalizedName public folderTreeView: TreeviewItem[] = [] public parentListItems: ListItem[] = [] public listItems: ListItem[] = [] public list: List createList(parent: Number, model: List) { return this.http.post(`api/${this.account}/data/${parent}/list`, model).pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.List).subscribe())) } editList(parent: Number, model: List) { return this.http.put(`api/${this.account}/data/${parent}/list/${model.id}`, model).pipe(tap(r => this.folderService.getFolderTreeView(-1, Table.List).subscribe())) } createListItem(listId: number, model: ListItem): Observable<ListItem> { return this.http.post<ListItem>(`api/${this.account}/data/${listId}/list-item`, model).pipe( tap(r => this.listItems.unshift(r))) } editListItem(listId: number, model: ListItem): Observable<ListItem> { return this.http.put<ListItem>(`api/${this.account}/data/${listId}/list-item/${model.id}`, model).pipe( tap(r => this.listItems[this.listItems.map(li => li.id).indexOf(model.id)] = r)) } goToList(listId: number = null, pListId: number = null) { this.listItems = this.parentListItems = [] listId = listId == null ? this.list.id : listId pListId = pListId == null ? this.list.parentListId : pListId return forkJoin( this.http.get<ListItem[]>(`api/${this.account}/data/${listId}/list-item`), this.list.dependant ? this.http.get<ListItem[]>(`api/${this.account}/data/${pListId}/list-item`) : of(undefined) ).pipe(tap( r => { this.listItems = r[0] this.parentListItems = r[1] } )) } getList(listId: number, withItems: "true" | "false" = "false"): Observable<List> { return this.http.get<List>(`api/${this.account}/data/0/list/${listId}`, { params: { withItems } }).pipe( tap(r => this.list = r)) } goToListItem(listId: number) { return this.http.get<ListItem[]>(`api/${this.account}/data/${listId}/list-item`) } getListItems(listId: number, parentListItems : Array<number> = null) { const params = parentListItems && parentListItems.length > 0 ? { parentListItems: JSON.stringify(parentListItems) } : null return this.http.get<ListItem[]>(`api/${this.account}/data/${listId}/list-item`, { params }) .pipe(tap(r => this.listItems = r)) } } <file_sep>import { Injectable } from '@angular/core' import { AccountService } from 'src/app/account/account.service' import { HttpClient } from '@angular/common/http' import { EntityService } from 'src/app/master/states/entity.service' import { Field } from './field.model' @Injectable({ providedIn: 'root' }) export class FieldService extends EntityService<Field> { public constructor(protected http: HttpClient, private accountService: AccountService) { super(http) } protected get url() {return `api/${this.accountService.account.normalizedName}/data/${this.parentId}/field`} // remove(id: ID) { // this.treview.remove(id); // } }<file_sep>using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Query; using MiniS.Areas.Identity.Data; using MiniS.Areas.Master.Enums; namespace MiniS.Areas.Master.Factories { public class EnumTableToModel { private AppDbContext _dbContext; public EnumTableToModel (AppDbContext dbContext) { _dbContext = dbContext; } private static EnumTableToModel Instance = null; public static EnumTableToModel Singleton (AppDbContext dbContext) { if (Instance == null) { Instance = new EnumTableToModel(dbContext); return Instance; } else return Instance; } public IQueryable Factory (Table table) { switch (table) { case Table.Database: return _dbContext.Databases; case Table.Folder: return _dbContext.Folders; default: return null; } } } }<file_sep>using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using MiniS.Areas.Admin.Models; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Controllers; namespace MiniS.Areas.Data.Controllers { [Route("api/{account}/data/{parentId}/field")] [Authorize] [Account] public class FieldController : GroupableController<Field, Database, FieldService> { private readonly ListController _listConroller; public FieldController(FieldService service, DatabaseService parentService, AuthorizationService authService, ListController listController) : base(service, authService) { _listConroller = listController; } protected override Access _access => Access.Database; public override async Task<ActionResult<Field>> CreateAsync(long parentId, Field model) { if (parentId == 0) return BadRequest("bad parent Id"); //todo: write the message if (model.Type.Equals(FieldType.list) || model.Type.Equals(FieldType.dependentList)) { if (model.ListId is null) return BadRequest("list Id not found");//todo: write the message var result0 = await _listConroller.GetAsync(model.ListParentId, model.ListId ?? default(long)); if (result0.Value == null) return result0.Result; if (model.Type.Equals(FieldType.dependentList)) { if (model.RelatedFieldId is null) return BadRequest();//todo: write the message var result1 = await GetAsync(parentId, model.RelatedFieldId ?? default(long)); if (result1.Value == null) return result1; if (result1.Value.ListId != result0.Value.ParentListId) return BadRequest("list and parent list not match");//todo: write the message } } return await base.CreateAsync(parentId, model); } } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { AccountDataFolderableService } from '../account-data-folder/account-data-folder.service'; import { Table } from 'src/app/enums/table.enum'; import { TreeviewItem, TreeItem, TreeviewConfig } from 'src/app/widgets/ngx-treeview'; import { Folder } from '../models/folder.model'; import { AccountDataListService } from './account-data-list.service'; import { List } from '../models/list.model'; import { ContextMenuComponent } from 'src/app/widgets/ngx-contextmenu/contextMenu.component'; import { Router, RouterOutlet } from '@angular/router'; import { ParentableService } from '../../account.service'; import { slideInAnimation } from './router-animation'; @Component({ selector: 'app-account-data-list', templateUrl: './account-data-list.component.html', styleUrls: ['./account-data-list.component.scss'], animations: [ slideInAnimation // animation triggers go here ] }) export class AccountDataListComponent implements OnInit { constructor(private folderService: AccountDataFolderableService, private listService: AccountDataListService, private accountService: ParentableService, private router: Router) { } Table = Table treeviewConfig: TreeviewConfig = TreeviewConfig.create({hasAllCheckBox: false }) @ViewChild('basicMenu', {static: false}) public basicMenu: ContextMenuComponent; @ViewChild('otherMenu', {static: false}) public otherMenu: ContextMenuComponent; ngOnInit() { this.folderService.getFolderTreeView(-1, Table.List).subscribe() this.account = this.accountService.account.normalizedName } prepareRoute(outlet: RouterOutlet) { return outlet && outlet.isActivated && outlet.activatedRoute && outlet.activatedRoute.snapshot.params.id; } public account: string get items(): TreeviewItem[] { return this.folderService.folderTreeView } /* goToList(list:List){ this.isListItem = true this.listService.list = list this.listService.goToList().subscribe() } */ dependant : boolean = false isListItem = false goToList(list:List){ this.isListItem = true this.listService.list = list this.listService.goToList().subscribe() } } <file_sep>import { Columns as cols } from './identificable.model' import { Table } from 'src/app/enums/table.enum'; import { Accountable, IAccountable } from './accountable.model'; import { InputType } from 'src/app/enums/input-type.enum'; export abstract class Parentable<P extends Accountable > extends Accountable implements IParentable<P> { private _parent: P public get parent(): P { return this._parent } public set parent(value: P) { this._parent = value this.parentId = value ? value.id : 0 } public parentId: number public parentTable: Table } export interface IParentable<P extends IAccountable> extends IAccountable { parentId: number parent: P parentTable: Table } let Columns = [ ...cols, { key: "parent", display: "parent", sort: 0, show: true, items: [], inputType: InputType.Select }, ] export { Columns }<file_sep>import { concat, isNil, pull } from "lodash"; import { TreeviewItem } from "./treeview-item"; import { Table } from "src/app/enums/table.enum"; import { getObjectCopy } from "src/app/helpers/object.helper"; import { Folder } from 'src/app/account/data/folder/folder.model'; export const TreeviewHelper = { findItem: findItem, findItemInList: findItemInList, findParent: findParent, removeItem: removeItem, concatSelection: concatSelection, onChildCheckedChange: onChildCheckedChange, findParents: findParents, findParentsInList: findParentsInList, filterTreeviewItems: filterTreeviewItems, filterTreeviewItem: filterTreeviewItem, rootTreeview: rootTreeview, setChecked: setChecked }; function findItem(root: TreeviewItem, value: number, type: Table): TreeviewItem { if (isNil(root)) { return undefined; } if (root.value == value && root.type == type) { return root; } if (root.children) { for (const child of root.children) { const foundItem = findItem(child, value, type); if (foundItem) { return foundItem; } } } return undefined; } function rootTreeview(children: TreeviewItem[] = []) { return new TreeviewItem({ value: 0, text: "root", type: Table.Folder, entity: new Folder(), children }) } function findItemInList(list: TreeviewItem[], value: any, type?: Table): TreeviewItem { if (isNil(list)) { return undefined; } for (const item of list) { const foundItem = findItem(item, value, type); if (foundItem) { return foundItem; } } return undefined; } function findParent(root: TreeviewItem, item: TreeviewItem | number, type: Table = Table.Folder): TreeviewItem { if (isNil(root) || isNil(root.children)) return undefined for (const child of root.children) { if (child === item || (child.value == item && child.type == type)) return root else { const parent = findParent(child, item, type); if (!isNil(parent)) return parent; } } return undefined; } function findParents( root: TreeviewItem, item: TreeviewItem | number, type: Table = Table.Folder ): Array<TreeviewItem> { if (isNil(root) || isNil(root.children)) return Array.of(); let parents = []; let parent = findParent(root, item, type); while (!isNil(parent)) { parents.push(parent) parent = findParent(root, parent); } return parents; } function findParentsInList( roots: Array<TreeviewItem>, item: TreeviewItem | number, type: Table = Table.Folder ): Array<TreeviewItem> { for (const root of roots) { const parents = findParents(root, item, type); if (parents.length > 0) return parents; } return []; } function removeItem(root: TreeviewItem, item: TreeviewItem): boolean { const parent = findParent(root, item); if (parent) { pull(parent.children, item); if (parent.children.length === 0) { parent.children = undefined; } else { parent.correctChecked(); } return true; } return false; } function concatSelection( items: TreeviewItem[], checked: TreeviewItem[], unchecked: TreeviewItem[] ): { [k: string]: TreeviewItem[] } { let checkedItems = [...checked]; let uncheckedItems = [...unchecked]; for (const item of items) { const selection = item.getSelection(); checkedItems = concat(checkedItems, selection.checkedItems); uncheckedItems = concat(uncheckedItems, selection.uncheckedItems); } return { checked: checkedItems, unchecked: uncheckedItems }; } function onChildCheckedChange(item: TreeviewItem, checked: boolean) { let itemChecked: boolean = null; for (const childItem of item.children) { if (itemChecked === null) { itemChecked = childItem.checked; } else if (itemChecked !== childItem.checked) { itemChecked = undefined; break; } } if (itemChecked === null) { itemChecked = false; } if (item.checked !== itemChecked) { item.checked = itemChecked; } } function filterTreeviewItems( items: Array<TreeviewItem>, fn: (item: TreeviewItem) => boolean, original: boolean = false ) { let filterItems = []; items.forEach(item => { let newItem = filterTreeviewItem(item, fn); if (!isNil(newItem)) { filterItems.push(newItem); } }); return filterItems; } function filterTreeviewItem( item: TreeviewItem, fn: (item: TreeviewItem) => boolean, original: boolean = false ): TreeviewItem { if (fn(item)) { return (original ? item : getObjectCopy(item)); } else { if (!isNil(item.children)) { const children: TreeviewItem[] = []; item.children.forEach(child => { const newChild = filterTreeviewItem(child, fn); if (!isNil(newChild)) { children.push(newChild); } }); if (children.length > 0) { const newItem = new TreeviewItem(item); newItem.collapsed = false; newItem.children = children; return newItem; } } } return undefined; } function updateCheckedOfAll(items: Array<TreeviewItem>) { let itemChecked: boolean = null; for (const filterItem of this.filterItems) { if (itemChecked === null) { itemChecked = filterItem.checked; } else if (itemChecked !== filterItem.checked) { itemChecked = undefined; break; } } if (itemChecked === null) { itemChecked = false; } this.allItem.checked = itemChecked; } function setChecked(items: TreeviewItem[], selected: number[], type: Table): TreeviewItem[] { if (Array.isArray(selected)) selected.forEach(v => { const tvi = TreeviewHelper.findItemInList( items, v, type) isNil(tvi) || (tvi.checked = true) }); return items } <file_sep>import { Component, OnInit } from '@angular/core'; import { FolderableEditComponent } from 'src/app/master/states/folderable-edit.component'; import { User, UserLevel } from '../state/user.model'; import { Folder } from 'src/app/account/data/folder/folder.model'; import { Table } from 'src/app/enums/table.enum'; import { Right } from '../../account-security-access-template/right.enum'; import { Access } from '../../account-security-access-template/access.enum'; import { AccountService } from 'src/app/account/account.service'; import { TreeviewItem, TreeviewHelper } from 'src/app/widgets/ngx-treeview'; export type Labelable = { label: any, value: any, } // const accesses = Object.keys(Access).filter(a => isNaN(Number(a))).map(a => { return { label: a, value: Access[a] } }) // const rights = Object.keys(Right).filter(a => isNaN(Number(a))).map(a => { return { label: a, value: Right[a] } }) @Component({ selector: 'app-user-edit', templateUrl: './user-edit.component.html', styleUrls: ['./user-edit.component.sass'] }) export class UserEditComponent extends FolderableEditComponent<User, Folder> implements OnInit { public UserLevel = UserLevel public Right = Right public accesses: Labelable[] public ct: number = 0 public isAccess = (ul: UserLevel): boolean => (ul & UserLevel.Access) === UserLevel.Access public isGroup = (ul: UserLevel): boolean => (ul & UserLevel.Group) === UserLevel.Group public isAdmin = (ul: UserLevel): boolean => (ul & UserLevel.Admin) === UserLevel.Admin public authUser: User public accountService: AccountService public existByNameLink: string; ngOnInit(): void { this.type = Table.User this.accountService = this.injector.get(AccountService) this.authUser = this.accountService.authUser this.existByNameLink = `api/${this.accountService.account.normalizedName}/security/${this.parent.id}/user/existsby` this.oModel.accesses = this.oModel.accesses || {} this.accesses = Object.keys(Access).filter(a => isNaN(Number(a))).map(a => { return { label: a, value: Access[a], rights: Object.keys(Right) .filter(r => isNaN(Number(r)) && (this.isAccess(this.authUser.userLevel) || Right[r] <= this.authUser.accesses[a])) .map(r => { return { label: r, value: Right[r] } }) } }).filter(a => a.rights.length > 1) this.accesses.forEach(a => this.oModel.accesses[a.label] = this.oModel.accesses[a.label] || Right.None) this.model = new User().clone(this.oModel) super.ngOnInit() } get showGroup(): boolean { return (this.model.userLevel & UserLevel.Group) != UserLevel.Group } } <file_sep>import { List } from "../../models/list.model"; import { Stepper } from "./stepper"; import { Form } from "./form"; import { AccountableParentableTrackable } from 'src/app/master/base-model/trackable-parentable-accountable.model'; import { Db } from './db'; export class Field extends AccountableParentableTrackable<Db> { private _relatedField: Field; constructor(public type: FieldType, ) { super() } public static get(obj: Field): Field { let klass = new Field(obj.type) klass.list = obj.list klass.name = obj.name klass.relatedField = obj.relatedField return klass } public guid: string private _list: List; public get relatedField() { return this._relatedField; } public set relatedField(value: Field) { this._relatedField = value if (value) this.relatedFieldId = value.id; } public listParentId: number public get list() { return this._list } public set list(value: List) { this._list = value; if (value) { this.listId = value.id; this.listParentId = value.parentId; } } public listId: number; public relatedFieldId: number; public inputType: string; public updated: boolean = false public created: boolean = false } export class FieldAttribute { public get stepper(): Stepper { return this._stepper; } public set stepper(value: Stepper) { this._stepper = value; this.stepperId = value.id; } constructor( public name?: string, public field?: Field, public form?: Form, private _stepper?: Stepper, public order: number = 0 ) { this.fieldId = this.field.id; this.formId = this.form.id; this.stepperId = _stepper.id; } public stepperId: number = 0; public fieldId: number; public id: number = 0; public formId: number = 0; public options: FieldAttributeOptions = { text: { mask: {}, regex: {} }, integer: { mask: {}, regex: {} }, decimal: { mask: {}, regex: {} }, select: {}, multiSelect: {} }; public updated: boolean = false; public created: boolean = false; } export enum FieldType { Integer = 10, Decimal = 20, Text = 30, TextArea = 40, List = 50, DependentList = 60, Address = 100 } export interface Mask { content?: string; prefix?: string; suffix?: string; dropSpecialCharacter?: boolean; showMask?: boolean; clearIfNotMatch?: boolean; } export interface Regex { value?: string; message?: string; } export interface FieldAttributeOptions { text?: TextOptions; integer?: NumberOptions; decimal?: NumberOptions; select?: SelectOptions; multiSelect?: MultiSelectOptions; } export interface TextOptions extends NumberTextOptions { default?: string; } export interface NumberOptions extends NumberTextOptions { min?: number; max?: number; } export interface SelectOptions extends BaseOptions { default?: number; } export interface MultiSelectOptions extends BaseOptions { default?: Array<number>; } export interface NumberTextOptions extends BaseOptions { maxLength?: number; minlength?: number; regex?: Regex; mask?: Mask; } export interface BaseOptions { default?: any; placeholder?: string; required?: boolean; hidden?: boolean; readonly?: boolean; } <file_sep>import { Component, OnInit, Input, TemplateRef, Injector } from '@angular/core'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { icon } from 'src/app/master/components/icon/icon.component'; import { DisplayView } from 'src/app/master/components/display-view/nav-view.component'; import { contextmenu } from './folder-contextmenu.const'; import { VOLUMEICON, SERVERICON } from 'src/app/master/components/icon/icon.const'; import { Table } from 'src/app/enums/table.enum'; import { FactoryService } from 'src/app/master/states/factory.service'; import { Folder } from '../../data/folder/folder.model'; import { FolderableService } from 'src/app/master/states/folderable.service'; @Component({ selector: 'app-folder-item', templateUrl: './folder-item.component.html', styleUrls: ['./folder-item.component.sass'] }) export class FolderItemComponent implements OnInit { private service: FolderableService<any, Folder> constructor(private injector: Injector) { } @Input() public item: TreeviewItem @Input() vColumns: any[] = [] @Input() type: Table @Input() public template: TemplateRef<{ item: TreeviewItem }>; @Input() display: DisplayView = DisplayView.inline public DisplayView = DisplayView @Input() public link: string public folderIcon: icon = { name: 'folder', class: 'yellow-text text-darken-1' } get isEdit(): boolean { return Table.Folder.toString() + this.item.entity.id == this.service.currentEdit } ngOnInit(): void { this.item.pEntity && this.item.pEntity.id || (this.folderIcon = VOLUMEICON) this.item.entity && this.item.entity.id || (this.folderIcon = SERVERICON) this.service = new FactoryService(this.injector).get(this.type) } public contextmenu = [ { icon: "folder-plus", action: (item) => item.entity.showAdd = true, text: "Create Folder", visible: (item) => true }, { icon: "folder-edit", action: (item) => this.service.getTreeview().subscribe(r => this.service.currentEdit = Table.Folder.toString() + item.entity.id), text: "Edit Folder", visible: (item) => true }, { icon: "folder-remove", action: (item) => item.entity.showEdit = true, text: "Delete Folder", visible: (item) => true } , { icon: "folder-pound", action: (item) => item.entity.showEdit = true, text: "Rename Folder", visible: (item) => true } ] public klose(){ this.service.currentEdit = null } } <file_sep> using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MiniS.Areas.Models; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Data.Models { public class ListItem : Groupable<List> { public bool Dependant{get; set;} public long? ParentListId {get; set;} public long? ParentListItemId {get; set;} public ListItem ParentListItem {get; set;} [InverseProperty("ParentListItem")] public List<ListItem> ListItemChildren {get; set;} [NotMapped] public bool ShowEdit {get; set; } = false; } public class ListItemConfiguration : GroupableConfiguration<ListItem, List> { } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Admin.Models { public class Account: Identificable, IIdentificable { [Required] [MaxLength(70)] public string NormalizedName {get; set;} // public ICollection<AccountUser> Users {get; set;} [Timestamp] public byte[] Timestamp { get; set; } } public class AccountConfiguration: IdentificableConfiguration<Account> { } }<file_sep>import { Injectable } from '@angular/core'; import { Account } from './account.model'; import { HttpClient } from '@angular/common/http'; import { ActivatedRoute, Router } from '@angular/router'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { AccountUser } from './security/account-security-user/account-user.model'; import { AccountSecurityAuthService } from './security/account-security-auth/account-security-auth.service'; import { User } from './security/user/state/user.model'; import { TranslocoService } from '@ngneat/transloco'; @Injectable({ providedIn: 'root' }) export class AccountService { constructor(private http: HttpClient, private route: ActivatedRoute, private translocoService: TranslocoService, private router: Router) { } public account: Account public languages: any[] public currLang: any public authUser: User = null public url: string = "" getAccount(account: string): Observable<Account> { return this.http.get<Account>(`api/admin/account/${account}`).pipe(tap(r => { this.account = r })) } public getLanguages(): Observable<any> { return this.http.get<any>("api/language/all").pipe(tap(r => { this.languages = r })) } public currentLang(): Observable<any> { return this.http.get<any>("api/language").pipe(tap(r => { this.currLang = r this.translocoService.setActiveLang(r.value) })) } public setLanguage(l: any): Observable<any> { return this.http.post<any>("api/language", l).pipe(tap(r => { this.translocoService.setActiveLang(r.value) console.log(this.translocoService.getActiveLang()) this.currLang = r })) } redirectToLogin() { this.router.navigateByUrl(`/${this.account.normalizedName}/security/auth/login`) } } <file_sep>/* using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using MiniS.Areas.Data.Models; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using Newtonsoft.Json.Linq; namespace MiniS.Areas.Data.Repositories { public class DatabaseFieldAttributeRepository { private AppDbContext _dbContext; private List<FieldAttribute> _fieldAttributes; private FieldAttribute _fieldAttribute; private object _defaultValue; public DatabaseFieldAttributeRepository ( AppDbContext dbContext ) { _dbContext = dbContext; } public async Task<FieldAttribute> GetFieldAttribute (long fieldAttributeId, long accountId) { _fieldAttribute = await _dbContext.FieldAttributes.Where (fa => fa.Id == fieldAttributeId && fa.AccountId == accountId) .Include (fa => fa.Field).ThenInclude (f => f.List).Include (fa => fa.Field).ThenInclude (f => f.relatedField).FirstOrDefaultAsync (); return _fieldAttribute; } public async Task<List<FieldAttribute>> GetFieldAttributes (long formId, long accountId) { _fieldAttributes = await _dbContext.FieldAttributes.Where (fa => fa.Account.Id == accountId && fa.FormId == formId) .Include (fa => fa.Field).ThenInclude (f => f.List) .Include (fa => fa.Field).ThenInclude (f => f.relatedField) .ToListAsync (); /* Fetch all folders belonging to the current account and child of the parent folder return _fieldAttributes; } public async Task<FieldAttribute> CreateFieldAttribute (FieldAttribute fieldAttribute, FieldAttribute model, AccountUser autUser) { fieldAttribute.Options = model.Options; fieldAttribute.Name = model.Name; fieldAttribute.Description = model.Description; await _dbContext.AddAsync (fieldAttribute); await _dbContext.SaveChangesAsync (autUser); return model; } public async Task<FieldAttribute> UpdateFieldAttribute (FieldAttribute model, AccountUser autUser) { _fieldAttribute.Options = model.Options; _fieldAttribute.Name = model.Name; _fieldAttribute.Description = model.Description; _dbContext.Update (_fieldAttribute); await _dbContext.SaveChangesAsync (autUser); return _fieldAttribute; } public bool Exists (FieldAttribute model, bool update = false) { return _fieldAttributes.Any (ef => ef.Name.Equals (model.Name, StringComparison.OrdinalIgnoreCase)) && !(update && _fieldAttribute.Name.Equals (model.Name, StringComparison.OrdinalIgnoreCase) //ignore the same name if it's an update ); } public bool FieldHasAttribute (FieldAttribute model) { return _fieldAttributes.Any (fa => fa.Field.Id == model.Field.Id); } public FieldAttribute FindDField (FieldAttribute model) { return _fieldAttributes.Find (ef => ef.Id == model.Field.relatedField.Id); } /* public async Task<bool> ValidateDefault (FieldAttribute model, long accountId) { FieldType fieldType = model.Field.Column; if (fieldType == FieldType.List || fieldType == FieldType.DList) { if (model.Field.Multi) { JArray temp = (JArray) model.DefaultValue; if (!temp.HasValues) { _defaultValue = null; return true; } try { _defaultValue = temp.ToObject<long[]> (); } catch (Exception e) { return false; } ICollection<long> defaultAsCollection = _defaultValue as ICollection<long>; List<ListItem> listItems = await _dbContext.ListItems .Where (li => li.AccountId == accountId).ToListAsync (); return listItems.Count (li => defaultAsCollection.Contains (li.Id)) == defaultAsCollection.Count (); } else { try { _defaultValue = (long?) model.DefaultValue; return await _dbContext.ListItems .Where (li => li.AccountId == accountId && li.Id == (long) _defaultValue).CountAsync () > 0; } catch (Exception e) { return false; } } } if (fieldType == FieldType.Decimal) { try { _defaultValue = Convert.ToDecimal (model.DefaultValue); } catch (Exception e) { return false; } } if (fieldType == FieldType.Integer) { try { _defaultValue = Convert.ToInt64 (model.DefaultValue); } catch (Exception e) { return false; } } if (fieldType == FieldType.Text || fieldType == FieldType.TextArea) { try { string str = (string) model.DefaultValue; _defaultValue = String.IsNullOrWhiteSpace (str) ? null : str; } catch (Exception e) { return false; } } return true; } public async Task Delete (FieldAttribute fieldAttribute) { _dbContext.FieldAttributes.Remove (fieldAttribute); await _dbContext.SaveChangesAsync (); } } } */<file_sep>import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, CanActivateChild } from '@angular/router'; import { Observable, of } from 'rxjs'; import { switchMap } from 'rxjs/operators'; import { GroupService } from '../security/group/state/group.service'; @Injectable({ providedIn: 'root' }) export class AccountGroupGuard implements CanActivateChild { constructor(private groupService: GroupService){} canActivateChild( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return this.groupService.getTreeview().pipe(switchMap(a => of(true))) } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { TreeviewItem } from '../../ngx-treeview'; import { InputType } from 'src/app/enums/input-type.enum'; @Component({ selector: '[app-datatable-td]', templateUrl: './datatable-td.component.html', styleUrls: ['./datatable-td.component.sass'] }) export class DatatableTdComponent implements OnInit { constructor() { } public inputType = InputType ngOnInit() { } @Input() item: TreeviewItem @Input() column: any } <file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { InputType } from 'src/app/enums/input-type.enum'; import { DatatableService } from '../datatable.service'; import { Filter, ColDisplay, Expression } from '../datatable.interface'; @Component({ selector: '[app-datatable-filters]', templateUrl: './datatable-filters.component.html', styleUrls: ['./datatable-filters.component.sass'] }) export class DatatableFiltersComponent implements OnInit { constructor(private datatableService: DatatableService) { } @Input() columns: Array<ColDisplay> @Input() filters: Array<{ [key: string]: Expression }> @Output() filtersChange: EventEmitter<Array<{ [key: string]: Expression }>> = new EventEmitter<Array<{ [key: string]: Expression }>>() keys = Object.keys ngOnInit() { this.filters = [this.initFilter()] this.emitFilters() } addFilter() { this.filters.push(this.initFilter()) this.emitFilters() } removeFilter(index: number) { this.filters.splice(index, 1) this.emitFilters() } initFilter(): Filter { let filter: { [key: string]: Expression } = {} this.columns.forEach(k => { filter[k.key] = { value: null, equality: this.inputTypeToEquality(k.inputType) } }) return filter } private inputTypeToEquality(t: InputType): string { switch (t) { case InputType.Text: return 'contains' case InputType.Textarea: return 'contains' case InputType.MultiSelect: return 'in' case InputType.Select: return 'in' case InputType.Date: return 'equalsDate' default: return 'none' } } private emitFilters(){ this.filtersChange.emit(this.filters) } isCleanFilter(index: number): boolean { const filter = this.filters[index] return this.keys(filter).every(k => filter[k].value == null || filter[k].value == '' || filter[k].value == {} && filter[k].value == [] || filter[k].value == 'undefined') } get hasOneClean(): boolean { return this.filters.some((f, i) => this.isCleanFilter(i)) } clearFilter(index: number) { this.filters[index] = this.initFilter() } /* get filters():Array<Filter>{ return this.datatableService.filters } */ } <file_sep>import { Groupable } from 'src/app/master/base-model/groupable.model'; import { Folder } from 'src/app/account/data/folder/folder.model'; /* export interface User { id: number | string; } */ export class User extends Groupable<Folder>{ public userName: string public email: string public password: string public confirmPassword: string public accesses: any = {} public userLevel: UserLevel = UserLevel.Regular public firstName?: string = "" public lastName?: string ="" public get name() { return (this.firstName + " " + this.lastName).trim() } public set name(v:string){ } } export function createUser(params: Partial<User>) { return { } as User; } export enum UserLevel { Regular = 10, Group = 100 | Regular, Access = 1000 | Regular, Admin = 10000 | Access | Group, Super = 100000 | Admin, } <file_sep># MiniS MiniS <file_sep>import { Component, OnInit, Input, TemplateRef, Output, EventEmitter } from '@angular/core'; import { Table } from 'src/app/enums/table.enum'; import { TreeviewItem, TreeviewConfig } from 'src/app/widgets/ngx-treeview'; import { ITrackable } from '../../base-model/trackable.model'; @Component({ selector: 'app-treeview-folderable', templateUrl: './treeview-folderable.component.html', styleUrls: ['./treeview-folderable.component.sass'] }) export class TreeviewFolderableComponent implements OnInit { constructor() { } @Input('item-template') itemTemplate: TemplateRef<TreviewItemContext>; @Input('volume-template') volumeTemplate: TemplateRef<{ showAddVolume: boolean }>; @Input() items: TreeviewItem[] @Input() type: Table @Input() loading: boolean public routerLink: string = "link to enter" public showAddVolume: boolean = false @Input() public multi: boolean = true @Input() public checkbox: boolean = false @Input() public noLink = false public treeviewConfig: TreeviewConfig = TreeviewConfig.create({ hasAllCheckBox: this.checkbox }) @Output() selectedChange: EventEmitter<ITrackable[]> = new EventEmitter() public onSelect = (selected: ITrackable[]) => this.selectedChange.emit(selected) ngOnInit() { } toggleCheck(item: TreeviewItem, onCheckChange: Function, event: Event) { const checked = item.checked event.preventDefault() if (!this.multi) { if (item.type == Table.Folder) return; this.items.forEach(item => item.setCheckedRecursive(false)) } item.checked = !checked; onCheckChange() } } export interface TreviewItemContext { item: TreeviewItem; } <file_sep>import { Groupable } from 'src/app/master/base-model/groupable.model'; import { FieldAttribute } from '../field-attribute/field-attribute.model'; import { Database } from '../../state/database.model'; export function createForm(params: Partial<Form>) { return { } as Form; } export class Form extends Groupable<Database> { public fieldAttributes: Array<FieldAttribute> = [] public showAdd: boolean = false public showFields: boolean = false public fieldProcessing: boolean = false public showDatabase: boolean = false } <file_sep>import { Component, OnInit, Output, Input, EventEmitter, ViewChild, ElementRef } from '@angular/core'; import { Database } from '../../database/state/database.model'; import { FieldType, Field } from '../state/field.model'; import { FieldService } from '../state/field.service'; import { ListService } from '../../list/state/list.service'; import { trigger } from '@angular/animations'; @Component({ selector: 'app-field-edit', templateUrl: './field-edit.component.html', styleUrls: ['./field-edit.component.sass'] }) export class FieldEditComponent implements OnInit { constructor( private fieldService: FieldService, private listService: ListService ) { } public newField: Field public showAdd: boolean = false public currentIndex = -1 @Input('database') model: Database @Output() close: EventEmitter<any> = new EventEmitter() edit: boolean = false FieldType = FieldType @ViewChild("goTo", { static: false }) goTo: ElementRef; get fields() { return this.fieldService.entities$ } get listTreeview() { return this.listService.treeview$ } get fieldsLoading() { return this.fieldService.loader.set$ } get listTreeviewLoading() { return this.listService.store.loading$ } ngOnInit() { this.fieldService.updateParentId(this.model.id) this.fieldService.get().subscribe() this.listService.getTreeview().subscribe() // this.folderService.getFolderTreeView(0, Table.List).subscribe() } add(type: FieldType) { this.newField = new Field(type) this.showAdd = true setTimeout(r=> this.goTo.nativeElement.scrollIntoView({ behavior: "smooth" }), 300) } deleteField(index: number, field: Field) { this.model.fields.splice(index, 1) } cancel() { this.close.emit() } isStandard(field: Field): boolean { return [FieldType.text, FieldType.bigint, FieldType.varchar, FieldType.numeric].some(t => t == field.type) } /* get loading():boolean{ return false return this.dbService.loading || this.folderService.isLoading } */ /* isNumeric(field: Field, integer: boolean = false) { const a = integer ? [FieldType.Integer] : [FieldType.Integer, FieldType.Decimal] return a.indexOf(field.type) > -1 } */ get dListVisible(): boolean { return this.model.fields.some(f => (f.type == FieldType.dependentList || f.type == FieldType.list)) } /* get listTreeview(): Array<TreeviewItem>{ return this.folderService.folderTreeView } */ } <file_sep>import { Component, OnInit, Input } from "@angular/core"; import { Field } from "../../models/field"; import { AccountDataFieldBase } from "../account-data-field-base"; import { AccountDataDbService } from "../../account-data-db.service"; @Component({ selector: "app-account-data-db-dlist-field", templateUrl: "./account-data-db-dlist-field.component.html", styleUrls: ["./account-data-db-dlist-field.component.sass"] }) export class AccountDataDbDlistFieldComponent extends AccountDataFieldBase implements OnInit { public constructor(dbService: AccountDataDbService) { super(dbService); } @Input() dependableFields: Array<Field> = []; public ngOnInit() {} /* get treeviewList(): Array<TreeviewItem> { return this.folderService.folderTreeView } get isLoading(): boolean { return this.folderService.isLoading } */ /* get list() { console.log(this.field.list) return this.field.list } */ } <file_sep>import { AbstractControl, Validator, NG_VALIDATORS, ValidatorFn } from "@angular/forms"; import { Input, Directive } from "@angular/core"; import { equals } from '../helpers/string.helper'; export function ItemAlreadyExists(names: Array < string > , suffix: string, caseSensitive: boolean): ValidatorFn { return (control: AbstractControl): { [key: string]: any } | null => { return names.some(n => typeof n == "string" && equals(n,control.value + suffix, caseSensitive)) ? { 'itemAlreadyExists': { value: control.value } } : null; }; } @Directive({ selector: '[itemAlreadyExists]', providers: [{ provide: NG_VALIDATORS, useExisting: ItemAlreadyExistsDirective, multi: true }] }) export class ItemAlreadyExistsDirective implements Validator { @Input('itemAlreadyExists') items:Array < string > @Input('current') current : string = "" @Input() suffix : string = "" @Input() caseSensitive : boolean = false validate(control: AbstractControl): { [key: string]: any } | null { if(this.current && equals(this.current, control.value + this.suffix || "", this.caseSensitive)) return null return this.items.length > 0 ? ItemAlreadyExists(this.items, this.suffix,this.caseSensitive)(control) : null; } } <file_sep>import { BehaviorSubject } from 'rxjs'; import { LoaderStore as BaseLoaderStore, LoadingState } from 'src/app/master/states/loader.store'; export class LoaderStore extends BaseLoaderStore { public setPListitem$: BehaviorSubject<boolean> = new BehaviorSubject(false); constructor() { super(); } startLoading(loadingState: LoadingState) { super.startLoading(loadingState); switch(loadingState){ case LoadingState.setPListitems: this.setPListitem$.next(true); break; } } stopLoading(loadingState: LoadingState) { super.stopLoading(loadingState) switch(loadingState){ case LoadingState.setPListitems: this.setPListitem$.next(false); break; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; using MiniS.Areas.Models; using MiniS; using MiniS.Helpers; namespace MiniS.Areas.Services { public interface IAccountGroupService<Model, Parent> : IParentableService<Model, Parent>, IGroupableService { } public interface IGroupableService { } public abstract class AccountGroupService<Model, Parent> : ParentableService<Model, Parent>, IAccountGroupService<Model, Parent> where Model : IGroupable<Parent> where Parent : Accountable, IOGroupable { public AccountGroupService( AppDbContext dbContext, ILogger logger, IStringLocalizer<SharedResource> localizer, IParentableStore<Model, Parent> parentableStore, IParentableService<Parent> parentService ) : base(dbContext, logger, localizer, parentableStore, parentService) { _parentableStore = parentableStore; } public override async Task<Model> FetchModel(long id) { var model = await base.FetchModel(id); if (model != null) { if (!model.AllGroup) { try { model.Groups = GetGroups(model); } catch (Exception exception) { LogError(LoggingEvents.GetItemError, exception, String.Format("{0}-Get-Group-Error", _nameofModel)); AddErrorState("error", String.Format("{0}-Get-Group-Error", _nameofModel)); //modelstate //modelstate return model; } if (model.Groups.Count == 0) { LogError(LoggingEvents.GetItemError, null, String.Format("{0}-Get-Group-Empty", _nameofModel)); AddErrorState("count", String.Format("{0} {1} has no groups associated to it", _nameofModel, model.Name)); } } } LogInformation(LoggingEvents.GetItem, String.Format("{0}-Get-Group-success", _nameofModel)); return model; } public override async Task<List<Model>> FetchModels(long parentId, params object[] param) { var models = await base.FetchModels(parentId, param); try { foreach (Model model in models) model.Groups = GetGroups(model); if (!_authUser.UserLevel.HasFlag(Identity.Enums.UserLevel.Group)) models = models.Where(d => d.AllGroup || d.Groups.Any(d1 => _authUser.Groups.Contains(d1))).ToList(); LogInformation(LoggingEvents.GetItems, String.Format("{0}-Get-All-Group-success-", _nameofModel)); } catch (Exception ex) { LogError(LoggingEvents.GetItemError, ex, String.Format("{0}-Get-All-Group-Error", _nameofModel)); AddErrorState("getall-error", "Error occured when trying to fetch the {0} list", _nameofModel); } return models; } protected override Model PopulateModelWithGroup(Model model) { //If parent model is not allGroup then the model either, else model take the form value MODEL.AllGroup = (PARENT == null || PARENT.AllGroup) ? model.AllGroup : false; if (!MODEL.AllGroup) { if (model.Groups == null || model.Groups.Count == 0) { LogWarning(LoggingEvents.GetItemsEmpty, "{0} has no groups assosciated with it", _nameofModel); AddErrorState("No-group-submitted", "{0} {1} has no group submitted to it", _nameofModel, model.Name); return MODEL; } MODEL.Groups = IntersectGroup(model.Groups).Result; if (PARENT != null && PARENT.AllGroup) MODEL.Groups = MODEL.Groups.Intersect(PARENT.Groups, new IDEqualityComparer<Group>()).ToList(); if (MODEL.Groups.Count < 1) { LogError(LoggingEvents.GetItemError, null, String.Format("{0}-Get-Group-Empty", _nameofModel)); AddErrorState("Group-isempty", String.Format("{0}-Get-Group-Empty", _nameofModel)); }; } return MODEL; } protected IDbContextTransaction GetTransaction() => _dbContext.Database.BeginTransaction(); public override async Task TryUpdateModel(Model model) { using (var transaction = GetTransaction()) { base.TryUpdateModel(model).Wait(); try { _UpdateEntityGroup(MODEL, _table, /*Get the current EntityGroup*/ await _dbContext.GetEntityGroups(MODEL.Id, _table)); await _dbContext.SaveChangesAsync(_authUser); transaction.Commit(); } catch (Exception) { } } } public override async Task TryCreateModel(Model model) { using (var transaction = GetTransaction()) { try { base.TryCreateModel(model).Wait(); _UpdateEntityGroup(model, _table, new List<EntityGroup>()); await _dbContext.SaveChangesAsync(_authUser); transaction.Commit(); } catch (Exception) { } } } protected void _UpdateEntityGroup(Model model, Table table, List<EntityGroup> currentEntityGroup) { if (!model.AllGroup && model.Groups != null && model.Groups.Count > 0) { _dbContext.UpdateManyToMany(model.Groups.Select( g => new EntityGroup() { EntityId = model.Id, Table = table, GroupId = g.Id, AccountId = _authUser.AccountId } ).ToList(), currentEntityGroup); } else { _dbContext.UpdateManyToMany(new List<EntityGroup>(), currentEntityGroup); } } public List<Group> GetGroups(Model model) { return _dbContext.GetGroups(model.Id, _table).Result; } public async Task<List<Group>> IntersectGroup(List<Group> groups) { var query = await _dbContext.Groups.Where<Group>(g => g.AccountId == _authUser.AccountId).ToListAsync(); return query.Intersect<Group>(groups, new IDEqualityComparer<Group>()).ToList(); } public override bool CanAccessGroupResouce(IOGroupable resource) { if (_authService.CanAccessGroupResouce(resource)) return true; LogWarning(LoggingEvents.ForbiddenItem, "cannot-access-resource-account"); return false; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Enums; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master; using MiniS.Areas.Master.Enums; using MiniS.Areas.Models; using MiniS; using MiniS.Areas.Services; using MiniS.Helpers; namespace MiniS.Areas.Identity.Services { public class AccountUserService : ParentableService<AccountUser, Folder> { private readonly UserManager<AccountUser> _userManager; private readonly SignInManager<AccountUser> _signInManager; public AccountUserService(AppDbContext dbContext, ILogger<GroupService> logger, IStringLocalizer<SharedResource> localizer, FolderService folderService, IParentableStore<AccountUser, Folder> parentableStore, UserManager<AccountUser> userManager, SignInManager<AccountUser> signInManager) : base(dbContext, logger, localizer, parentableStore, folderService) { _userManager = userManager; _signInManager = signInManager; } protected override Table _table => Table.User; protected IDbContextTransaction GetTransaction() => _dbContext.Database.BeginTransaction(); public async Task<AccountUser> Login(Login login) { // Try to find the account user by userName AccountUser user = await _userManager.FindByNameAsync(login.UserName); // Otherwise try to find the account user by email if (user == null) user = await _userManager.FindByEmailAsync(login.UserName); // If no account user was found return a 404 not found response if (user == null) { NotFound = true; LogError(LoggingEvents.GetItemError, null, String.Format("{0}-Item-NotFound", _nameofModel)); AddErrorState("user-not-found", "there is no user with that username"); return null; } // Sign in SignInResult result = await _signInManager.PasswordSignInAsync(user, login.Password, login.RememberMe, user.LockoutEnabled); // If sign in succeed, retur a 200 response withe signed in account user if (result.Succeeded) LogInformation(LoggingEvents.GetItem, "userLogged IN successfully"); else // If user is lockedout return a 400 response if (result.IsLockedOut) { LogWarning(LoggingEvents.ForbiddenItem, "User Locket Out"); AddErrorState("locked-out", "user is locked out"); } // otherwise if other errors occured return 400 error response else { LogError(LoggingEvents.GetItemsEmpty, null, " error logging in"); AddErrorState("error-login", "Invalid login attempt."); } return user; } public override async Task<AccountUser> FetchModel(long id) { var MODEL = await base.FetchModel(id); if (HasSameAccessLevel(MODEL.Accesses)) { LogInformation(LoggingEvents.GetItem, "User Has same access level as the authenticated"); return MODEL; } else { LogError(LoggingEvents.GetItemError, null, "user hsa no same level of access as trhe authentiacted user"); AddErrorState("not-same access level", "User Has same access level as the authenticated"); return null; } } public override async Task<List<AccountUser>> FetchModels(long parentId, params object[] param) { var models = await base.FetchModels(parentId, param); try { foreach (AccountUser model in models) model.Groups = GetGroups(model); if (!_authUser.UserLevel.HasFlag(Identity.Enums.UserLevel.Group)) models = models.Where(d => (d.AllGroup || d.Groups.Any(d1 => _authUser.Groups.Contains(d1))) && HasSameAccessLevel(d.Accesses) ).ToList(); LogInformation(LoggingEvents.GetItems, String.Format("{0}-Get-All-Group-success-", _nameofModel)); } catch (Exception ex) { LogError(LoggingEvents.GetItemError, ex, String.Format("{0}-Get-All-Group-Error", _nameofModel)); AddErrorState("getall-error", "Error occured when trying to fetch the {0} list", _nameofModel); } return models; } public override async Task TryCreateModel(AccountUser model) { // we do some Validations if(await ValidationFails(model)) return; using (var transaction = GetTransaction()) { // Create new Instance of the Model PopulateCreateModel( model); MODEL.AccountId = _authUser.AccountId; MODEL.CreatedBy = _authUser.UserName; MODEL.CreatedAt = DateTime.Now; PopulateModelWithGroup(model); if (Fails()) return; try { IdentityResult result = await _userManager.CreateAsync(MODEL, MODEL.Password); if (result.Succeeded) LogInformation(10, "User created a new account with password."); else { foreach (IdentityError error in result.Errors) { LogError(LoggingEvents.GetItemError, null, error.Description); AddErrorState(error.Code, error.Description); } return; } } catch (Exception ex) { LogError(LoggingEvents.GetItemError, ex, String.Format("{0}-Create-Error", _nameofModel)); AddErrorState("create-error", String.Format("{0}-Create-Error", _nameofModel)); return; } _UpdateEntityGroup(model, _table, new List<EntityGroup>()); await _dbContext.SaveChangesAsync(_authUser); transaction.Commit(); } } protected void _UpdateEntityGroup(AccountUser model, Table table, List<EntityGroup> currentEntityGroup) { if (model.UserLevel.HasFlag(UserLevel.Group)) { _dbContext.UpdateManyToMany(new List<EntityGroup>(), currentEntityGroup); } else { _dbContext.UpdateManyToMany(model.Groups.Select( g => new EntityGroup() { EntityId = model.Id, Table = table, GroupId = g.Id, AccountId = _authUser.AccountId } ).ToList(), currentEntityGroup); } } public override async Task TryUpdateModel(AccountUser model) { // #endregionupdate user properties // Update user trackable properties // Includes UserGroup related data to use it for removing existing manytomany relationship // update User Password // we do some Validation if(await ValidationFails(model)) return; using (var transaction = GetTransaction()) { /* if (await ExistsByName(parent.Id, model.Name, MODEL.Name)) { LogWarning(LoggingEvents.GetItemError, String.Format("Name-already-exist", model.Name)); return MODEL; } */ MODEL = await _userManager.FindByIdAsync(model.Id.ToString()); PopulateUpdateModel(model); if (model.Password != null) MODEL.PasswordHash = _userManager.PasswordHasher.HashPassword(MODEL, model.Password); //FetchAndSetModel or SetModel must be called First PopulateModelWithGroup(model); if (Fails()) return; try { IdentityResult result = await _userManager.UpdateAsync(MODEL); if (result.Succeeded) { LogInformation(2, "User updated."); } foreach (IdentityError error in result.Errors) { LogError(1, null, error.Description); return; } } catch (Exception ex) { LogError(LoggingEvents.GetItemError, ex, String.Format("{0}-Update-Error", _nameofModel)); return; } try { _UpdateEntityGroup(model, _table, /*Get the current EntityGroup*/ await _dbContext.GetEntityGroups(model.Id, _table)); await _dbContext.SaveChangesAsync(_authUser); transaction.Commit(); LogInformation(1, "saves group andcommited"); } catch (Exception ex) { LogError(LoggingEvents.GetItemError, ex, String.Format("{0}-Update-Error", _nameofModel)); } } } protected override AccountUser PopulateModelWithGroup(AccountUser model) { if (!MODEL.UserLevel.HasFlag(UserLevel.Group)) { MODEL.Groups = IntersectGroup(model.Groups).Result; /* if (parent != null) MODEL.Groups = MODEL.Groups.Intersect(parent.Groups, new IDEqualityComparer<Group>()).ToList(); */ if (MODEL.Groups.Count < 1) { LogError(LoggingEvents.GetItemError, null, String.Format("{0}-Get-Group-Empty-intersect", _nameofModel)); }; } return MODEL; } protected override AccountUser PopulateUpdateModel(AccountUser model) { base.PopulateUpdateModel(model); MODEL.UserName = model.UserName; MODEL.Email = model.Email; MODEL.FirstName = model.FirstName; MODEL.LastName = model.LastName; MODEL.UserLevel = model.UserLevel; MODEL.Accesses = AdjustAccesses(model.Accesses); MODEL.LastUpdatedBy = _authUser.UserName; MODEL.Password = <PASSWORD>; MODEL.LastUpdatedAt = DateTime.Now; return MODEL; } public List<Group> GetGroups(AccountUser model) { return _dbContext.GetGroups(model.Id, _table).Result; } public async Task<List<Group>> IntersectGroup(List<Group> groups) { var query = await _dbContext.Groups.Where<Group>(g => g.AccountId == _authUser.AccountId).ToListAsync(); return query.Intersect<Group>(groups, new IDEqualityComparer<Group>()).ToList(); } public Dictionary<Access, Right> AdjustAccesses(Dictionary<Access, Right> accesses) { var acc = new Dictionary<Access, Right>(); foreach (KeyValuePair<Access, Right> entry in accesses) { acc[entry.Key] = _authUser.UserLevel.HasFlag(UserLevel.Access) || !_authUser.Accesses.ContainsKey(entry.Key) ? entry.Value : _authUser.Accesses[entry.Key] < entry.Value ? _authUser.Accesses[entry.Key] : entry.Value; } return acc; } public bool HasSameAccessLevel(Dictionary<Access, Right> accesses) { foreach (KeyValuePair<Access, Right> entry in accesses) if (!_authUser.UserLevel.HasFlag(UserLevel.Access) && _authUser.Accesses[entry.Key] < entry.Value) return false; return true; } public Task<bool> ExistsByEmail(string email, string current){ if (StringUtilities.Equals(email, current)) return Task.FromResult(false); return ExistsBy(m => StringUtilities.Equals(m.Email,email)); } public Task<bool> ExistsByUserName(string userName, string current){ if (StringUtilities.Equals(userName, current)) return Task.FromResult(false); return ExistsBy(m => StringUtilities.Equals(m.UserName,userName)); } } }<file_sep>using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using MiniS.Areas.Data.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; using MiniS; using MiniS.Areas.Services; namespace MiniS.Areas.Data.Services { public class ListItemService : AccountGroupService<ListItem, List> { public ListItemService ( AppDbContext dbContext, ILogger <ListItemService> logger, IStringLocalizer<SharedResource> localizer, IParentableStore<ListItem, List> parentableStore, ListService listService) : base (dbContext,logger, localizer, parentableStore, listService) { } protected override Table _table => Table.ListItem; protected override ListItem PopulateCreateModel(ListItem model){ base.PopulateCreateModel(model); MODEL.Dependant = model.Dependant; MODEL.ParentListItemId = model.ParentListItemId; MODEL.ParentListId = model.ParentListId; return MODEL; } public override IQueryable<ListItem> GetModels(long parentId, params object[] param){ return base.GetModels(parentId, param).Include(ListItem=>ListItem.ParentListItem); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using MiniS.Areas.Admin.Models; using MiniS.Areas.Identity.Enums; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Identity.Authorization { public interface IResource : IOGroupable, IOAccountable { } public class AuthorizationService { private AccountUser _authUser; private Account _account; private bool _authorized = false; private string[] _message; private readonly HttpContext _httpContext; private Access _access; public AuthorizationService( IHttpContextAccessor accessor ) { _httpContext = accessor.HttpContext; _authUser = (AccountUser)_httpContext.Items["authUser"]; _account = (Account)_httpContext.Items["account"]; } public void SetAccess(Access access) { _access = access; } public HttpContext GetHttpContext() => _httpContext; public AccountUser GetAuthUser() => _authUser; public Account GetAccount() => _account; public long GetAccountId() => _account.Id; public bool HasRight(Right right) { return _authUser.UserLevel.HasFlag(Enums.UserLevel.Access) || (_authUser.Accesses.ContainsKey(_access) && _authUser.Accesses[_access] >= right); } public bool NotAuthorized() { return !_authorized; } public bool CanAccessAccountRessource(IOAccountable resource) { return _authUser.AccountId == resource.AccountId; } public bool CanAccessGroupResouce(IOGroupable resource) { return _authUser.UserLevel.HasFlag(Enums.UserLevel.Group) || resource.AllGroup || resource.Groups.Any(r => _authUser.Groups.Contains(r)); } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MiniS.Areas.Admin.Models; using MiniS.Areas.Data.Models; using MiniS.Areas.Identity.Controllers; using MiniS.Areas.Identity.Enums; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; using MiniS.Areas.Models; namespace MiniS.Areas.Identity.Models { public class AccountUser : IdentityUser<long>, IUser, IGroupable<Folder>/*, IParentable<Folder> */ { [Required] [Remote(action: nameof(AccountUserController.ExistByParentId), controller: nameof(AccountUserController))] public long ParentId { get; set; } [Required] public string LastName { get; set; } public string FirstName { get; set; } [Required(ErrorMessage = "An account user must be assosiated to an account")] public long AccountId { get; set; } public Account Account { get; set; } [Required(ErrorMessage = "The email field is required")] [EmailAddress] [ProtectedPersonalData] public override string Email { get; set; } public UserLevel UserLevel { get; set; } public Dictionary<Access, Right> Accesses { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public DateTime CreatedAt { get; set; } public string CreatedBy { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public DateTime LastUpdatedAt { get; set; } public string LastUpdatedBy { get; set; } public DateTime? Deleted { get; set; } [NotMapped] public string Password { get; set; } [NotMapped] [Compare("Password")] public string ConfirmPassword { get; set; } public bool AllGroup { get; set; } = false; [NotMapped] public List<Group> Groups { get; set; } /* public long? ParentId { get; set; } public Folder Parent { get; set; } */ public string Description { get; set; } public Folder Parent { get; set; } public Table ParentTable => Table.Folder; public System.Type ParentType => typeof(Folder); public string Name { get => FirstName + " " + LastName; set { } } public Table Table => Table.User; } public class AccountUserConfiguration : IEntityTypeConfiguration<AccountUser> { public void Configure(EntityTypeBuilder<AccountUser> builder) { builder.Property(e => e.CreatedAt).HasDefaultValueSql("datetime('now')"); //replace by getdate for sql server builder.Property(e => e.LastUpdatedAt).HasDefaultValueSql("datetime('now')"); //replace by getdate for sql server builder.Property(e => e.Deleted).HasDefaultValue(null); // Set delete flag to null by default builder.HasQueryFilter(t => t.Deleted == null); //soft delete builder.Property(e => e.CreatedAt).HasDefaultValueSql("datetime('now')"); //replace by getdate for sql server builder.Property(e => e.LastUpdatedAt).HasDefaultValueSql("datetime('now')"); //replace by getdate for sql server builder.Property(e => e.UserLevel).HasConversion(new EnumToStringConverter<UserLevel>()).HasDefaultValue(UserLevel.Regular); // Value converter } } }<file_sep>import { Injectable } from '@angular/core'; import { QueryEntity } from '@datorama/akita'; import { StepperStore, StepperState } from './stepper.store'; @Injectable({ providedIn: 'root' }) export class StepperQuery extends QueryEntity<StepperState> { constructor(protected store: StepperStore) { super(store); } } <file_sep>import { Component, Input } from "@angular/core"; import { AccountDataFieldBase } from "../account-data-field-base"; import { TreeviewItem, TreeviewHelper } from "src/app/widgets/ngx-treeview"; import { List } from "../../../models/list.model"; @Component({ selector: "app-account-data-db-address-field", templateUrl: "./account-data-db-address-field.component.html", styleUrls: ["./account-data-db-address-field.component.sass"] }) export class AccountDataDbAddressFieldComponent extends AccountDataFieldBase { public provinceListTreeview: Array<TreeviewItem>; public cityListTreeview: Array<TreeviewItem>; public streetListTreeview: Array<TreeviewItem>; public showProvinceList: boolean; public showCityList: boolean; public showStreetList: boolean; public ngOnInit() {} @Input() public listTreeview: Array<TreeviewItem>; deleteField(force: boolean = false) { this.database.fieldProcessing = false; if (force) this.dbService .deleteField(this.database.id, this.field.id) .subscribe(r => this.delete.emit()); this.field.created ? (this.field.updated = true) : this.delete.emit(); } updateField(value: any) {} public onSelect( selected: Array<List>, type: "country" | "province" | "city" ): void { if (type == "country") this.showProvinceList = this.showCityList = this.showStreetList = false; else if (type == "province") this.showCityList = this.showStreetList = false; else this.showStreetList = false; if (selected.length == 1) { const selectedId = selected[0].id; const fn = item => item.entity.pListId == selectedId; if (type == "country") { this.provinceListTreeview = TreeviewHelper.filterTreeviewItems( this.listTreeview, fn ); this.showProvinceList = true; } else if (type == "province") { this.cityListTreeview = TreeviewHelper.filterTreeviewItems( this.listTreeview, fn ); this.showCityList = true; } else if (type == "city") { this.streetListTreeview = TreeviewHelper.filterTreeviewItems( this.listTreeview, fn ); this.showStreetList = true; } } } } <file_sep>// inspired by Angular resizable (<NAME>) import { Directive, ElementRef, Input, Renderer2} from '@angular/core'; @Directive({ selector: '[resizable]' }) export class ResizableDirective{ constructor(private el: ElementRef, private renderer: Renderer2) { renderer.addClass(el.nativeElement, 'resizable') this.style = window.getComputedStyle(el.nativeElement, null) let that = this this.rDirection.forEach(function (direction) { let grabber = renderer.createElement('div') // add class for styling purposes renderer.setAttribute(grabber, 'class', 'rg-' + direction) grabber.innerHTML = '<span></span>' renderer.appendChild(el.nativeElement, grabber) renderer.listen(grabber, 'ondragstart', function () { return false; }) let down = function (e) { if (!this.rDisabled && (e.which === 1 || e.touches)) { // left mouse click or touch screen this.dragStart(e, direction); } } renderer.listen(grabber, 'mousedown', down.bind(that)) renderer.listen(grabber, 'touchstart', down.bind(that)) }) } @Input() resizable: any = null @Input('r-directions') rDirection: Array<string> = ['right'] @Input('r-disabled') rDisabled: boolean = false @Input('r-flex') rFlex: boolean = false dragDir: 'left' | 'right' | 'top' | 'bottom' axis: 'x' | 'y' start: number style: CSSStyleDeclaration w: number h: number flexBasis = 'flexBasis' in document.documentElement.style ? 'flexBasis' : 'webkitFlexBasis' in document.documentElement.style ? 'webkitFlexBasis' : 'msFlexPreferredSize' in document.documentElement.style ? 'msFlexPreferredSize' : 'flexBasis' info: any listeners = [] dragStart = (e, direction) => { this.dragDir = direction; this.axis = this.dragDir === 'left' || this.dragDir === 'right' ? 'x' : 'y' this.start = this.axis === 'x' ? this.getClientX(e) : this.getClientY(e) this.w = parseInt(this.style.getPropertyValue('width')) this.h = parseInt(this.style.getPropertyValue('height')) //prevent transition while dragging this.renderer.addClass(this.el.nativeElement, 'no-transition') this.listeners.push(this.renderer.listen(document, 'mouseup', this.dragEnd)) this.listeners.push(this.renderer.listen(document, 'mousemove', this.dragging)) this.listeners.push(this.renderer.listen(document, 'touchend', this.dragEnd)) this.listeners.push(this.renderer.listen(document, 'touchmove', this.dragging)) // Disable highlighting while dragging if (e.stopPropagation) e.stopPropagation() if (e.preventDefault) e.preventDefault() e.cancelBubble = true e.returnValue = false // updateInfo(e); // scope.$emit('angular-resizable.resizeStart', info); } dragging = (e) => { let prop, offset = this.axis === 'x' ? this.start - this.getClientX(e) : this.start - this.getClientY(e); switch (this.dragDir) { case 'top': prop = this.rFlex ? 'flexBasis' : 'height' this.renderer.setStyle(this.el.nativeElement, prop, this.h + offset + 'px') break; case 'bottom': prop = this.rFlex ? 'flexBasis' : 'height' this.renderer.setStyle(this.el.nativeElement, prop, this.h - offset + 'px') break; case 'right': prop = this.rFlex ? 'flexBasis' : 'width' this.renderer.setStyle(this.el.nativeElement, prop, this.w - offset + 'px') break; case 'left': prop = this.rFlex ? 'flexBasis' : 'width' this.renderer.setStyle(this.el.nativeElement, prop, this.w + offset + 'px') break } // updateInfo(e) } dragEnd = (e) => { // updateInfo(); // scope.$emit('angular-resizable.resizeEnd', info); // scope.$apply(); this.listeners.forEach(l => l()) // this.renderer.listen(document, 'mouseup', this.dragEnd) // this.renderer.listen(document, 'mousemove', this.dragging) // this.renderer.listen(document, 'touchend', this.dragEnd) // this.renderer.listen(document, 'touchmove', this.dragging) this.listeners = [] this.renderer.removeClass(this.el.nativeElement, 'no-transition') }; private getClientX(e) { return e.touches ? e.touches[0].clientX : e.clientX }; private getClientY(e) { return e.touches ? e.touches[0].clientY : e.clientY; }; private updateInfo(e) { this.info.width = false this.info.height = false if (this.axis === 'x') this.info.width = parseInt(this.el.nativeElement.style[this.rFlex ? 'flexBasis' : 'width']) else this.info.height = parseInt(this.el.nativeElement.style[this.rFlex ? 'flexBasis' : 'height']) this.info.id = this.el.nativeElement.id this.info.evt = e } }<file_sep>import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-icon', template: ` <i class="mdi mdi-{{primaryIcon}} {{primaryClass}}" style="font-size:{{size}}em" ></i> <span><ng-content></ng-content><span>` /* ` <fa-layers [fixedWidth]="true"> <fa-icon icon="{{primaryIcon}}" class="{{primaryClass}}" [size]="size"></fa-icon> <fa-icon icon="{{secondaryIcon}}" class="{{secondaryClass}}" *ngIf="!!secondaryIcon" transform="shrink-3 up-6 right-6"></fa-icon> </fa-layers> <ng-content></ng-content> ` */ }) export class IconComponent implements OnInit { constructor() { } ngOnInit() { } @Input() set icon(value: string | icon) { if(typeof value === 'string') this.primaryIcon = value else { this.primaryIcon = value.name this.primaryClass = value.class } } @Input('klass') set klass(value:string){ this.primaryClass = value } public primaryIcon: string public primaryClass: string @Input('icon-2') secondaryIcon:string @Input('icon-class-2') secondaryClass @Input('size') size: string = "1.25" } export interface icon { name: string, class: string } <file_sep>import { Injectable } from '@angular/core'; import { FolderableService } from 'src/app/master/states/folderable.service'; import { Group } from './group.model'; import { Folder } from 'src/app/account/data/folder/folder.model'; import { HttpClient } from '@angular/common/http'; import { AccountService } from 'src/app/account/account.service'; import { Table } from 'src/app/enums/table.enum'; @Injectable() export class GroupService extends FolderableService<Group> { protected type = Table.Group protected getFolderUrl(path?: string) { let url = [`api/${this.account}/data/group/${this.parentId}/folder`] if (path) url.push(path) return url.join('/') } get account(){ return this.accountService.account.normalizedName } public constructor(protected http: HttpClient, private accountService: AccountService) { super() } protected getUrl(path?: string) { let url = [`api/${this.accountService.account.normalizedName}/security/${this.parentId}/group`] if (path) url.push(path) return url.join('/') } } <file_sep>import { NumericValidatorDirective } from './numeric-validator.directive'; describe('IntegerValidatorDirective', () => { it('should create an instance', () => { const directive = new NumericValidatorDirective(); expect(directive).toBeTruthy(); }); }); <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AccountDataListEditComponent } from './account-data-list-edit.component'; describe('AccountDataListEditComponent', () => { let component: AccountDataListEditComponent; let fixture: ComponentFixture<AccountDataListEditComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AccountDataListEditComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AccountDataListEditComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Identificable, IIdentificable } from './identificable.model' import { Account } from 'src/app/account/account.model' export abstract class Accountable extends Identificable implements IAccountable { private _account: Account public get account(): Account { return this._account } public set account(value: Account) { this._account = value if (value) this.accountId = value.id } public accountId: number } export interface IAccountable extends IIdentificable { accountId: number account: Account } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { DisplayView } from 'src/app/master/components/display-view/nav-view.component'; import { AccountService } from 'src/app/account/account.service'; import { Table } from 'src/app/enums/table.enum'; import { USERICON } from 'src/app/master/components/icon/icon.const'; import { icon } from 'src/app/master/components/icon/icon.component'; import { UserService } from '../state/user.service'; @Component({ selector: 'app-user-item, [app-user-item]', templateUrl: './user-item.component.html', styleUrls: ['./user-item.component.sass'] }) export class UserItemComponent implements OnInit { constructor(private accountService: AccountService, private userService: UserService) { } @Input() item: TreeviewItem @Input() columns: any[] = [] @Input() display: DisplayView = DisplayView.inline get isEdit(): boolean { return Table.User.toString() + this.item.entity.id == this.userService.currentEdit } public folderContextmenu = [ { icon: "account-plus", action: (item) => item.entity.showAddFile = true, text: "Add User", visible: (item) => true } ] public contextmenu = [ /* { icon: "account-multiple-plus", action: (item) => item.entity.showAdd = true, text: "Create User", visible: (item) => true }, */ { icon: "account-edit", action: (item) => this.userService.getTreeview().subscribe(r => this.userService.currentEdit = Table.User.toString() + item.entity.id), text: "Edit User", visible: (item) => true }, /* { icon: "account-plus", action: (item) => item.entity.showAddFile = true, text: "Add User", visible: (item) => true }, */ ] public account: string = this.accountService.account.normalizedName; public Table = Table public folderLink: string = `/${this.account}/security/user/folder` public itemLink: string = `/${this.account}/security/user` public icon: icon = USERICON ngOnInit() { } public klose(){ this.userService.currentEdit = null } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-account-data-db-data-control', templateUrl: './account-data-db-data-control.component.html', styleUrls: ['./account-data-db-data-control.component.sass'] }) export class AccountDataDbDataControlComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>import { TestBed } from '@angular/core/testing'; import { AccountDataDbFormService } from './account-data-db-form.service'; describe('AccountDataDbFormService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: AccountDataDbFormService = TestBed.get(AccountDataDbFormService); expect(service).toBeTruthy(); }); }); <file_sep>import { Injectable } from '@angular/core'; import { FolderableService } from 'src/app/master/states/folderable.service'; import { Listitem } from './listitem.model'; import { List } from '../../list/state/list.model'; import { HttpClient } from '@angular/common/http'; import { AccountService } from 'src/app/account/account.service'; import { Observable, BehaviorSubject } from 'rxjs'; import { LoadingState } from 'src/app/master/states/loader.store'; import { TreeItem, TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { DisplayItemsStore } from 'src/app/master/states/display-page.store'; import { tap, map } from 'rxjs/operators'; import { Table } from 'src/app/enums/table.enum'; @Injectable({ providedIn: 'root' }) export class ListitemService extends FolderableService<Listitem> { protected type = Table.ListItem protected getFolderUrl = (path?: string) => { } public constructor(protected http: HttpClient, private accountService: AccountService) { super() } private _pListitems = new BehaviorSubject<Listitem[]>([]) public pListitems$ = this._pListitems.asObservable() protected getUrl(path?: string) { let url = [`api/${this.accountService.account.normalizedName}/data/${this.parentId}/listitem`] if (path) url.push(path) return url.join('/') } /* public getParentListitem(parentId: number): Observable<Listitem[]> { this.loader.startLoading(LoadingState.setPListitems) return this.http.get<Listitem[]>(`api/${this.accountService.account.normalizedName}/data/${parentId}/listitem`) .pipe( tap( r => this._pListitems.next(r), console.log, () => this.loader.stopLoading(LoadingState.setPListitems) ) ) } */ } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { Account } from '../admin-account/account' @Injectable({ providedIn: 'root' }) export class AdminAccountService { constructor(private http: HttpClient) { } accounts: Account[] = [] getAccount(id: number): Observable<Account> { return this.http.get<Account>(`api/admin/account/${id}`) } getAccounts(): Observable<Account[]> { return this.http.get<Account[]>(`api/admin/account`).pipe( tap(resp => this.accounts = resp) ) } createAccount(account: Account): Observable<Account> { return this.http.post<Account>(`api/admin/account`, account).pipe( tap(resp => this.accounts.push(resp)) ); } } <file_sep>namespace MiniS.Areas.Master.Enums { public class LoggingEvents { public const int GetItems = 1000; public const int ListItems = 1001; public const int GetItem = 1002; public const int InsertItem = 1003; public const int InsertItemError = 1007; public const int UpdateItem = 1004; public const int DeleteItem = 1005; public const int GetItemNotFound = 4000; public const int UpdateItemNotFound = 4001; public const int UpdateItemError = 4003; public const int GetItemsEmpty = 4100; public const int ManyToManyRelatedItemsEmpty = 4110; public const int ForbiddenItem = 4500; public const int GetItemError = 5000; public const int GetItemsError = 5001; } }<file_sep>import { Injectable } from '@angular/core'; import { AccountService } from 'src/app/account/account.service'; import { HttpClient } from '@angular/common/http'; import { FolderableService } from 'src/app/master/states/folderable.service'; import { List } from './list.model'; import { Folder } from '../../folder/folder.model'; import { Table } from 'src/app/enums/table.enum'; @Injectable({ providedIn: 'root' }) export class ListService extends FolderableService<List> { protected type= Table.List protected getFolderUrl(path?: string) { let url = [`api/${this.accountService.account.normalizedName}/data/list/${this.parentId}/folder`] if (path) url.push(path) return url.join('/') } public constructor(protected http: HttpClient, private accountService: AccountService) { super() } protected getUrl(path?: string) { let url = [`api/${this.accountService.account.normalizedName}/data/${this.parentId}/list`] if (path) url.push(path) return url.join('/') } } <file_sep> // using MiniS.Areas.Data.Models; // using MiniS.Areas.Identity.Data; // using MiniS.Areas.Identity.Models; // using MiniS.Areas.Master; // using MiniS.Areas.Master.Enums; // namespace MiniS.Areas.Data.Repositories { // public class DatabaseRepository : AccountGroupRepository<Database, long,Folder> { // public DatabaseRepository(AppDbContext dbContext) : base(dbContext) // { // } // protected override Table _table => Table.Database; // } // }<file_sep>using MiniS.Areas.Admin.Models; namespace MiniS.Areas.Master.Models { public abstract class Accountable : Identificable, IAccountable { public long AccountId { get; set; } public Account Account { get; set; } } public interface IAccountable : IIdentificable, IOAccountable { } public interface IOAccountable { long AccountId { get; set; } Account Account { get; set; } } public abstract class AccountableConfiguration<T> : IdentificableConfiguration<T> where T : Identificable { } }<file_sep>import { Component, Input, Output, EventEmitter } from "@angular/core"; import { AccountDataFieldBase } from "../account-data-field-base"; import { TreeviewItem } from "src/app/widgets/ngx-treeview"; import { AccountDataFolderableService } from "../../../account-data-folder/account-data-folder.service"; import { Field } from "../../models/field"; import { List } from "../../../models/list.model"; @Component({ selector: "app-account-data-db-list-field", templateUrl: "./account-data-db-list-field.component.html", styleUrls: ["./account-data-db-list-field.component.sass"], providers: [AccountDataFolderableService] }) export class AccountDataDbListFieldComponent extends AccountDataFieldBase { @Input() public listTreeView: Array<TreeviewItem>; public relatedFields: Array<Field>; public relatedLists: Array<List> = []; public ngOnInit() { super.ngOnInit(); this.relatedFields = this.database.fields.filter( f => f.list && f.list.listChildren.length > 0 ); this.relatedLists = this.field.relatedField ? this.field.relatedField.list.listChildren : []; } updateField(value: any) { value = Field.get(value) const observable = this.field.created ? this.dbService.updateField(this.database.id, value.id, value) : this.dbService.createField(this.database.id, value) observable.subscribe(r => { console.log("update subscribe") this.edit.emit(r) this.database.fieldProcessing = false this.relatedFields = this.database.fields.filter(f => f.list && f.list.listChildren) }) } public onDFieldSelected(selected: Field) { this.relatedLists = selected && selected.list ? selected.list.listChildren : []; } } <file_sep>import { Component, OnInit, HostBinding, Output, EventEmitter, Input } from '@angular/core'; export enum DisplayView { datatable = "datatable", inline = "inline", inlineBlock = "inlineBlock", iconText = "iconText" } export const VIEWS: Array<any> = [ { view: DisplayView.datatable, icon: "table" }, { view: DisplayView.iconText, icon: "format-list-text" }, { view: DisplayView.inline, icon: "format-columns" }, { view: DisplayView.inlineBlock, icon: "view-module" }, ] @Component({ selector: '[app-nav-view]', template: ` <a *ngFor="let v of VIEWS" class="btn" (click)="onClick(v.view)" [class.disabled]="isActive(v.view)"> <app-icon [icon]="v.icon"></app-icon> </a>` }) export class NavViewComponent implements OnInit { constructor() { } @HostBinding('class.btn-group') get valid() { return true } @Output() viewChange: EventEmitter<DisplayView> = new EventEmitter<DisplayView>() @Input() view: DisplayView ngOnInit(): void { console.log("view", this.view) } public VIEWS: Array<any> = VIEWS public isActive = (v: DisplayView) => this.view === v public onClick = (v: DisplayView) => this.viewChange.emit(v) } <file_sep>using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master; using MiniS.Areas.Master.Enums; using MiniS; using MiniS.Areas.Services; namespace MiniS.Areas.Identity.Services { public class GroupService:ParentableService<Group, Folder>{ public GroupService(AppDbContext dbContext, ILogger<GroupService> logger, IStringLocalizer<SharedResource> localizer,IParentableStore<Group, Folder> parentableStore, FolderService folderService) : base(dbContext, logger, localizer, parentableStore, folderService){ } protected override Table _table => Table.Group; } }<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FolderEditComponent } from './folder-edit.component'; import { InfoFormControlModule } from 'src/app/master/components/form-control/info-form-control/info-form-control.module'; import { EditModalModule } from 'src/app/master/components/edit-modal/edit-modal.module'; import { IconModule } from 'src/app/master/components/icon/icon.module'; import { FolderItemComponent } from './folder-item.component'; import { EntityItemModule } from 'src/app/master/components/entity-item/entity-item.module'; import { ContextMenuModule } from 'src/app/widgets/ngx-contextmenu/ngx-contextmenu'; @NgModule({ declarations: [FolderEditComponent, FolderItemComponent], imports: [ CommonModule, InfoFormControlModule, EditModalModule, IconModule, EntityItemModule, ContextMenuModule.forRoot() ], exports: [FolderEditComponent, FolderItemComponent] }) export class Folder2Module { } <file_sep>import { Injectable } from '@angular/core' import { AccountService } from 'src/app/account/account.service' import { HttpClient } from '@angular/common/http' import { Observable } from 'rxjs' import { LoaderStore, LoadingState } from './loader.store' import { EntityStore } from './entity.store' import { tap } from 'rxjs/operators' import { IIdentificable } from '../base-model/identificable.model' @Injectable({ providedIn: 'root' }) export abstract class EntityService<Entity extends IIdentificable> { protected parentId: number public loader = new LoaderStore() public entityStore = new EntityStore() public entities$ = this.entityStore.entities$ public constructor(protected http: HttpClient) { } protected abstract url: string protected getUrl(path?: string): string { const url = [this.url] if (path) url.push(path) return url.join('/') } public get(): Observable<Entity[]> { this.loader.startLoading(LoadingState.set) return this.http.get<Entity[]>(this.getUrl()) .pipe( tap( r => { this.entityStore.entities = r }, console.log, () => this.loader.stopLoading(LoadingState.set) ) ) } /* public getParents(): Observable<Entity[]> { this.loader.startLoading(LoadingState.setParents) return this.http.get<Entity[]>(this.getUrl('parents')) .pipe( tap( r => this.entityStore.parents = r, console.log, () => this.loader.stopLoading(LoadingState.setParents) ) ) } */ updateParentId(parentId: number) { this.parentId = parentId } add(model: Entity) { return this.http.post<Entity>(this.getUrl(), model).pipe(tap(entity => { this.entityStore.add(entity); })) } update(id, model: Partial<Entity>) { return this.http.put<Entity>(this.getUrl(id), model).pipe(tap(entity => { this.entityStore.update(entity); })) } remove(id: number) { return this.http.delete<Entity>(this.getUrl(id.toString())).pipe(tap(entity => { this.entityStore.remove(id); })) } }<file_sep>/* using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using MiniS.Areas.Admin.Models; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Repositories; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Enums; using MiniS.Helpers; namespace MiniS.Areas.Data.Controllers { [Route ("api/{account}/data/{formId}/data")] [Authorize] [Account] public class DatabaseDataController : ControllerBase { private readonly FormRepository _formRepo; private AppDbContext _dbContext { get; } public AuthorizationService _authService { get; } public DatabaseRepository _dbRepo { get; } private readonly DatabaseDataService _databaseDataService; public DatabaseDataController ( AppDbContext dbContext, AuthorizationService authService, DatabaseRepository dbRepo, DatabaseDataService databaseDataService, FormRepository formRepo ) { _dbContext = dbContext; _dbRepo = dbRepo; _databaseDataService = databaseDataService; _formRepo = formRepo; _authService = new AuthorizationService (HttpContext, Access.DatabaseData); } [HttpGet] public ActionResult<List<DatabaseData>> GetAllAsync (long databaseId) { // return forbidden response if the user has not read rights on database data if (!_authService.HasRight (Right.Read)) return Forbid (); // fetch all Database data the authenticated has access and return a 404 response if an error occurs if (_databaseDataService.FetchAllDatabaseData (databaseId, _authService.GetAuthUser ()) == LoggingEvents.GetItemsError) return BadRequest (); // return all Database data the authenticated has access return _databaseDataService.GetAllDatabaseData (); } [HttpGet ("{id}", Name = "GetDatabaseData")] public ActionResult<DatabaseData> GetAsync (long id) { if (!_authService.HasRight (Right.Read)) return Forbid (); switch (_databaseDataService.FetchDatabaseData (id, _authService.GetAccountId ()).Result) { case LoggingEvents.GetItemNotFound: return NotFound (); case LoggingEvents.GetItemsEmpty: return BadRequest (); case LoggingEvents.GetItemError: return BadRequest (); } if (!_authService.CanAccess (_databaseDataService.GetDatabaseData ())) return Forbid (); return _databaseDataService.GetDatabaseData (); } [HttpPost] public async Task<ActionResult<DatabaseData>> CreateAsync (long formId, DatabaseData model) { if (!_authService.HasRight (Right.Create)) return Forbid (); long accountId = _authService.GetAccountId (); // if(_authService.AuthorizeResource(HttpContext, list.PList).Fails()) return Forbid(_authService.GetMessage()); Form form = await _formRepo.GetForm (formId, accountId); if (form == null) return BadRequest (new { Message = "there is no form associated with the Database Data" }); if (!_authService.CanAccess (form)) return Forbid (); Database database = await _dbRepo.GetDatabase (form.DatabaseId, accountId); if (database == null) return BadRequest (new { Message = "there is no database associated with the Form" }); if (!_authService.CanAccess (database)) return Forbid (); DatabaseData databaseData = new DatabaseData (); databaseData.AllGroup = database.AllGroup ? model.AllGroup : false; if (!database.AllGroup) { databaseData.Groups = model.Groups.Intersect (database.Groups, new IDEqualityComparer<Group> ()).ToList (); if (database.Groups.Count < 1) return BadRequest (new { Message = "At least one group must be Included" }); } database = await _dbRepo.Create (database, model, parent, _authService.GetAuthUser ()); return CreatedAtRoute ("GetDatabase", new { parent = parent, id = database.Id, account = _authService.GetAccount ().NormalizedName }, database); } [HttpPut ("{id}")] public async Task<ActionResult<Database>> updateAsync (long parent, long id, Database model) { if (id != model.Id) return BadRequest (new { Message = "mismatch list ID" }); if (_authService.AuthorizePermission (HttpContext, new Tuple<Access, Right> (Access.Database, Right.Modify)).Fails ()) return Forbid (_authService.GetMessage ()); long accountId = _authService.GetAccountId (); Folder parentFolder = await _folderRepo.GetFolder (parent, accountId); if (parentFolder == null) return NotFound ("error fetching the parent Folder"); Database database = await _dbRepo.GetDatabase (id, accountId); if (!database.AllGroup && _authService.AuthorizeResource (HttpContext, database).Fails ()) return Forbid (_authService.GetMessage ()); if (!parentFolder.AllGroup) { database.Groups = model.Groups.Intersect (parentFolder.Groups, new IDEqualityComparer<Group> ()).ToList (); database.AllGroup = false; } else database.AllGroup = model.AllGroup; if (!database.AllGroup && database.Groups.Count < 1) return BadRequest (new { Message = "you must specify a group" }); return await _dbRepo.Update (database, model, _authService.GetAccountId ()); } } } */<file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { Login } from './account-security-auth-login/login.model'; import { User } from '../user/state/user.model'; @Injectable({ providedIn: 'root' }) export class AccountSecurityAuthService { constructor(private http: HttpClient) {} public login(account: string, model: Login): Observable<User> { return this.http.post<User>(`api/${account}/security/user/login`, model) } public logout(account: string): Observable<null> { return this.http.post<null>(`api/${account}/security/auth/logout`, null) } public getAuthUser(account: string): Observable<User> { return this.http.get<User>(`api/${account}/security/auth/user`) } } <file_sep>import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, CanActivateChild, Router } from '@angular/router'; import { Observable, of } from 'rxjs'; import { AccountService } from '../account.service'; import { map, catchError } from 'rxjs/operators'; import { AuthService } from '../security/auth/state/auth.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivateChild { constructor( private accountService: AccountService, private router: Router, private authService: AuthService ) { } canActivateChild( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { let loginUrlEnd = '/security/auth/login' // if it is the login page we grant access if (state.url.indexOf(loginUrlEnd) > -1) return of(true) // save the current url to redirect after the login else this.accountService.url = state.url let account = this.accountService.account.normalizedName, accountId = this.accountService.account.id, authUser = this.accountService.authUser // if there is a saved authenticated user and it belong to the current account we grant access if (authUser && authUser.accountId === accountId) return of(true) // else we try to get the user return this.authService.getAuthUser(account).pipe( map(r => { // if an authenticad user found and belonf to the currenyt account we save it and we grant access if (r && r.accountId == accountId) { this.accountService.authUser = r return true } else { // otherwise we logout the user (in case of authenticated doesn't belong to the current account) this.authService.logout(account).subscribe(r => this.accountService.authUser = null) this.router.navigateByUrl(`/${account}${loginUrlEnd}`, { queryParams: { returnUrl: state.url } }) return false } }), catchError(e => { this.authService.logout(account).subscribe(r => this.accountService.authUser = null) this.router.navigate([`/${account}${loginUrlEnd}`], { queryParams: { returnUrl: state.url } }) return of(false)} ) ) } } <file_sep>export enum Table { None, Account, User, Group, AccessTemplate, Folder, Database, List, ListItem, Form, Field, DatabaseData } <file_sep>// using System.Linq; // using MiniS.Areas.Data.Models; // using MiniS.Areas.Master.Enums; // using MiniS.Areas.Master; // using MiniS.Areas.Identity.Models; // using System; // using MiniS.Areas.Identity.Data; // namespace MiniS.Areas.Data.Repositories // { // public class FolderRepository : AccountGroupRepository<Folder,Nullable<long>,Folder> // { // public FolderRepository(AppDbContext dbContext) : base(dbContext) // { // } // private Table _type; // protected override Table _table => Table.Folder; // public FolderRepository SetType(Table type){ // _type = type; // return this; // } // public override IQueryable<Folder> GetModels(long? parentId, params object[] param){ // return base.GetModels(parentId).Where(Model=>Model.Type == _type); // } // } // }<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core"; import { FieldAttribute, FieldType, Field } from "../../../models/field"; import { ListItem } from "src/app/account/data/models/list-item"; import { AccountDataListService } from "src/app/account/data/account-data-list/account-data-list.service"; import { AccountDataDbFormService } from "../../account-data-db-form.service"; import { Form } from "../../../models/form"; import { getObjectCopy } from "src/app/helpers/object.helper"; @Component({ selector: "[app-account-data-db-form-field-attribute-list]", templateUrl: "./account-data-db-form-field-attribute-list.component.html", styleUrls: ["./account-data-db-form-field-attribute-list.component.sass"] }) export class AccountDataDbFormFieldAttributeListComponent implements OnInit { constructor(private listService: AccountDataListService) {} @Input() public model: FieldAttribute; @Input() public field: Array<Field> = []; @Input() public form: Form; @Input() public listDefaults: any; @Output() public edit: EventEmitter<FieldAttribute> = new EventEmitter< FieldAttribute >(); @Output() public remove: EventEmitter<any> = new EventEmitter<any>(); public listItems: Array<ListItem> = []; public modelCopy: FieldAttribute; public type: "multiSelect" | "select"; ngOnInit() { this.modelCopy = getObjectCopy(this.model); //this.type = this.modelCopy.field.multi ? "multiSelect" : "select"; if (this.model.field.type == FieldType.List) { this.listService .getListItems(this.model.field.list.id) .subscribe(r => (this.listItems = r)); } else { this.listService .getListItems( this.model.field.list.id, this.listDefaults[this.model.field.relatedFieldId] ) .subscribe(r => (this.listItems = r)); } } } <file_sep>import { AccessTemplate } from './access-template'; describe('AccessTemplate', () => { it('should create an instance', () => { expect(new AccessTemplate()).toBeTruthy(); }); }); <file_sep>import { Injectable } from '@angular/core'; import { Stepper } from './stepper.model'; import { EntityState, EntityStore, StoreConfig } from '@datorama/akita'; export interface StepperState extends EntityState<Stepper> {} @Injectable({ providedIn: 'root' }) @StoreConfig({ name: 'stepper' }) export class StepperStore extends EntityStore<StepperState> { constructor() { super(); } } <file_sep>using System; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; using MiniS.Areas.Admin.Models; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using System.Linq; namespace MiniS.Areas.Identity.Authorization { public class AccountAttribute : TypeFilterAttribute { public AccountAttribute() : base(typeof(AccountFilter)) { } private class AccountFilter : IAsyncAuthorizationFilter { public int Order => 3; public AccountFilter( AppDbContext dbContext, UserManager<AccountUser> userManager, ILogger<AccountFilter> logger) { _dbContext = dbContext; _userManager = userManager; _logger = logger; } private const string accountString = "account"; private readonly AppDbContext _dbContext; private readonly UserManager<AccountUser> _userManager; private readonly ILogger<AccountFilter> _logger; public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { if (context.RouteData.Values.ContainsKey(accountString)) { Account account = await _dbContext.Accounts.FirstOrDefaultAsync(e => e.NormalizedName.Equals((string)context.RouteData.Values[accountString])); if (account == null) context.Result = new NotFoundObjectResult(new { Message = "No account found" }); else { context.HttpContext.Items[accountString] = account; if (context.HttpContext.User.Identity.IsAuthenticated) { AccountUser user = await _userManager.GetUserAsync(context.HttpContext.User); if (user == null) context.Result = new NotFoundObjectResult(new { Message = "No user found" }); else { _dbContext.Entry(user).Reference(b => b.Account).Load(); // context.Result = new NotFoundObjectResult(user); if (user.AccountId != account.Id) context.Result = new ForbidResult(); user.Groups = await _dbContext.GetGroups(user.Id, MiniS.Areas.Master.Enums.Table.User); // User found so we store it in the Http Context context.HttpContext.Items["authUser"] = user; } } } } } } } }<file_sep>namespace MiniS.Areas.Master.Enums { public enum Module { Security = 10, Data = 100, Library = 1000 } }<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { InputType } from 'src/app/enums/input-type.enum'; import { trigger, state, transition, animate, style } from '@angular/animations'; import { Expression } from '../datatable.interface'; @Component({ selector: 'app-datatable-filter', templateUrl: './datatable-filter.component.html', styleUrls: ['./datatable-filter.component.sass'], animations: [ trigger('widthAnimation', [ // ... state('normal', style({ width: '*' })), state('widen', style({ width: '25em' })), transition('normal <=> widen', [ animate('1s') ]) ]), ], }) export class DatatableFilterComponent implements OnInit { constructor() { } ngOnInit() { console.log('colomn', this.column) } rand = Math.random() @Input('expression') model: Expression @Input() column: any // @Output() change: EventEmitter<any> = new EventEmitter<any>() get items(): Array<any> { return this.column.items || [] } @Input() key: string InputType = InputType groupByFn = (item) => item.pListItem ? item.pListItem.name : null groupValueFn = (_: string, children: any[]) => children[0].pListItem ? ({ name: children[0].pListItem.name, total: children.length }) : null } <file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Models; namespace MiniS.Areas.Master.Models { public abstract class Groupable<P> : Parentable<P>, IGroupable<P>,IResource { public bool AllGroup { get; set; } [NotMapped] public List<Group> Groups { get; set; } } public interface IGroupable<P>: IParentable<P>, IOGroupable { } public interface IOGroupable { bool AllGroup { get; set; } List<Group> Groups { get; set; } } public abstract class GroupableConfiguration<T, P> : ParentableConfiguration<T,P> where T : Groupable<P> where P : Accountable { } }<file_sep>// using System; // using System.Collections.Generic; // using System.Linq; // using System.Threading.Tasks; // using Microsoft.EntityFrameworkCore; // using Microsoft.EntityFrameworkCore.Storage; // using MiniS.Areas.Identity.Data; // using MiniS.Areas.Identity.Models; // using MiniS.Areas.Master.Enums; // using MiniS.Areas.Master.Models; // using MiniS.Areas.Models; // using MiniS.Helpers; // namespace MiniS.Areas.Master // { // public interface IAccountGroupRepository<Model, ParentId> : IAccountRepository<Model, ParentId> // { // List<Group> GetGroups(Model model); // Task<List<Group>> IntersectGroup(List<Group> groups); // } // public abstract class AccountGroupRepository<Model, ParentId, Parent> // : AccountRepository<Model, ParentId, Parent>, IAccountGroupRepository<Model, ParentId> // where Model : AccountGroupTrackable<ParentId, Parent> // { // private IDbContextTransaction GetTransaction() => _dbContext.Database.BeginTransaction(); // public AccountGroupRepository(AppDbContext dbContext) : base(dbContext) // { // } // public override async Task<Model> SaveUpdateAsync(Model model) // { // using (var transaction = GetTransaction()) // { // try // { // model = await base.SaveUpdateAsync(model); // _UpdateEntityGroup(model, _table, /*Get the current EntityGroup*/ await _dbContext.GetEntityGroups(model.Id, _table)); // await _dbContext.SaveChangesAsync(_authUser); // transaction.Commit(); // } // catch (Exception) // { // return null; // } // } // return model; // } // public override async Task<Model> SaveCreateAsync(Model model) // { // using (var transaction = GetTransaction()) // { // await base.SaveCreateAsync(model); // _UpdateEntityGroup(model, _table, new List<EntityGroup>()); // await _dbContext.SaveChangesAsync(_authUser); // transaction.Commit(); // /* try // { // await base.SaveCreateAsync(model); // _UpdateEntityGroup(model, _table, new List<EntityGroup>()); // await _dbContext.SaveChangesAsync(_authUser); // transaction.Commit(); // } // catch (Exception e) // { // throw e; // return null; // } */ // } // return model; // } // private void _UpdateEntityGroup(Model model, Table table, List<EntityGroup> currentEntityGroup) // { // if (!model.AllGroup) // { // _dbContext.UpdateManyToMany(model.Groups.Select( // g => new EntityGroup() // { // EntityId = model.Id, // Table = table, // GroupId = g.Id, // AccountId = _authUser.AccountId // } // ).ToList(), currentEntityGroup); // } // else // { // _dbContext.UpdateManyToMany(new List<EntityGroup>(), currentEntityGroup); // } // } // public List<Group> GetGroups(Model model) // { // return _dbContext.GetGroups(model.Id, _table).Result; // } // public async Task<List<Group>> IntersectGroup(List<Group> groups) // { // var query = await _dbContext.Groups.Where<Group>(g => g.AccountId == _authUser.AccountId).ToListAsync(); // return query.Intersect<Group>(groups, new IDEqualityComparer<Group>()).ToList(); // } // } // }<file_sep>import { Form } from '../form/form.model'; export function createStepper(params: Partial<Stepper>) { return { } as Stepper; } export class Stepper { public constructor( public name?: string, public order?: number ) { } public id: number = 0 public form: Form public formId:number public updated: boolean = false public created: boolean = false } <file_sep>using System; namespace MiniS.Helpers { public class StringUtilities { public static bool Equals(string s1, string s2) { if (s1 == null) return false; s2 = s2 ?? String.Empty; return s1.Trim().Equals(s2.Trim(), StringComparison.OrdinalIgnoreCase); } } }<file_sep>import { TableToIconPipe } from './table-to-icon.pipe'; describe('TableToIconPipe', () => { it('create an instance', () => { const pipe = new TableToIconPipe(); expect(pipe).toBeTruthy(); }); }); <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Models; abstract class AuthValidator : IValidatableObject { private Right _right; protected Access _access; public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { /* HttpContext httpContext = (validationContext.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor).HttpContext; string httpMethod = httpContext.Request.Method; if(HttpMethods.IsPut(httpMethod)) _right = Right.Modify; else if(HttpMethods.IsPost(httpMethod)) _right = Right.Create; else if(HttpMethods.IsGet(httpMethod)) _right =Right.Read; AuthorizationService _authService = new AuthorizationService(httpContext, _access); if (_authService.HasRight(_right)) yield return new ValidationResult("hell",new[] { "MinLength" }); */ yield return new ValidationResult( $"the minimum length must less tha the maximum length", new[] { "MinLength" }); } }<file_sep>import { Component, OnInit } from '@angular/core'; import { Form } from '../../models/form'; import { ActivatedRoute, Router } from '@angular/router'; import { AccountDataDbService } from '../../account-data-db.service'; @Component({ selector: 'app-account-data-db-form-display', templateUrl: './account-data-db-form-display.component.html', styleUrls: ['./account-data-db-form-display.component.sass'] }) export class AccountDataDbFormDisplayComponent implements OnInit { constructor(private route: ActivatedRoute, private router: Router, private dbService: AccountDataDbService) { } public account: string public children: Array<Form> ngOnInit() { this.account = this.dbService.account this.route.params.subscribe(routeParams => this.dbService.getForms(routeParams.id).subscribe( r => this.children = r ) ) } public goTo(id: number, to: "form" | "folder" | "data" = "folder") { this.router.navigateByUrl(`/${this.account}/data/database/${to}/${id}`); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Table } from 'src/app/enums/table.enum'; import { GroupService } from '../state/group.service'; import { Columns } from 'src/app/master/base-model/parentable.model'; import { DisplayView } from 'src/app/master/components/display-view/nav-view.component'; @Component({ selector: 'app-group-display-page', templateUrl: './group-display-page.component.html', styleUrls: ['./group-display-page.component.sass'] }) export class GroupDisplayPageComponent implements OnInit { constructor( private route: ActivatedRoute, private groupService: GroupService, ) { } public account: string public type = Table.Group public columns = Columns public display: DisplayView = DisplayView.inline public DisplayView = DisplayView public ngOnInit() { this.account = this.groupService.account this.route.params.subscribe(routeParams => { this.groupService.updateParentId(routeParams.id); this.groupService.getCurrentItems(routeParams.id).subscribe() // this.groupService.getParents().subscribe(); }); } public Table = Table get items() { return this.groupService.currentItems$ } get parent() { return this.groupService.parentEntity$ } get parents() { return this.groupService.parents$ } get root() { return this.groupService.rootEntity$ } get loading() { return this.groupService.store.loading$ } /* get parentsLoading() { return this.groupService.loader.setParents$ } get displayItemsLoading() { return this.groupService.loader.set$ } */ } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using MiniS.Areas.Data.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Master; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; using MiniS; using MiniS.Areas.Services; namespace MiniS.Areas.Data.Services { public class FolderService : AccountGroupService<Folder, Folder> { protected override Table _table => Table.Folder; protected Table _type; public FolderService(AppDbContext dbContext,ILogger<FolderService> logger, IStringLocalizer<SharedResource> localizer, IParentableStore<Folder, Folder> parentableStore) : base(dbContext,logger, localizer, parentableStore, null) { } public FolderService SetType(Table type) { _type = type; return this; } protected override Folder PopulateCreateModel(Folder model) { base.PopulateCreateModel(model); MODEL.Type = _type; return MODEL; } public async Task<List<Folder>> GetParents(Folder folder = null) { int counter = 0; List<Folder> folders = new List<Folder>(); while (folder != null && counter < 10) { folders.Add(folder); folder = await FetchModel(folder.Id); counter++; } return folders; } public override IQueryable<Folder> GetModels(long parentId, params object[] param) { return base.GetModels(parentId).Where(Model => Model.Type == _type); } } }<file_sep>import { Injectable } from '@angular/core'; import { Query } from '@datorama/akita'; import { AuthenticationStore, AuthenticationState } from './authentication.store'; @Injectable({ providedIn: 'root' }) export class AuthenticationQuery extends Query<AuthenticationState> { constructor(protected store: AuthenticationStore) { super(store); } } <file_sep>import { Injectable } from '@angular/core'; import { FolderableService } from 'src/app/master/states/folderable.service'; import { User } from './user.model'; import { Folder } from 'src/app/account/data/folder/folder.model'; import { HttpClient } from '@angular/common/http'; import { AccountService } from 'src/app/account/account.service'; import { Table } from 'src/app/enums/table.enum'; @Injectable() export class UserService extends FolderableService<User> { protected type = Table.User protected getFolderUrl(path?: string) { let url = [`api/${this.account}/data/user/${this.parentId}/folder`] if (path) url.push(path) return url.join('/') } get account(){ return this.accountService.account.normalizedName } public constructor(protected http: HttpClient, private accountService: AccountService) { super() } protected getUrl(path?: string) { let url = [`api/${this.accountService.account.normalizedName}/security/${this.parentId}/user`] if (path) url.push(path) return url.join('/') } } <file_sep>using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MiniS.Areas.Admin.Models; using MiniS.Areas.Data.Models; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; using MiniS.Areas.Models; using Newtonsoft.Json; using Folder = MiniS.Areas.Data.Models.Folder; namespace MiniS.Areas.Identity.Data { public class AppDbContext : IdentityDbContext<AccountUser, Role, long> { //private readonly UserManager<AccountUser> _UserManager; public AppDbContext(DbContextOptions<AppDbContext> options //,UserManager<AccountUser> _userManager ) : base(options) { //_UserManager = _userManager; } protected override void OnModelCreating(ModelBuilder builder) { // Calling the base Method base.OnModelCreating(builder); // Access Right Dictionary to Json Value Converter class ValueConverter<Dictionary<Access, Right>, string> accessConverter = new ValueConverter<Dictionary<Access, Right>, string>( v => JsonConvert.SerializeObject(v), v => JsonConvert.DeserializeObject<Dictionary<Access, Right>>(v) ); // Seeding Data builder.Entity<Account>().HasData(new Account() { Id = 1, Name = "victo", NormalizedName = "Victo", Description = "first account", CreatedBy = "9ecf7ds07-ca4f-459a-b202-189f076c8d02", LastUpdatedBy = "9ecf7d07-ca4f-459a-b202-189f076c8d02" }); builder.Entity<Account>().HasData(new Account() { Id = -1, Name = "acoount0", NormalizedName = "a0", Description = "0 account", CreatedBy = "mahdic", LastUpdatedBy = "mahdic" }); builder.Entity<Folder>().HasData(new Folder() { Id = -1, Name = "for relation", AccountId = -1, ParentId = -1, CreatedBy = "mahdic", LastUpdatedBy = "mahdic" }); builder.Entity<Folder>().HasData(new Folder() { Id = 1, Name = "userContainer", AccountId = 1, ParentId = -1, CreatedBy = "mahdic", LastUpdatedBy = "mahdic", Type = Table.User }); AccountUser user = new AccountUser() { Id = 1, LastName = "Choyekh", FirstName = "Mahdi", UserName = "mahdic", Email = "<EMAIL>", AccountId = 1, NormalizedEmail = "<EMAIL>", NormalizedUserName = "MAHDIC", SecurityStamp = "5UURQWYBHEBO7TBRGR6I6Q2GOURQRBHD", CreatedBy = "mahdic", LastUpdatedBy = "mahdic", ParentId = -1 }; //builder.Entity<Folder> ().HasData (new Folder () { Name = "root", AccountId = 1, ParentId = -1 }); var newPassword = new PasswordHasher<AccountUser>().HashPassword(user, "<PASSWORD>"); user.PasswordHash = newPassword; builder.Entity<AccountUser>().HasData(user); // Apply EntityTypeConfiguration builder.ApplyConfigurationsFromAssembly(typeof(Folder).Assembly) .ApplyConfigurationsFromAssembly(typeof(AccountUser).Assembly); /* builder.ApplyConfiguration (new AccountConfiguration ()) .ApplyConfiguration (new AccountUserConfiguration ()) .ApplyConfiguration (new AccessTemplateConfiguration ()) .ApplyConfiguration (new GroupConfiguration ()) .ApplyConfiguration (new FolderConfiguration ()) .ApplyConfiguration (new EntityGroupConfiguration ()) .ApplyConfiguration (new DatabaseConfiguration ()) .ApplyConfiguration (new ListConfiguration ()) .ApplyConfiguration (new ListItemConfiguration ()) .ApplyConfiguration (new FieldConfiguration ()) .ApplyConfiguration (new FieldAttributeConfiguration ()) .ApplyConfiguration (new FormConfiguration ()) .ApplyConfiguration (new StepperConfiguration ()) .ApplyConfiguration (new DataConfiguration ()) .ApplyConfiguration (new DataContactConfiguration ()) .ApplyConfiguration (new DataAddressConfiguration ()); */ // Accesses property conversion dictionary to Json builder.Entity<AccessTemplate>().Property(e => e.Accesses).HasConversion(accessConverter); builder.Entity<AccountUser>().Property(e => e.Accesses).HasConversion(accessConverter); // Manyto Many relationship between AccountUser and Group } public int SaveChanges(AccountUser user) { OnBeforeSaving(user); return base.SaveChanges(); } public Task<int> SaveChangesAsync(AccountUser user, Account account = null) { OnBeforeSaving(user); return base.SaveChangesAsync(); } private void OnBeforeSaving(AccountUser user) { var entries = ChangeTracker.Entries(); foreach (var entry in entries) { if (entry.Entity is ITrackable trackable) { switch (entry.State) { case EntityState.Modified: trackable.LastUpdatedBy = user.UserName; break; case EntityState.Added: trackable.CreatedBy = user.UserName; trackable.LastUpdatedBy = user.UserName; break; } } if (entry.Entity is IAccountable accountable) { accountable.AccountId = user.AccountId; } } } //DB Set public DbSet<Account> Accounts { get; set; } public DbSet<AccountUser> AccountUsers { get; set; } public DbSet<AccessTemplate> AccessTemplates { get; set; } public DbSet<Group> Groups { get; set; } public DbSet<Folder> Folders { get; set; } public DbSet<EntityGroup> EntityGroups { get; set; } public DbSet<Database> Databases { get; set; } public DbSet<Form> Forms { get; set; } public DbSet<List> Lists { get; set; } public DbSet<ListItem> ListItems { get; set; } public DbSet<Field> Fields { get; set; } public DbSet<FieldAttribute> FieldAttributes { get; set; } public DbSet<Stepper> Steppers { get; set; } public DbSet<DatabaseData> DatabaseData { get; set; } /* public DbSet<DataContact> DataContacts { get; set; } */ public DbSet<DataAddress> DataAddresses { get; set; } } }<file_sep>import { Injectable } from '@angular/core'; import { QueryEntity } from '@datorama/akita'; import { FormStore, FormState } from './form.store'; @Injectable({ providedIn: 'root' }) export class FormQuery extends QueryEntity<FormState> { constructor(protected store: FormStore) { super(store); } } <file_sep>import { icon } from './icon.component' export const LISTICON = { name: 'list', class: 'blue-text' } export const GROUPICON : icon = { name: 'users', class: 'green-text' } export const USERICON : icon = { name: 'user', class: 'red-text' } export const PENICON : icon = { name: 'pen', class: 'blue-text' } export const VOLUMEICON: icon = { name: 'hdd', class: 'blue-text text-darken-2' } export const SERVERICON: icon = { name: 'server', class: 'grey-text text-darken-3' }<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core"; import { FieldAttribute, FieldType } from "../../models/field"; @Component({ selector: "app-account-data-db-data-edit", templateUrl: "./account-data-db-data-edit.component.html", styleUrls: ["./account-data-db-data-edit.component.sass"] }) export class AccountDataDbDataEditComponent implements OnInit { constructor() {} public Column = FieldType; public isNaN = isNaN; public model: any = {}; public detect: number = 0; public isDList(fieldAttribute: FieldAttribute, model: any) { /* return ( fieldAttribute.field.column == FieldType.DependentList && !isNaN(model[fieldAttribute.field.relatedField.columnName]) ); */ } @Input() fieldAttributes: Array<FieldAttribute>; @Input() items: any; @Output() close: EventEmitter<any> = new EventEmitter<any>(); ngOnInit() { //init the defaut value of the model /* this.fieldAttributes.forEach( fa => (this.model[fa.field.columnName] = fa.options[fa.field.inputType].default) ); */ } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-account-data-db-form', templateUrl: './account-data-db-form.component.html', styleUrls: ['./account-data-db-form.component.sass'] }) export class AccountDataDbFormComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core"; import { Stepper } from "../../../models/stepper"; import { Form } from "../../../models/form"; import { FieldAttribute, FieldType } from "../../../models/field"; @Component({ selector: "app-account-data-db-form-stepper-content", templateUrl: "./account-data-db-form-stepper-content.component.html", styleUrls: ["./account-data-db-form-stepper-content.component.sass"] }) export class AccountDataDbFormStepperContentComponent implements OnInit { constructor() {} private _fieldAttributes: Array<FieldAttribute> = []; @Input() stepper: Stepper; @Input() form: Form; @Input() fieldAttributes: Array<FieldAttribute>; @Output() remove: EventEmitter<number> = new EventEmitter<number>(); get listDefaults(): any { let obj = {}; this.fieldAttributes.forEach(element => { obj[element.field.id] = element.options[element.field.inputType].default; }); return obj; } public isNumeric(field: FieldAttribute) { return ( field.field.type == FieldType.Integer || field.field.type == FieldType.Decimal ); } public isList(field: FieldAttribute) { return ( field.field.type == FieldType.List || field.field.type == FieldType.DependentList ); } public isText(field: FieldAttribute) { return field.field.type == FieldType.Text; } ngOnInit() {} public removeFieldAttribute(index: number) { this.remove.emit(index); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using MiniS.Areas.Admin.Models; using MiniS.Areas.Data.Controllers; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Identity.Services; using MiniS.Areas.Master.Controllers; namespace MiniS.Areas.Identity.Controllers { [Route("api/{account}/security/{parentId:long}/group")] [Authorize] [Account] public class GroupController : GroupableController<Group, Folder, GroupService> { public GroupController(GroupService service, AuthorizationService authService) : base(service, authService) { } protected override Access _access => Access.Group; } } <file_sep>import { ColDisplay } from 'src/app/widgets/datatable/datatable.interface' import { InputType } from 'src/app/enums/input-type.enum' export abstract class Trackable { constructor() { } public createdAt: Date public createdBy: string public lastUpdatedAt: Date public lastUpdatedBy: string public showEdit: boolean = false } export interface ITrackable { createdAt?: Date createdBy?: string lastUpdatedAt?: Date lastUpdatedBy?: string } let Columns: ColDisplay[] = [ { key: "createdAt", display: "Created At", sort: 0, show: true, items: [], inputType: InputType.Date }, { key: "createdBy", display: "Created By", sort: 0, show: true, items: [], inputType: InputType.Text }, { key: "lastUpdatedAt", display: "Last Updated At", sort: 0, show: true, items: [], inputType: InputType.Date }, { key: "lastUpdatedBy", display: "Last Updated by", sort: 0, show: true, items: [], inputType: InputType.Text }, ] export {Columns}<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DatabaseEditComponent } from './components/database/database-edit.component'; import { FormsModule } from '@angular/forms'; import { NgSelectModule } from 'src/app/widgets/ng-select/ng-select.module'; import { EditModalModule } from 'src/app/master/components/edit-modal/edit-modal.module'; import { InfoFormControlModule } from 'src/app/master/components/form-control/info-form-control/info-form-control.module'; import { DatabaseComponent } from './components/database/database.component'; import { TreeviewFolderableModule } from 'src/app/master/components/treeview-template/treeview-folderable.module'; import { ContextMenuModule } from 'src/app/widgets/ngx-contextmenu/ngx-contextmenu'; import { DatabaseDisplayPageComponent } from './components/database/database-display-page.component'; import { DatabaseItemComponent } from './components/database/database-item.component'; import { IconModule } from 'src/app/master/components/icon/icon.module'; import { RouterModule } from '@angular/router'; import { FolderModule } from '../folder/folder.module'; import { DatatableModule } from 'src/app/widgets/datatable/datatable.module'; import { FieldModule } from '../field/field.module'; import { GroupModule } from '../../security/group/group.module'; @NgModule({ declarations: [DatabaseEditComponent, DatabaseComponent, DatabaseDisplayPageComponent, DatabaseItemComponent], imports: [ CommonModule, FormsModule, NgSelectModule, EditModalModule, InfoFormControlModule, TreeviewFolderableModule, FolderModule, IconModule, RouterModule, ContextMenuModule.forRoot(), DatatableModule, FieldModule ], exports: [DatabaseEditComponent] }) export class DatabaseModule { } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using MiniS.Areas.Data.Models; using MiniS.Areas.Data.Services; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; using MiniS.Areas.Master; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; using MiniS.Areas.Master.Extensions; using Microsoft.AspNetCore.Routing; using MiniS; using MiniS.Helpers; using System.Linq.Expressions; using MiniS.Master.Extensions; using System.Diagnostics.CodeAnalysis; namespace MiniS.Areas.Services { public interface IParentableService<Model, Parent> : IParentableService<Model> { Task TryCreateModel(Model model); Task TryUpdateModel(Model Model); IParentableStore<Model, Parent> _parentableStore { get; set; } Task<Model> Delete(Model model); Parent PARENT { get; set; } IParentableService<Parent> ParentService { get; set; } Component GetTreeviewFolder(Folder folder, bool deep); Component GetTreeview(Parent parent, bool deep = true); List<Leaf> GetParents(long id); Task<bool> ValidateNameExists(Model model); Task<bool> ExistsByName(long parentId, string name1, string name2); Task<bool> ExistsBy(Expression<Func<Model, bool>> predicate); } public interface IParentableService<Model> : IParentableService { IQueryable<Model> GetModel(long id); Task<Model> FetchModel(long id); Model MODEL { get; set; } List<Model> MODELS { get; set; } Task<List<Model>> FetchModels(long parentId, params object[] param); void SetAuthService(AuthorizationService authService); bool HasRight(Right right); bool CanAccessAccountResource(IOAccountable resource); bool CanAccessGroupResouce(IOGroupable resource); void LogError(int eventId, Exception exception, string errorString, params object[] args); void LogInformation(int eventId, string infoString, params object[] args); void LogWarning(int eventId, string message, params object[] args); void AddErrorState(string input, string message, params object[] args); bool NotFound { get; set; } } public interface IParentableService { List<Component> GetTreeviews(); ModelStateDictionary ModelState { get; } bool Fails(); } public abstract class ParentableService<Model, Parent> : IParentableService<Model, Parent> where Model : IParentable<Parent> where Parent : Accountable { public ModelStateDictionary ModelState { get; set; } = new ModelStateDictionary(); protected readonly ILogger _logger; protected readonly IStringLocalizer<SharedResource> _localizer; public Model MODEL { get; set; } = (Model)Activator.CreateInstance(typeof(Model)); public Parent PARENT { get; set; } public List<Model> MODELS { get; set; } protected readonly AppDbContext _dbContext; public IParentableStore<Model, Parent> _parentableStore { get; set; } public IParentableService<Parent> ParentService { get; set; } protected AuthorizationService _authService; public ParentableService( AppDbContext dbContext, ILogger logger, IStringLocalizer<SharedResource> localizer, IParentableStore<Model, Parent> parentableStore, IParentableService<Parent> parentService = null ) { _localizer = localizer; _logger = logger; _dbContext = dbContext; ParentService = parentService ?? this as IParentableService<Parent>; _parentableStore = parentableStore; } protected abstract Table _table { get; } protected AccountUser _authUser; public void SetAuthService(AuthorizationService authService) { _authService = authService; _authUser = authService.GetAuthUser(); } protected string _nameofModel = typeof(Model).Name; public bool NotFound { get; set; } public virtual async Task<Model> FetchModel(long id) { try { MODEL = await GetModel(id).FirstOrDefaultAsync(); if (MODEL == null) { NotFound = true; LogError(LoggingEvents.GetItemError, null, _nameofModel + "-NotFound#{id}", id); AddErrorState("notFound", _nameofModel + "-notFound"); } else LogInformation(LoggingEvents.GetItem, _nameofModel + "-Get-success"); return MODEL; } catch (Exception exception) { LogError(LoggingEvents.GetItemError, exception, _nameofModel + "-Get-Error"); AddErrorState("notFound", _nameofModel + "-notFound"); return default(Model); } } public virtual async Task<List<Model>> FetchModels(long parentId, params object[] param) { try { MODELS = await GetModels(parentId, param).ToListAsync(); LogInformation(LoggingEvents.GetItems, _nameofModel + "-GetAll-Sucess"); return MODELS; } catch (Exception ex) { LogError(LoggingEvents.GetItemError, ex, String.Format("{0}-GetAll-Error", _nameofModel)); AddErrorState("error", _nameofModel + "-GetAll-Error"); return new List<Model>(); } } public virtual async Task TryCreateModel(Model model) { if (await ValidationFails(model)) return; //Populate the model PopulateCreateModel(model); PopulateModelWithGroup(model); if (Fails()) return; try { await _dbContext.AddAsync(MODEL); await _dbContext.SaveChangesAsync(_authUser); } catch (Exception ex) { LogError(LoggingEvents.GetItemError, ex, String.Format("{0}-Create-Error", _nameofModel)); AddErrorState("create-error", "create-error {0}", model.Name); } } public virtual async Task<bool> ValidationFails(Model model) { // Check Parent Model exist and has access right PARENT = await ParentService.FetchModel(model.ParentId); if (ParentService.Fails()) { LogError(LoggingEvents.GetItemError, null, String.Format("{0}-ParentModel,not exit or dont have access to it", _nameofModel)); AddErrorState("error", nameof(PARENT) + "Get-Access-Parent-error"); return true; } // Validate if the mode we trying to edit exit and we have access to it we assigne also the MODEL here if (model.Id > 0) { FetchModel(model.Id).Wait(); if (Fails()) { LogError(LoggingEvents.GetItemError, null, String.Format("{0}-model-to-update-not-exist-or-not-accescced", _nameofModel)); AddErrorState("error", nameof(MODEL) + "-model-to-update-not-exist-or-not-accescced"); return true; }; } // Checkif the name already exists if (await ValidateNameExists(model)) { LogError(LoggingEvents.GetItemError, null, String.Format("{0}-model-name-already-exist", _nameofModel)); AddErrorState("error", nameof(MODEL) + "{0}-model-name-already-exist", model.Name); return true; } return false; } public virtual async Task TryUpdateModel(Model model) { if (await ValidationFails(model)) return; //FetchAndSetModel or SetModel must be called First PopulateModelWithGroup(model); if (Fails()) return; PopulateUpdateModel(model); try { _dbContext.Update(MODEL); await _dbContext.SaveChangesAsync(_authUser); return; } catch (Exception ex) { LogError(LoggingEvents.GetItemError, ex, String.Format("{0}-Update-Error", _nameofModel)); AddErrorState("create-error", "create-error {0}", model.Name); } } protected virtual Model PopulateCreateModel(Model model) { PopulateUpdateModel(model); MODEL.Parent = (Parent)PARENT; return MODEL; } protected virtual Model PopulateUpdateModel(Model model) { MODEL.Name = model.Name; MODEL.Description = model.Description; return MODEL; } protected virtual Model PopulateModelWithGroup(Model model) { return MODEL; } public bool Fails() => !this.ModelState.IsValid; public void LogInformation(int eventId, string infoString, params object[] args) { _logger.LogInformation(eventId, infoString + "({id})", args); } public void LogWarning(int eventId, string message, params object[] args) { _logger.LogWarning(eventId, message, args); } public void LogError(int eventId, Exception exception, string errorString, params object[] args) { _logger.LogError(eventId, exception, errorString, args); } public void AddErrorState(string input, string message, params object[] args) { ModelState.AddModelError(input, _localizer[message, args]); } public Component GetTreeviewFolder(Folder folder, bool deep = true) { var _folderService = (FolderService)ParentService; _folderService.SetType(_table); Composite tree = new Composite(folder); List<Folder> folders = _folderService.FetchModels(folder.Id).Result; List<Model> files = FetchModels(folder.Id).Result; if (folders.Count() > 0) if (deep) // Get also descendants folders.ForEach(f => tree.Add(GetTreeviewFolder(f))); // tree.Children = folders.Select(f => GetTreeview(f)).ToList(); else //get only direct children folders.ForEach(f => tree.Add(new Leaf(f))); if (files.Count() > 0) // Get no folder children files.ForEach(file => tree.Add(new Leaf(file))); return tree; } public Component GetTreeview(Parent parent, bool deep = true) { if (parent is Folder) { return GetTreeviewFolder(parent as Folder, deep); } else { Composite tree = new Composite(parent); List<Model> files = FetchModels(parent.Id).Result; if (files.Count() > 0) // Get no folder children files.ForEach(file => tree.Add(new Leaf(file))); return tree; } } public List<Component> GetTreeviews() { if (!(ParentService is FolderService)) return null; return ((FolderService)ParentService).SetType(_table).FetchModels(0).Result .Select(folder => GetTreeviewFolder(folder)).ToList<Component>(); } public virtual Task<bool> ValidateNameExists(Model model) { return ExistsByName(model.ParentId, model.Name, MODEL.Name); } public virtual IQueryable<Model> GetModel(long id) => _dbContext.Queryable(_table).Cast<Model>().Where(Model => Model.Id == id && Model.AccountId == _authUser.AccountId); public virtual IQueryable<Model> GetModels(long parentId, params object[] param) => _dbContext.Queryable(_table).Cast<Model>() .Where<Model>(Model => Model.AccountId == _authUser.AccountId && parentId == Model.ParentId); public virtual Task<bool> ExistsBy( [NotNullAttribute] Expression<Func<Model, bool>> predicate) => _dbContext.Queryable(_table).Cast<Model>().Where(m => m.AccountId == _authUser.AccountId) .AnyAsync<Model>(predicate); public virtual Task<bool> ExistsByName(long parentId, string name1, string name2) { if (StringUtilities.Equals(name1, name2)) return Task.FromResult(false); return ExistsBy(m => m.ParentId == parentId && StringUtilities.Equals(m.Name, name1)); } public Leaf GetLeaf<T>(long id) where T : Accountable => new Leaf(_dbContext.Set<T>().Where(Model => Model.Id == id && Model.AccountId == _authUser.AccountId) .FirstOrDefault()); public Task<Model> Delete(Model model) { _dbContext.Remove(model); _dbContext.SaveChangesAsync(); return Task.FromResult<Model>(model); } public List<Leaf> GetParents(long id) { int count = 0; List<Leaf> leaves = new List<Leaf>(); IParentableService parentService = this; leaves.Add(GetLeaf<Parent>(id)); while (count < 10) { id = Convert.ToInt64((leaves[count].Entity as Identificable).GetPropertyValue("ParentId")); if (id.Equals(0)) break; System.Type type = (leaves[count].Entity as Identificable).GetPropertyType("Parent"); leaves.Add((Leaf)this.GetType().GetMethod("GetLeaf") .MakeGenericMethod(type) .Invoke(this, new object[] { id })); count++; } leaves.Reverse(); return leaves; } public bool HasRight(Right right) { if (_authService.HasRight(right)) return true; LogWarning(LoggingEvents.ForbiddenItem, "has non access right"); return false; } public bool CanAccessAccountResource(IOAccountable resource) { if (_authService.CanAccessAccountRessource(resource)) return true; LogWarning(LoggingEvents.ForbiddenItem, "cannot-access-resource-account"); return false; } public virtual bool CanAccessGroupResouce(IOGroupable resource) { return true; } public RouteValueDictionary GetRouteValues() => _authService.GetHttpContext().Request.RouteValues; /* static Expression<Func<Model, bool>> CombinePredicates(Expression<Func<Model, bool>> predicate1, Expression<Func<Model, bool>> predicate2) { var body = Expression.AndAlso(predicate1.Body, predicate2.Body); var expr3 = PredicateBuilder.And(expr1, expr2); return Expression.Lambda<Func<Model, bool>>(body, predicate2.Parameters[0]); } */ } }<file_sep>import { ExistAsyncDirective } from './exist-async.directive'; describe('ExistAsyncDirective', () => { it('should create an instance', () => { const directive = new ExistAsyncDirective(); expect(directive).toBeTruthy(); }); }); <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using MiniS.Areas.Admin.Models; using MiniS.Areas.Identity.Authorization; using MiniS.Areas.Identity.Data; using MiniS.Areas.Identity.Models; namespace MiniS.Areas.Identity.Controllers { [Route("api/{account}/security/access-template")] [Authorize] [Account] public class AccessTemplateController: ControllerBase { public AccessTemplateController( AppDbContext dbContext ){ _dbContext = dbContext; } public AppDbContext _dbContext { get; } [HttpGet] public async Task<ActionResult<List<AccessTemplate>>> GetAllAsync(){ Account account = (Account) HttpContext.Items["account"]; return await _dbContext.AccessTemplates.Where(at=>at.Account.Id == account.Id).ToListAsync<AccessTemplate>(); } [HttpGet("{Id}", Name="GetAccessTemplate")] public async Task<ActionResult<AccessTemplate>> GetAsync(int Id){ AccessTemplate accesstemplate = await _dbContext.AccessTemplates.FindAsync(Id); if (accesstemplate == null) return NotFound(); return accesstemplate; } [HttpPost] public async Task<ActionResult<AccessTemplate>> CreateAsync(AccessTemplate accessTemplate){ await _dbContext.AccessTemplates.AddAsync(accessTemplate); await _dbContext.SaveChangesAsync((AccountUser) HttpContext.Items["authUser"], (Account) HttpContext.Items["account"]); return CreatedAtRoute("GetAccessTemplate", new {Id= accessTemplate.Id}, accessTemplate); } [HttpPut("{id}")] public async Task<ActionResult<AccessTemplate>> updateAsync(long id, AccessTemplate access) { if (id != access.Id) { return BadRequest(new { Message = "mismatch access template ID" }); } _dbContext.Entry(access).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); return access; } [HttpDelete("{id}")] public async Task<IActionResult> DeleteAsync(long id) { var access = await _dbContext.AccessTemplates.FindAsync(id); if (access == null) { return NotFound(new {Message="no access template with this Id was found"}); } access.Deleted = DateTime.Now; _dbContext.Entry(access).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); return NoContent(); } } }<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { InfoFormControlComponent } from './info-form-control.component'; import { FormsModule } from '@angular/forms'; import { InputFieldDirective } from '../input-field/input-field.directive'; import { IconModule } from '../../icon/icon.module'; @NgModule({ declarations: [InfoFormControlComponent, InputFieldDirective], imports: [ CommonModule, FormsModule, IconModule ], exports: [InfoFormControlComponent] }) export class InfoFormControlModule { } <file_sep>import { Component, OnInit } from "@angular/core"; import { AccountDataListService } from "../../account-data-list/account-data-list.service"; import { AccountDataDbFormService } from "../account-data-db-form/account-data-db-form.service"; import { ActivatedRoute } from "@angular/router"; import { FieldAttribute, FieldType } from "../models/field"; import { ColDisplay } from "src/app/widgets/datatable/datatable.interface"; import { InputType } from "src/app/enums/input-type.enum"; @Component({ selector: "app-account-data-db-data", templateUrl: "./account-data-db-data.component.html", styleUrls: ["./account-data-db-data.component.sass"] }) export class AccountDataDbDataComponent implements OnInit { constructor( private listService: AccountDataListService, private formService: AccountDataDbFormService, private route: ActivatedRoute ) {} public columns = {}; public loading: boolean = true; public fieldAttributes: Array<FieldAttribute>; public cols: Array<ColDisplay> = []; public items: any = {}; public ngOnInit() { this.route.params.subscribe(routeParams => { this.formService.getFieldAttributes(routeParams.id).subscribe(r => { this.fieldAttributes = r; this.updateCols(); }); }); } private updateCols() { let i = 0; const l = this.fieldAttributes.filter( fa => fa.field.type == FieldType.List || fa.field.type == FieldType.DependentList ).length; this.fieldAttributes.forEach(fa => { let col = { key: fa.field.guid, display: fa.name, show: !fa.options[fa.field.inputType].hidden, inputType: this.columnToInputType(fa), sort: "none", items: null }; if ( fa.field.type == FieldType.List || fa.field.type == FieldType.DependentList ) { this.listService.getListItems(fa.field.list.id).subscribe(r => { i++; col.items = this.items[fa.field.guid] = r; this.cols.push(col); this.loading = i < l; }); } else { this.cols.push(col); } this.loading = l > 0; }); } /* isCreate = false selections: { [key: number]: boolean } = {} keys = Object.keys inputType = InputType public list: List public listItems: Array<ListItem> = [] public pListItems: ListItem[] = [] public loading: boolean = true ngOnInit() { this.loading = true this.route.params.subscribe(routeParams => { this.loading = true this.listService.getList(routeParams.id, "true") .subscribe(l => { this.list = l forkJoin( this.listService.goToListItem(l.id), (this.list.dependant ? this.listService.goToListItem(l.pListId) : of(undefined)) ).subscribe( r => { this.listItems = r[0] this.afterPLi(r[1]) } ) }) }) } public afterPLi(pli: Array<ListItem>) { this.pListItems = pli this.defaultCol = Object.assign(defaultColumns, { pListItem: { show: this.list.dependant, inputType: InputType.Select, items: this.pListItems }, groups: { show: true, inputType: InputType.MultiSelect, items: this.groupService.groups } }) this.loading = false } public defaultCol: any = {} */ /* public editselections() { let id = Object.keys(this.selections).find(s => this.selections[s]) if (id) this.users.some(u => { if (u.id == id) { u.showEdit = true return true } }) } public deleteselections() { let id = Object.keys(this.selections).find(s => this.selections[s]) if (id) this.users.some(u => { if (u.id == id) { u.showEdit = true return true } }) } */ /* get selectionsIsEmpty(): boolean { return objectHasLess(this.selections, 0) } */ private columnToInputType(fieldAttribute: FieldAttribute): InputType { if ( fieldAttribute.field.type == FieldType.Decimal || fieldAttribute.field.type == FieldType.Integer ) return InputType.Number; /* if ( fieldAttribute.field.type == FieldType.DependentList || fieldAttribute.field.type == FieldType.List ) { if (fieldAttribute.field.) return InputType.MultiSelect; else return InputType.Select; } */ if (fieldAttribute.field.type == FieldType.Text) return InputType.Text; } } <file_sep> // using MiniS.Areas.Data.Models; // using MiniS.Areas.Identity.Data; // using MiniS.Areas.Master; // using MiniS.Areas.Master.Enums; // namespace MiniS.Areas.Data.Repositories { // public class FormRepository : AccountGroupRepository<Form,long, Database> { // public FormRepository(AppDbContext dbContext) : base(dbContext) // { // } // protected override Table _table => Table.Form; // } // }<file_sep>import { Component, OnInit } from '@angular/core'; import { AccountUserService } from './account-user.service'; import { AccountService } from '../../account.service'; import { AccountUser } from './account-user.model'; import { isEmpty } from 'src/app/helpers/object.helper'; @Component({ selector: 'app-account-security-user', templateUrl: './account-security-user.component.html', styleUrls: ['./account-security-user.component.scss'] }) export class AccountSecurityUserComponent implements OnInit { constructor(private accountService: AccountService, private accountUserService: AccountUserService) { } public showCreate = false public account: string public showGroup: boolean = false public selected: { [s: string]: boolean; } = {} public showColumn = ['firstName', 'lastName', 'userName', 'email', 'createdBy','createdAt','lastUpdatedAt', 'lastUpdatedBy'] public ngOnInit() { //assign the account string from the route data this.account = this.accountService.account.normalizedName this.accountUserService.getUsers(this.account).subscribe() } get users(): Array<AccountUser> { return this.accountUserService.accountUsers } public delete(id: string):void { this.accountUserService.delete(this.account, id).subscribe() } public editSelected() { let id = Object.keys(this.selected).find(s => this.selected[s]) if(id) this.users.some(u => { if (u.id == id) { u.showEdit = true return true } }) } public deleteSelected() { let id = Object.keys(this.selected).find(s => this.selected[s]) if(id) this.users.some(u => { if (u.id == id) { u.showEdit = true return true } }) } get selectedIsEmpty(): boolean { return isEmpty(this.selected) } } <file_sep>import { concat, isBoolean, isNil, isString } from 'lodash'; import { Table } from 'src/app/enums/table.enum'; export interface TreeviewSelection { checkedItems: TreeviewItem[]; uncheckedItems: TreeviewItem[]; } function concatSelection( items: TreeviewItem[], checked: TreeviewItem[], unchecked: TreeviewItem[] ): { [k: string]: TreeviewItem[] } { let checkedItems = [...checked]; let uncheckedItems = [...unchecked]; for (const item of items) { const selection = item.getSelection(); checkedItems = concat(checkedItems, selection.checkedItems); uncheckedItems = concat(uncheckedItems, selection.uncheckedItems); } return { checked: checkedItems, unchecked: uncheckedItems }; } export interface TreeItem { text: string; value: any; type: Table disabled?: boolean; checked?: boolean; collapsed?: boolean; entity?: any; pEntity?: any; children?: TreeItem[]; } export class TreeviewItem { private internalDisabled = false; private internalChecked = false; private internalCollapsed = false; private internalChildren: TreeviewItem[]; text: string; value: any; entity: any; pEntity: any; type: Table; constructor(item?: TreeItem, autoCorrectChecked = false) { if (isNil(item)) { throw new Error('Item must be defined'); } if (isString(item.text)) { this.text = item.text; } else { throw new Error('A text of item must be string object'); } this.type = item.type this.value = item.value; if (isBoolean(item.checked)) { this.checked = item.checked; } if (!isNil(item.pEntity)) { this.pEntity = item.pEntity } if (isBoolean(item.collapsed)) { this.collapsed = item.collapsed; } if (isBoolean(item.disabled)) { this.disabled = item.disabled; } if (!isNil(item.children) && item.children.length > 0) { this.children = item.children.map(child => { if (this.disabled === true) { child.disabled = true; } child.pEntity = item.entity return new TreeviewItem(child); }); } if (!isNil(item.entity)) this.entity = item.entity if (autoCorrectChecked) { this.correctChecked(); } } get checked(): boolean { return this.internalChecked; } set checked(value: boolean) { if (!this.internalDisabled) { if (this.internalChecked !== value) { this.internalChecked = value; } } } get indeterminate(): boolean { return this.checked === undefined; } setCheckedRecursive(value: boolean) { if (!this.internalDisabled) { this.internalChecked = value; if (!isNil(this.internalChildren)) { this.internalChildren.forEach(child => child.setCheckedRecursive(value)); } } } get disabled(): boolean { return this.internalDisabled; } set disabled(value: boolean) { if (this.internalDisabled !== value) { this.internalDisabled = value; if (!isNil(this.internalChildren)) { this.internalChildren.forEach(child => child.disabled = value); } } } get collapsed(): boolean { return this.internalCollapsed; } set collapsed(value: boolean) { if (this.internalCollapsed !== value) { this.internalCollapsed = value; } } setCollapsedRecursive(value: boolean) { this.internalCollapsed = value; if (!isNil(this.internalChildren)) { this.internalChildren.forEach(child => child.setCollapsedRecursive(value)); } } get children(): TreeviewItem[] { return this.internalChildren; } set children(value: TreeviewItem[]) { if (this.internalChildren !== value) { if (!isNil(value) && value.length === 0) { throw new Error('Children must be not an empty array'); } this.internalChildren = value; if (!isNil(this.internalChildren)) { let checked = null; this.internalChildren.forEach(child => { if (checked === null) { checked = child.checked; } else { if (child.checked !== checked) { checked = undefined; return; } } }); this.internalChecked = checked; } } } getSelection(): TreeviewSelection { let checkedItems: TreeviewItem[] = []; let uncheckedItems: TreeviewItem[] = []; if (isNil(this.internalChildren)) { if (this.internalChecked) { checkedItems.push(this); } else { uncheckedItems.push(this); } } else { const selection = concatSelection(this.internalChildren, checkedItems, uncheckedItems); checkedItems = selection.checked; uncheckedItems = selection.unchecked; } return { checkedItems: checkedItems, uncheckedItems: uncheckedItems }; } correctChecked() { this.internalChecked = this.getCorrectChecked(); } private getCorrectChecked(): boolean { let checked: boolean = null; if (!isNil(this.internalChildren)) { for (const child of this.internalChildren) { child.internalChecked = child.getCorrectChecked(); if (checked === null) { checked = child.internalChecked; } else if (checked !== child.internalChecked) { checked = undefined; break; } } } else { checked = this.checked; } return checked; } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { AccountService } from 'src/app/account/account.service'; import { GroupService } from 'src/app/account/security/group/state/group.service'; import { Group } from 'src/app/account/security/group/state/group.model'; import { TreeviewItem } from 'src/app/widgets/ngx-treeview'; import { isNil } from 'lodash'; import { Table } from 'src/app/enums/table.enum'; import { UserLevel } from '../../account-security-user/user-level.enum'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { ITrackable } from 'src/app/master/base-model/trackable.model'; import { IIdentificable } from 'src/app/master/base-model/identificable.model'; @Component({ selector: 'app-group-form-control', templateUrl: './group-form-control.component.html', }) export class GroupFormControlComponent implements OnInit { public treeview$: Observable<TreeviewItem[]> constructor(private groupService: GroupService, private accountService: AccountService) { } @Input() parentModel: any = null @Input() model: any = null @Input() public showAllGroup: boolean = true private groups: Group[] = [] get loading$(): Observable<boolean> { return this.groupService.store.loading$ } ngOnInit() { this.groups = this.parentModel && !this.parentModel.allGroup && (this.parentModel.userLevel & UserLevel.Group) != UserLevel.Group ? this.parentModel.groups : [] this.treeview$ = this.groupService.treeview$.pipe(map(r=>this.updateFilterItems(r),this)) this.model.showEdit || (this.model.allGroup = true) this.parentModel && !this.parentModel.allGroup && (this.model.allGroup = false) } onSelect(selected:IIdentificable[]){ selected = selected || [] this.groupService.selected = selected.map(s=>s.id) this.groupService.getTreeview().subscribe() } myGroups() { this.model.groups = this.groups.filter(gr => this.accountService.authUser.groups.map(g => g.id).indexOf(gr.id) > -1) } allGroups() { this.model.groups = this.groups } private updateFilterItems(r: TreeviewItem[]): TreeviewItem[] { if (this.groups.length > 0) { const filteredGroups: TreeviewItem[] = []; r.forEach(item => { const newItem = this.filterItem(item, this.groups); if (!isNil(newItem)) { filteredGroups.push(newItem); } }); console.log(filteredGroups, "filteredGroups") return filteredGroups; } else { return r; } } private filterItem(item: TreeviewItem, groups: Group[]): TreeviewItem { const isMatch = groups.findIndex(g => g.id == item.value && item.type == Table.Group) > -1 if (isMatch) { return item; } else { if (!isNil(item.children)) { const children: TreeviewItem[] = []; item.children.forEach(child => { const newChild = this.filterItem(child, groups); if (!isNil(newChild)) { children.push(newChild); } }); if (children.length > 0) { const newItem = new TreeviewItem(item); newItem.collapsed = false; newItem.children = children; return newItem; } } } return undefined; } } <file_sep> using System; using System.Collections.Generic; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Data.Models { public interface IComponent { string Text { get; } long Value { get; } bool IsComposite(); bool IsExtendable(); } public abstract class Component : IComponent { public IIdentificable Entity { get; set; } public Component(IIdentificable entity) { Entity = entity; } public string Text { get => Entity.Name; } public long Value { get => Entity.Id; } public Table type { get => Entity.Table; } public virtual void Add(Component component) { throw new NotImplementedException(); } public virtual void Remove(Component component) { throw new NotImplementedException(); } public virtual bool IsComposite() { return true; } public virtual bool IsExtendable() { return false; } } public class Leaf : Component { public Leaf(IIdentificable entity) : base(entity) { } public override bool IsComposite() { return false; } } public class Composite : Component { public Composite(IIdentificable entity) : base(entity) { } public List<Component> Children { get; set; } = new List<Component>(); public override bool IsExtendable() { return Children.Count > 0; } public override void Add(Component component){ Children.Add(component); } } } <file_sep>import { Stepper } from './stepper'; describe('Stepper', () => { it('should create an instance', () => { expect(new Stepper()).toBeTruthy(); }); }); <file_sep>// using System; // using System.Linq; // using Microsoft.EntityFrameworkCore; // using MiniS.Areas.Data.Models; // using MiniS.Areas.Identity.Data; // using MiniS.Areas.Identity.Models; // using MiniS.Areas.Master; // using MiniS.Areas.Master.Enums; // namespace MiniS.Areas.Data.Repositories // { // public class ListItemRepository : AccountGroupRepository<ListItem, long, List> // { // public ListItemRepository(AppDbContext dbContext) : base(dbContext) // { // } // protected override Table _table => Table.ListItem; // public override IQueryable<ListItem> GetModels(long parentId, params object[] param) // { // var query = base.GetModels(parentId).Include(ListItem => ListItem.ParentListItem); // return param == null || param.Length == 0 ? query : // query.Where<ListItem>(ListItem => param.Any(param => ListItem.ParentListItemId == Convert.ToInt64(param))); // } // } // }<file_sep>import { Pipe, PipeTransform } from '@angular/core'; import { Table } from 'src/app/enums/table.enum'; @Pipe({ name: 'fa' }) export class TableToIconPipe implements PipeTransform { transform(value: Table, args?: any): string { switch (value) { case Table.Database: return 'database' case Table.List: return 'list' case Table.Folder: return 'folder' default: return 'file' } } } <file_sep> using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; using MiniS.Areas.Master.Validators; namespace MiniS.Areas.Data.Models { public class Folder : Groupable<Folder > { [ValidEnum] public Table Type {get; set;} [InverseProperty("Parent")] public List<Folder> Folders { get; set; } [NotMapped] public bool ShowAdd { get; set; } = false; } public class FolderConfiguration : GroupableConfiguration<Folder,Folder> { public override void Configure(EntityTypeBuilder<Folder> builder) { base.Configure(builder); builder.Property(e => e.Type).HasConversion(new EnumToStringConverter<Table>()); } } }<file_sep> using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MiniS.Areas.Master.Enums; using MiniS.Areas.Master.Models; namespace MiniS.Areas.Data.Models { public class Form : Groupable<Database> { [InverseProperty("Parent")] public List<FieldAttribute> FieldAttributes {get; set;} [InverseProperty("Parent")] public List<Stepper> Steppers {get; set;} [NotMapped] public bool ShowForm {get; set;} = false; } public class FormConfiguration : GroupableConfiguration<Form,Database> { } }
0d492bf594b5eb79d5f166b98d45b0de15ce18ae
[ "Markdown", "C#", "TypeScript" ]
281
C#
achouaiekh/MiniS
c45e7379210b9993ccaebeaeef1b8c473a5741fe
a5b2b8fa501920e27e3c04218429afefeeb4b70b
refs/heads/master
<file_sep># -*- coding: utf-8 -*- import datetime import requests as req import xmlschema from smtplib import SMTP from email.mime.text import MIMEText import sys from eztable import Table def return_unicode_string(_str): return u''.join(_str) class RedmineConnection: parameters = None server = None def initialize_parameters(self): self.parameters = { "key": "<YOUR_API_KEY>", "server": "http://redmine.com.ua", "copy_to": "<EMAIL>", "smtp_login": "test", "smtp_pass": "<PASSWORD>", "smtp_server": "mail.com", "limit": 100, "assigned_to_id": 23, "from": "<EMAIL>" } def send_mail(self, to, subject, text): self.initialize_parameters() parameters = self.parameters if self.server is None: server_login = self.parameters["smtp_login"] server_password = self.parameters["smtp_pass"] smtp_server = self.parameters["smtp_server"] server = SMTP(smtp_server, 587) server.login(server_login, server_password) self.server = server msg = MIMEText(text, _charset="utf-8") msg['Subject'] = subject msg['From'] = parameters["from"] msg['To'] = ""+to self.server.sendmail(parameters["from"], to, msg.as_string()) class RedmineIssues: # datatype users or issues def get_data(self): connection = RedmineConnection() connection.initialize_parameters() parameters = connection.parameters key = parameters["key"] server = parameters["server"] limit = parameters["limit"] assigned_to_id = parameters["assigned_to_id"] url = "{0}/{1}?key={2}&limit={3}&assigned_to_id={4}".format( server, "issues.xml", key, limit, # limit assigned_to_id ) print "getting data at : "+url+"&" data = req.get(url) content = u''.join(data.text).encode("utf-8") if content: print "issues updated!" f = open("issues.xml", "w") f.write(content) f.close() else: "sorry, something wrong :(" f = open("issues.xml", "r") my_sch = xmlschema.XMLSchema('issues.xsd') data = my_sch.to_dict('issues.xml') return data class RedmineUsers: data = None # Образец : # {'last_login_on': u'2018-10-09 08:28:21 UTC', # 'firstname': u'firstname', # 'lastname': u'lastname', 'created_on': u'2018-07-27 13:58:14 UTC', # 'mail': u'<EMAIL>', 'login': u'login', 'id': 48} def get_user_info(self): connection = RedmineConnection() connection.initialize_parameters() my_sch = xmlschema.XMLSchema('users.xsd') data = my_sch.to_dict('users.xml') self.data = data return data def get_user_by_id(self, id): if self.data == None: connection = RedmineConnection connection.initialize_parameters() self.get_user_info() for user in self.data['user']: if user['id'] == id: return user def process_data(data, connection): parameters = connection.parameters today = datetime.datetime.today() authors_issues = {} for issue in data['issue']: uni_author_name = issue['author']["@id"] status = issue['status']['@id'] # http://<redmine>/issue_statuses.xml # 4 - обратная связь от постановщика # 12 - Требуется тест. пользователем if not status in [4, 12]: continue strDate = issue['updated_on'][:-4] if len(strDate) == 16: issue_date = datetime.datetime.strptime(strDate, "%Y-%m-%dT%H:%M") else: issue_date = datetime.datetime.strptime( strDate, "%Y-%m-%d %H:%M:%S") delta = today - issue_date if delta.days < 7: print "Номер задачи {0}, прошло дней {1} дата задачи {2}".format( issue['id'], delta.days, issue_date) continue else: print "Номер задачи {0}, прошло дней {1} дата задачи {2}".format( issue['id'], delta.days, issue_date) info = u"{1} {2}/issues/{0}".format( issue['id'], issue['subject'], parameters["server"]) if authors_issues.has_key(uni_author_name): # если автор уже есть, то добавляем задачу в его массив authors_issues[uni_author_name].append(info) else: authors_issues[uni_author_name] = [] authors_issues[uni_author_name].append(info) return authors_issues def printDataGroupedByProjects(data): if not data.has_key("issue"): print "data doesn't have key issue" project = {} p = Table( # ['project' , ('issue_id',int) , 'issue_subject','issue'] ['project', 'tracker', ('issue_id', int), 'issue_status', 'issue_subject', 'issue_description'] ) for issue in data['issue']: project_name = issue["project"]["@name"] issue_id = issue["id"] issue_status = issue["status"]["@name"] issue_subject = str((issue["subject"])).strip() tracker = issue["tracker"]["@name"] issue_description = issue["description"] # p.append([project_name,issue_id,issue_subject,issue["description"]]) p.append([project_name, tracker, issue_id, issue_status, issue_subject, issue_description]) p.to_csv(open("issues.csv", "w")) def sendNotificationAboutUnclosedTasks(data, connection, params): issues = process_data(data, connection) redmineUsers = RedmineUsers() redmineUsers.get_user_info() for k in issues.keys(): user_info = redmineUsers.get_user_by_id(k) message = "Добрый день {0} {1}! \n email : {2} \n " \ "У Вас есть незакрытые задачи в Redmine.".format( user_info['firstname'], user_info['lastname'], user_info['mail'] ) for issue in issues[k]: message += "\n \t"+issue connection.send_mail( connection.parameters["copy_to"], "Незакрытые задачи в Redmine", u''.join(message) ) connection.send_mail( user_info['mail'], "Незакрытые задачи в Redmine", u''.join(message) ) if connection.server != None: connection.server.quit() def main(): reload(sys) sys.setdefaultencoding("utf8") connection = RedmineConnection() connection.initialize_parameters() redmineIssues = RedmineIssues() data = redmineIssues.get_data() printDataGroupedByProjects(data) # sendNotificationAboutUnclosedTasks(data, connection,connection.parameters)
f0e5cb6fc28073a84877eff6ba90101798f95616
[ "Python" ]
1
Python
jzabrodin/redmine_email_notifier
9354c99aa50574bf9061074c891bdfcfb0261068
07ce3aaf8f76ef7c5603f656779c338ea95947f1
refs/heads/master
<repo_name>NorthSanta/Mesh_Mecanica<file_sep>/GL_framework/src/physics.cpp #include <imgui\imgui.h> #include <imgui\imgui_impl_glfw_gl3.h> #include <GL\glew.h> #include <glm\gtc\type_ptr.hpp> #include <glm\gtc\matrix_transform.hpp> #include <cstdio> bool show_test_window = false; float radius; float reset ; const int numCols = 14; const int numRows = 18; float posX = 0; float posY = 0; float posZ = 0; float posX0 = 0; float posY0 = 0; float posZ0 = 0; float incliZ = 0.1; float data[numCols * numRows * 3]; float vecx; float vecy; float vecz; float modul; float v1; float v2; int ke = 50; int kd = 1; float restDist; float llargada = 0.5f; float llargadaShear; float llargadaBending; float mass = 1; struct Particle { glm::vec3 pos; glm::vec3 velocity; glm::vec3 antPos; glm::vec3 Forces; }; Particle* totalParts; Particle* AntParts; namespace Sphere { extern void setupSphere(glm::vec3 pos = glm::vec3(0.f, 1.f, 0.f), float radius = 1.f); extern void cleanupSphere(); extern void updateSphere(glm::vec3 pos, float radius = 1.f); extern void drawSphere(); } namespace ClothMesh { extern void setupClothMesh(); extern void cleanupClothMesh(); extern void updateClothMesh(float* array_data); extern void drawClothMesh(); } void GUI() { { //FrameRate ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::SliderInt("KE", &ke,0,1000); ImGui::SliderInt("KD", &kd, 0, 10); ImGui::SliderFloat("Initial Rest Distance", &llargada, 0.3f,0.6); //TODO } // ImGui test window. Most of the sample code is in ImGui::ShowTestWindow() if(show_test_window) { ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver); ImGui::ShowTestWindow(&show_test_window); } } void structuralForceH(Particle* part[], int i, int j) { glm::vec3 structuralForce; glm::vec3 p1; glm::vec3 p2; glm::vec3 vec; p1 = glm::vec3(totalParts[i*numCols + j].pos.x, totalParts[i*numCols + j].pos.y, totalParts[i*numCols + j].pos.z); p2 = glm::vec3(totalParts[(i)*numCols + (j + 1)].pos.x, totalParts[(i)*numCols + (j + 1)].pos.y, totalParts[(i)*numCols + (j + 1)].pos.z); vec = p2 - p1; modul = glm::length(vec);//modul del vector float var = -(ke*(modul - llargada) + kd * glm::dot((totalParts[i*numCols + j].velocity - totalParts[(i)*numCols + (j + 1)].velocity), (vec / modul))); structuralForce = var*(vec / modul); totalParts[i*numCols + j].Forces += structuralForce; totalParts[(i)*numCols + (j + 1)].Forces += -structuralForce; } void structuralForceV(Particle* part[], int i, int j) { glm::vec3 structuralForce; glm::vec3 p1; glm::vec3 p2; glm::vec3 vec; p1 = glm::vec3(totalParts[i*numCols + j].pos.x, totalParts[i*numCols + j].pos.y, totalParts[i*numCols + j].pos.z); p2 = glm::vec3(totalParts[(i + 1)*numCols + j].pos.x, totalParts[(i + 1)*numCols + j].pos.y, totalParts[(i + 1)*numCols + j].pos.z); vec = p2 - p1; modul = glm::length(vec);//modul del vector float var = -(ke*(modul - llargada) + kd * glm::dot((totalParts[i*numCols + j].velocity - totalParts[(i + 1)*numCols + j].velocity), (vec / modul))); structuralForce = var*(vec / modul); totalParts[i*numCols + j].Forces += structuralForce; totalParts[(i + 1)*numCols + j].Forces += -structuralForce; } void shearFroceLeft(Particle* part[], int i, int j) { glm::vec3 structuralForce; glm::vec3 p1; glm::vec3 p2; glm::vec3 vec; p1 = glm::vec3(totalParts[i*numCols + (numCols - j)].pos.x, totalParts[i*numCols + (numCols - j)].pos.y, totalParts[i*numCols + (numCols - j)].pos.z); p2 = glm::vec3(totalParts[(i + 1)*numCols + ((numCols - j) - 1)].pos.x, totalParts[(i + 1)*numCols + ((numCols - j) - 1)].pos.y, totalParts[(i + 1)*numCols + ((numCols - j) - 1)].pos.z); vec = p2 - p1; modul = glm::length(vec);//modul del vector float var = -(ke*(modul - llargadaShear) + kd * glm::dot((totalParts[i*numCols + j].velocity - totalParts[(i + 1)*numCols + ((numCols - j) - 1)].velocity), (vec / modul))); structuralForce = var*(vec / modul); totalParts[i*numCols + (numCols - j)].Forces += structuralForce; totalParts[(i + 1)*numCols + ((numCols - j) - 1)].Forces += -structuralForce; } void shearFroceRight(Particle* part[], int i, int j) { glm::vec3 structuralForce; glm::vec3 p1; glm::vec3 p2; glm::vec3 vec; p1 = glm::vec3(totalParts[i*numCols + j].pos.x, totalParts[i*numCols + j].pos.y, totalParts[i*numCols + j].pos.z); p2 = glm::vec3(totalParts[(i + 1)*numCols + (j + 1)].pos.x, totalParts[(i + 1)*numCols + (j + 1)].pos.y, totalParts[(i + 1)*numCols + (j + 1)].pos.z); vec = p2 - p1; modul = glm::length(vec);//modul del vector float var = -(ke*(modul - llargadaShear) + kd * glm::dot((totalParts[i*numCols + j].velocity - totalParts[(i + 1)*numCols + (j + 1)].velocity), (vec / modul))); structuralForce = var*(vec / modul); totalParts[i*numCols + j].Forces += structuralForce; totalParts[(i + 1)*numCols + (j + 1)].Forces += -structuralForce; } void bendingForceH(Particle* part[], int i, int j) { glm::vec3 structuralForce; glm::vec3 p1; glm::vec3 p2; glm::vec3 vec; p1 = glm::vec3(totalParts[i*numCols + j].pos.x, totalParts[i*numCols + j].pos.y, totalParts[i*numCols + j].pos.z); p2 = glm::vec3(totalParts[(i)*numCols + (j + 2)].pos.x, totalParts[(i)*numCols + (j + 2)].pos.y, totalParts[(i)*numCols + (j + 2)].pos.z); vec = p2 - p1; modul = glm::length(vec);//modul del vector float var = -(ke*(modul - llargadaBending) + kd * glm::dot((totalParts[i*numCols + j].velocity - totalParts[(i)*numCols + (j + 2)].velocity), (vec / modul))); structuralForce = var*(vec / modul); totalParts[i*numCols + j].Forces += structuralForce; totalParts[(i)*numCols + (j + 2)].Forces += -structuralForce; } void bendingForceV(Particle* part[], int i, int j) { glm::vec3 structuralForce; glm::vec3 p1; glm::vec3 p2; glm::vec3 vec; p1 = glm::vec3(totalParts[i*numCols + j].pos.x, totalParts[i*numCols + j].pos.y, totalParts[i*numCols + j].pos.z); p2 = glm::vec3(totalParts[(i + 2)*numCols + (j)].pos.x, totalParts[(i + 2)*numCols + (j)].pos.y, totalParts[(i + 2)*numCols + (j)].pos.z); vec = p2 - p1; modul = glm::length(vec);//modul del vector float var = -(ke*(modul - llargadaBending) + kd * glm::dot((totalParts[i*numCols + j].velocity - totalParts[(i + 2)*numCols + (j)].velocity), (vec / modul))); structuralForce = var*(vec / modul); totalParts[i*numCols + j].Forces += structuralForce; totalParts[(i + 2)*numCols + (j)].Forces += -structuralForce; } void posCorrectV(int i, int j) { if (i < 17 && j < 13) { glm::vec3 p1; glm::vec3 p2; glm::vec3 vec; p1 = glm::vec3(totalParts[i*numCols + j].pos); p2 = glm::vec3(totalParts[(i + 1)*numCols + j].pos); vec = p2 - p1; float mod = glm::length(vec); float max = restDist + (restDist * 1 / 100); if (mod > max) { float diff = mod - max; glm::vec3 unit = vec / mod; p1 = p1 + unit*(diff / 2); p2 = p2 - unit*(diff / 2); totalParts[i*numCols + j].pos = p1; totalParts[(i + 1)*numCols + j].pos = p2; } } } void posCorrectH(int i, int j) { if (i < 17 && j < 13) { glm::vec3 p1; glm::vec3 p2; glm::vec3 vec; p1 = glm::vec3(totalParts[i*numCols + j].pos); p2 = glm::vec3(totalParts[i* numCols + (j + 1)].pos); vec = p2 - p1; float mod = glm::length(vec); float max = restDist + (restDist * 1 / 100); if (mod > max) { float diff = mod - max; glm::vec3 unit = vec / mod; p1 = p1 + (unit*(diff / 2)); p2 = p2 - (unit*(diff / 2)); totalParts[i*numCols + j].pos = p1; totalParts[i* numCols + (j + 1)].pos = p2; } } } void posCorrectShearRight(int i, int j) { if (i < 17 && j < 13) { glm::vec3 p1; glm::vec3 p2; glm::vec3 vec; p1 = glm::vec3(totalParts[i*numCols + j].pos); p2 = glm::vec3(totalParts[(i + 1)*numCols + (j+1)].pos); vec = p2 - p1; float mod = glm::length(vec); float max = llargadaShear - (llargadaShear * 1 / 100); if (mod > max ) { glm::vec3 unit = vec / mod; float diff = mod - max; p1 = p1 + unit*(diff / 2); p2 = p2 - unit*(diff / 2); totalParts[i*numCols + (j)].pos = p1; totalParts[(i + 1)*numCols + (j + 1)].pos = p2; } } } void posCorrectShearLeft(int i, int j) { if (i < 17 && j < 13) { glm::vec3 p1; glm::vec3 p2; glm::vec3 vec; p1 = glm::vec3(totalParts[i*numCols + (numCols -j)].pos); p2 = glm::vec3(totalParts[(i + 1)*numCols + ((numCols - j) - 1)].pos); vec = p2 - p1; float mod = glm::length(vec); float max = llargadaShear - (llargadaShear * 1 / 100); if (mod > max) { glm::vec3 unit = vec / mod; float diff = mod - max; p1 = p1 + unit*(diff / 2); p2 = p2 - unit*(diff / 2); totalParts[i*numCols + (numCols - j)].pos = p1; totalParts[(i + 1)*numCols + ((numCols - j) - 1)].pos = p2; } } } void PhysicsInit() { //TODO //ke = 5;//duresa de la molla //kd = 1;//restriccio del moviment restDist = llargada; llargadaShear = sqrt((llargada*llargada) + (llargada*llargada)); llargadaBending = llargada * 2; reset = 5; radius = ((float)rand() / RAND_MAX)*1.5+0.5; //printf("%f", radius); glm::vec3 vector = glm::vec3(((float)rand() / RAND_MAX) * 5 - 5, ((float)rand() / RAND_MAX) * 10, ((float)rand() / RAND_MAX) * 5 - 5); if (vector.y >= 10 - radius) { vector.y -= radius; } else if (vector.y <= 0 + radius) { vector.y += radius; } if (vector.x >= 5 - radius) { vector.x -= radius; } else if (vector.x <= -5 + radius) { vector.x += radius; } if (vector.z >= 5 - radius) { vector.z -= radius; } else if (vector.z <= -5 + radius) { vector.z += radius; } Sphere::updateSphere(vector,radius); /*for (int i = 0; i < numCols*numRows; i++) { printf("%d\n", 3*i +0); printf("%d\n", 3*i + 1); printf("%d\n", 3*i + 2); data[ 3+i + 0] = -4.5*i*0.5; data[ 3*i + 1] = -4.5*i*0.5; data[ 3*i + 2] = -4.5*i*0.5; }*/ totalParts = new Particle[14 * 18]; for (int i = 0; i < (numRows); ++i) { for (int j = 0; j < (numCols); ++j) { totalParts[i*numCols + j].pos = glm::vec3(j*restDist - 5, 8, i*restDist - 5 ); //printf("CurPos: %f\n", totalParts[i*numCols + j].pos.x); totalParts[i*numCols + j].antPos = glm::vec3(totalParts[i*numCols + j].pos.x, totalParts[i*numCols + j].pos.y, totalParts[i*numCols + j].pos.z); //printf("AntPos: %f\n", totalParts[i*numCols + j].antPos.x); totalParts[i*numCols + j].Forces.x = 0; totalParts[i*numCols + j].Forces.y = 0; totalParts[i*numCols + j].Forces.z = 0; totalParts[i*numCols + j].velocity.x = 0; totalParts[i*numCols + j].velocity.y = 0; totalParts[i*numCols + j].velocity.z = 0; data[3 * (i*numCols + j) + 0] = totalParts[i*numCols + j].pos.x; data[3 * (i*numCols + j) + 1] = totalParts[i*numCols + j].pos.y; data[3 * (i*numCols + j) + 2] = totalParts[i*numCols + j].pos.z; } } posX0 = data[0]; posY0 = data[1]; posZ0 = data[2]; posX = data[39]; posY = data[40]; posZ = data[41]; ClothMesh::updateClothMesh(data); } void PhysicsUpdate(float dt) { reset -= dt; if (reset <= 0) { PhysicsInit(); } for (int i = 0; i < (numRows); i++) { //printf("%d", i); for (int j = 0; j < (numCols); j++) { totalParts[i*numCols + j].Forces = glm::vec3(0, -9.8, 0); } } //TODO for (int i = 0; i < (numRows); i++) { //printf("%d", i); for (int j = 0; j < (numCols); j++) { //correcio de posicio posCorrectV(i, j); posCorrectH(i, j); posCorrectShearLeft(i, j); posCorrectShearRight(i, j); //calcul posicio Verlet glm::vec3 temp = totalParts[i*numCols + j].pos; totalParts[i*numCols + j].pos.x = totalParts[i*numCols + j].pos.x + (totalParts[i*numCols + j].pos.x - totalParts[i*numCols + j].antPos.x) + (totalParts[i*numCols + j].Forces.x / mass)*(dt*dt); totalParts[i*numCols + j].pos.y = totalParts[i*numCols + j].pos.y + (totalParts[i*numCols + j].pos.y - totalParts[i*numCols + j].antPos.y) + (totalParts[i*numCols + j].Forces.y / mass)*(dt*dt); totalParts[i*numCols + j].pos.z = totalParts[i*numCols + j].pos.z + (totalParts[i*numCols + j].pos.z - totalParts[i*numCols + j].antPos.z) + (totalParts[i*numCols + j].Forces.z / mass)*(dt*dt); totalParts[0].pos = glm::vec3(posX0, posY0, posZ0); totalParts[13].pos = glm::vec3(posX, posY, posZ); totalParts[i*numCols + j].velocity = (totalParts[i*numCols + j].pos - temp) / dt; totalParts[i*numCols + j].antPos = temp; if (j < numCols-1 && i < numRows -1) { //Structural Vertical structuralForceV(&totalParts, i, j); //Structural Horizontal structuralForceH(&totalParts, i, j); } if (j < 13 && i < 17) { //Shear Forces Right shearFroceRight(&totalParts, i, j); //Shear Forces Left shearFroceLeft(&totalParts, i, j); } if (j < 12 && i < 17) { //Bending Force Vertical bendingForceV(&totalParts, i, j); //Bending Force Horizontal bendingForceH(&totalParts, i, j); } data[3 * (i*numCols + j) + 0] = totalParts[i*numCols + j].pos.x; data[3 * (i*numCols + j) + 1] = totalParts[i*numCols + j].pos.y; data[3 * (i*numCols + j) + 2] = totalParts[i*numCols + j].pos.z; if (data[3 * (i*numCols + j) + 2] <= -5) { data[3 * (i*numCols + j) + 2] = -5; } } } /*data[0] = posX0; data[1] = posY0; data[2] = posZ0; data[39] = posX; data[40] = posY; data[41] = posZ;*/ ClothMesh::updateClothMesh(data); } void PhysicsCleanup() { //TODO ClothMesh::cleanupClothMesh(); delete[] totalParts; }<file_sep>/GL_framework/imgui.ini [Debug] Pos=435,28 Size=400,400 Collapsed=0
44afeb6948d291993a141bc9004094b03f97314d
[ "C++", "INI" ]
2
C++
NorthSanta/Mesh_Mecanica
dd9fb12f5e3da668d128553ed2ba6d0ec6f32250
f028a0098a908521c9386461fd410374ab2a946a
refs/heads/master
<file_sep>/* globals _,$,Backbone,Marionette,Howl */ (function () { "use strict"; // Constants var SETTINGS = { API: window.location.origin, ENABLE_PLAYLISTS: 0 }, // Models Item = Backbone.Model.extend({ urlRoot: SETTINGS.API + "/item/", getFileUrl: function () { return this.urlRoot + this.get("id") + "/file"; }, initialize: function () { this.prepForDisplay(); }, // Format times as minutes and seconds. formatTime: function(secs) { if (secs == undefined || isNaN(secs)) { return '0:00'; } secs = Math.round(secs); var mins = '' + Math.floor(secs / 60); secs = '' + (secs % 60); if (secs.length < 2) { secs = '0' + secs; } return mins + ':' + secs; }, prepForDisplay: function () { this.set("time", this.formatTime(this.get("length"))); } }), Album = Backbone.Model.extend({ urlRoot: SETTINGS.API + "/album/", model: Item, getItems: function () { this.url = "/album/" + this.model.get("id") + "?expand=1"; this.fetch(); } }), Artist = Backbone.Model.extend({}), Stats = Backbone.Model.extend({ url: SETTINGS.API + "/stats" }), // Collections Items = Backbone.Collection.extend({ url: SETTINGS.API + "/item/", model: Item, parse: function (data) { return data.items; }, comparator: 'track' }), Albums = Backbone.Collection.extend({ url: SETTINGS.API + "/album/", model: Album, parse: function (data) { return data.albums; } }), Artists = Backbone.Collection.extend({ url: SETTINGS.API + "/artist/", model: Artist, comparator: 'name', parse: function (data) { var r = _.map(data.artist_names, function (n) { return { name: n }; }); return r; } }), Queue = Backbone.Collection.extend({ model: Album }), // Templates JST = { "album/view": _.template($("#tpl-album-view").html()), "album/listview": _.template($("#tpl-album-list-view").html()), "album/detailview": _.template($("#tpl-album-detail-view").html()), "app/view": _.template($("#tpl-app-view").html()), "artist/view": _.template($("#tpl-artist-view").html()), "artist/listview": _.template($("#tpl-artist-list-view").html()), "item/view": _.template($("#tpl-item-view").html()), "item/detailview": _.template($("#tpl-item-detail-view").html()), "item/listview": _.template($("#tpl-item-list-view").html()), "nowplaying/view": _.template($("#tpl-nowplaying-view").html()), "nowplaying/timingview": _.template($("#tpl-nowplaying-timing-view").html()), "queue/listview": _.template($("#tpl-queue-list-view").html()), "queue/emptyview": _.template($("#tpl-queue-empty-view").html()), "queue/itemview": _.template($("#tpl-queue-item-view").html()), "savedplaylist/view": _.template($("#tpl-savedplaylist-view").html()), "search/view": _.template($("#tpl-search-view").html()), "search/itemview": _.template($("#tpl-search-item-view").html()), "sidebar/view": _.template($("#tpl-sidebar-view").html()), "stats/view": _.template($("#tpl-stats-view").html()), }, // Views ItemDetailView = Marionette.View.extend({ template: JST["item/detailview"], templateContext: function () { return { time: this.model.formatTime(this.model.get("length")), }; } }), SavedPlaylistView = Marionette.View.extend({ template: JST["savedplaylist/view"] }), SidebarView = Marionette.View.extend({ template: JST["sidebar/view"], className: "sidebar-sticky", events: { "click .nav-link.search-link": function () { this.$(".nav-link.active").removeClass("active"); this.$(".nav-link.search-link").addClass("active"); }, "click .nav-link.queue-link": function () { this.$(".nav-link.active").removeClass("active"); this.$(".nav-link.queue-link").addClass("active"); }, "click .nav-link.albums-link": function () { this.$(".nav-link.active").removeClass("active"); this.$(".nav-link.albums-link").addClass("active"); }, "click .nav-link.stats-link": function () { this.$(".nav-link.active").removeClass("active"); this.$(".nav-link.stats-link").addClass("active"); }, "click .nav-link.artists-link": function () { this.$(".nav-link.active").removeClass("active"); this.$(".nav-link.artists-link").addClass("active"); }, }, regions: { "savedplaylists": "#savedplaylists" }, initialize: function () { this.listenTo(App.queue, "update", this.render); }, onRender: function () { if (SETTINGS.ENANLE_PLAYLISTS) { this.showChildView("savedplaylists", new SavedPlaylistView()); } }, templateContext: function () { return { queue_size: App.queue.size() }; }, }), QueueEmptyView = Marionette.View.extend({ template: JST["queue/emptyview"] }), QueueChildView = Marionette.View.extend({ tagName: "li", template: JST["queue/itemview"], events: { "click .play-button": function () { App.playTrack(this.model); }, "click .info-button": function () { App.router.navigate("track/" + this.model.get("id"), { trigger: true }); }, }, }), QueueView = Marionette.CollectionView.extend({ template: JST["queue/listview"], childViewContainer: ".js-widgets", emptyView: QueueEmptyView, childView: QueueChildView, events: { "click .play-icon": function () { App.playNext(); } } }), SearchResultView = Marionette.View.extend({ template: JST["search/itemview"], className: "list-group-item", events: { "click .play-button": function () { App.playTrack(this.model); }, "click .add-button": function () { App.queue.push(this.model); }, "click .info-button": function () { App.router.navigate("track/" + this.model.get("id"), { trigger: true }); }, }, }), SearchView = Marionette.CollectionView.extend({ template: JST["search/view"], tagName: "ul", className: "list-group", collection: new Items(), childView: SearchResultView, events: { "blur #query": "doSearch", "click .search-icon": "doSearch", "click button": "doSearch", "submit form": "doSearch" }, ui: { "q": "#query" }, doSearch: function () { var $inputField = this.getUI("q"); var query = $inputField.val(); var queryURL = query.split(/\s+/).map(encodeURIComponent).join("/"); var url = SETTINGS.API + "/item/query/" + queryURL; var self = this; $.getJSON(url, function (data) { self.collection.set(data.results); }); }, }), AlbumListChildView = Marionette.View.extend({ tagName: "li", className: "list-group-item", template: JST["album/view"], events: { "click .add-button": "doQueue" }, doQueue: function () { this.model.url = "/album/" + this.model.get("id") + "?expand=1"; this.model.fetch({ success: function (data) { var items = data.attributes.items; _.each(items, function (item) { var i = new Item( item ); App.queue.push(i); }); } }); } }), AlbumListView = Marionette.CollectionView.extend({ template: JST["album/listview"], childViewContainer: ".js-widgets", childView: AlbumListChildView, }), StatsView = Marionette.View.extend({ template: JST["stats/view"] }), TimingView = Marionette.View.extend({ template: JST["nowplaying/timingview"], tagName: 'span', className: 'typewriter time-area', currentTime: "0:00", initialize: function () { var self = this; var timer = function () { var p = App.sound.seek(); self.currentTime = self.model.formatTime(p); self.render(); }; this.currentTimeTracker = setInterval( function () { timer(); }, 1000 ); }, templateContext: function () { return { currentTime: this.currentTime, }; }, }), NowPlayingView = Marionette.View.extend({ template: JST["nowplaying/view"], regions: { timeRegion: { el: '.time-area', replaceElement: true } }, events: { "click .stop-icon": function () { App.sound.stop(); this.$('button').removeClass('active'); this.$('button.stop-icon').addClass('active'); }, "click .pause-icon": function () { App.sound.pause(); this.$('button').removeClass('active'); this.$('button.pause-icon').addClass('active'); }, "click .play-icon": function () { App.sound.play(); this.$('button').removeClass('active'); this.$('button.play-icon').addClass('active'); }, "click .forward-icon": function () { App.playNext(); }, "click .info-icon": function () { App.router.navigate("track/" + this.model.get("id"), { trigger: true }); } }, onRender: function () { this.showChildView("timeRegion", new TimingView({ model: this.model })); } }), TrackListChildView = Marionette.View.extend({ tagName: "li", className: "list-group-item", template: JST["item/view"], events: { "click .play-button": function () { App.playTrack(this.model); }, "click .add-button": function () { App.queue.push(this.model); }, "click .info-button": function () { App.router.navigate("track/" + this.model.get("id"), { trigger: true }); }, } }), TrackListView = Marionette.CollectionView.extend({ template: JST["item/listview"], childViewContainer: ".js-widgets", childView: TrackListChildView }), AlbumDetailView = Marionette.View.extend({ template: JST["album/detailview"], regions: { "tracksRegion": "#tracks-region" }, onRender: function () { var tracks = new Items(); tracks.add(this.model.get("items")); this.showChildView("tracksRegion", new TrackListView({ collection: tracks })); }, }), ArtistListChildView = Marionette.View.extend({ tagName: "li", className: "list-group-item", template: JST["artist/view"] }), ArtistListView = Marionette.CollectionView.extend({ template: JST["artist/listview"], childViewContainer: ".js-widgets", childView: ArtistListChildView }), AppView = Marionette.View.extend({ template: JST["app/view"], className: "container-fluid m0 p0", regions: { "sidebar": "#sidebar", "nowPlaying": "#nowPlaying", "mainview": "#main" }, initialize: function () { this.listenTo(Backbone, "show:queue", this.showQueueView); this.listenTo(Backbone, "show:search", this.showSearchView); this.listenTo(Backbone, "show:albums", this.showAlbumListView); this.listenTo(Backbone, "show:stats", this.showStatsView); this.listenTo(Backbone, "show:track", this.showTrackView); this.listenTo(Backbone, "show:album", this.showAlbumDetailView); this.listenTo(Backbone, "player:play", this.showNowPlayingView); this.listenTo(Backbone, "show:artists", this.showArtistListView); }, onRender: function () { this.showChildView("sidebar", new SidebarView()); }, showQueueView: function () { this.showChildView("mainview", new QueueView({ collection: App.queue })); }, showSearchView: function () { this.showChildView("mainview", new SearchView()); }, showAlbumListView: function () { var self = this; App.albums.fetch({ success: function () { self.showChildView("mainview", new AlbumListView({ collection: App.albums })); } }); }, showStatsView: function () { var self = this; App.stats.fetch({ success: function () { self.showChildView("mainview", new StatsView({ model: App.stats })); }, }); }, showNowPlayingView: function (model) { this.showChildView("nowPlaying", new NowPlayingView({ model: model })); }, showTrackView: function (id) { var item = new Item({ id: id }); var self = this; item.fetch({ success: function () { self.showChildView("mainview", new ItemDetailView({ model: item })); } }); }, showAlbumDetailView: function (id) { var album = new Album({ id: id }); album.url = "/album/" + id + "?expand=1"; var self = this; album.fetch({ success: function () { self.showChildView("mainview", new AlbumDetailView({ model: album })); } }); }, showArtistListView: function () { var self = this; App.artists.fetch({ success: function () { self.showChildView("mainview", new ArtistListView({ collection: App.artists })); } }); } }), // Routers Router = Backbone.Router.extend({ routes: { "": "default", "queue": "doQueue", "search": "doSearch", "albums": "doAlbums", "album/:id": "doAlbum", "track/:id": "doTrack", "stats": "doStats", "artists": "doArtists", }, default: function () { this.navigate("search", { trigger: true }); }, doQueue: function () { Backbone.trigger("show:queue"); }, doSearch: function () { Backbone.trigger("show:search"); }, doAlbums: function () { Backbone.trigger("show:albums"); }, doStats: function () { Backbone.trigger("show:stats"); }, doTrack: function (id) { Backbone.trigger("show:track", id); }, doAlbum: function (id) { Backbone.trigger("show:album", id); }, doArtists: function () { Backbone.trigger("show:artists"); }, }), // App Container App = { // Other Objects sound: new Howl({ src: [""], format: ["mp3"] }), queue: new Queue(), albums: new Albums(), stats: new Stats(), artists: new Artists(), appView: new AppView({ el: "#app" }), router: new Router(), start: function () { this.appView.render(); Backbone.history.start(); }, playTrack: function (model) { if (model) { this.sound.stop(); this.sound = new Howl({ src: [model.getFileUrl()], format: [model.get("format").toLowerCase()], }); Backbone.trigger("player:play", model); this.sound.play(); this.sound.on("end", function () { App.playTrack(App.queue.shift()); }); } }, playNext: function () { this.playTrack(this.queue.shift()); } }; $(function () { App.start(); }); }());
ddbed62a757aeb37af6881450138ec421e91947c
[ "JavaScript" ]
1
JavaScript
eidoom/beets
9c45e281d2122ca711af1e63358c6c7daae4ecaa
d0cb3a039d661d77be3e67e531658c1309dbc434
refs/heads/master
<repo_name>jasoncd/sphinx-small<file_sep>/README.md # sphinx-small For Linux / Rasbian Platform: ## To compile: cd src ./mk cd ../test ./mk ## To test speech to text: In one command line window - cd test ./run-sphinx In another command line window - cd test , use a USB mic: ./vad.exe speak to mic, see results in audio.txt ## To test keyword spotting: In one command line window - cd test ./run-sphinx-kws In another command line window - cd test , use a USB mic: ./vad.exe speak anything plus keywords (e.g. defined in trigger.jsgf) to mic, see results in audio.txt <file_sep>/src/profile.c /* * profile.c -- For timing and event counting. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> # include <unistd.h> # include <sys/time.h> # include <sys/resource.h> #include "sphinxbase/profile.h" #include "sphinxbase/err.h" #include "sphinxbase/ckd_alloc.h" pctr_t * pctr_new(char *nm) { pctr_t *pc; pc = ckd_calloc(1, sizeof(pctr_t)); pc->name = ckd_salloc(nm); pc->count = 0; return pc; } void pctr_reset(pctr_t * ctr) { ctr->count = 0; } void pctr_increment(pctr_t * ctr, int32 inc) { ctr->count += inc; /* E_INFO("Name %s, Count %d, inc %d\n",ctr->name, ctr->count, inc); */ } void pctr_print(FILE * fp, pctr_t * ctr) { fprintf(fp, "CTR:"); fprintf(fp, "[%d %s]", ctr->count, ctr->name); } void pctr_free(pctr_t * pc) { if (pc) { if (pc->name) ckd_free(pc->name); } ckd_free(pc); } static float64 make_sec(struct timeval *s) { return (s->tv_sec + s->tv_usec * 0.000001); } void ptmr_start(ptmr_t * tm) { #if (! defined(_WIN32)) || defined(GNUWINCE) || defined(__SYMBIAN32__) struct timeval e_start; /* Elapsed time */ #if (! defined(_HPUX_SOURCE)) && (! defined(__SYMBIAN32__)) struct rusage start; /* CPU time */ /* Unix but not HPUX */ getrusage(RUSAGE_SELF, &start); tm->start_cpu = make_sec(&start.ru_utime) + make_sec(&start.ru_stime); #endif /* Unix + HP */ gettimeofday(&e_start, 0); tm->start_elapsed = make_sec(&e_start); #elif defined(_WIN32_WP) tm->start_cpu = GetTickCount64() / 1000; tm->start_elapsed = GetTickCount64() / 1000; #elif defined(_WIN32_WCE) /* No GetProcessTimes() on WinCE. (Note CPU time will be bogus) */ tm->start_cpu = GetTickCount() / 1000; tm->start_elapsed = GetTickCount() / 1000; #else HANDLE pid; FILETIME t_create, t_exit, kst, ust; /* PC */ pid = GetCurrentProcess(); GetProcessTimes(pid, &t_create, &t_exit, &kst, &ust); tm->start_cpu = make_sec(&ust) + make_sec(&kst); tm->start_elapsed = (float64) clock() / CLOCKS_PER_SEC; #endif } void ptmr_stop(ptmr_t * tm) { float64 dt_cpu, dt_elapsed; #if (! defined(_WIN32)) || defined(GNUWINCE) || defined(__SYMBIAN32__) struct timeval e_stop; /* Elapsed time */ #if (! defined(_HPUX_SOURCE)) && (! defined(__SYMBIAN32__)) struct rusage stop; /* CPU time */ /* Unix but not HPUX */ getrusage(RUSAGE_SELF, &stop); dt_cpu = make_sec(&stop.ru_utime) + make_sec(&stop.ru_stime) - tm->start_cpu; #else dt_cpu = 0.0; #endif /* Unix + HP */ gettimeofday(&e_stop, 0); dt_elapsed = (make_sec(&e_stop) - tm->start_elapsed); #elif defined(_WIN32_WP) dt_cpu = GetTickCount64() / 1000 - tm->start_cpu; dt_elapsed = GetTickCount64() / 1000 - tm->start_elapsed; #elif defined(_WIN32_WCE) /* No GetProcessTimes() on WinCE. (Note CPU time will be bogus) */ dt_cpu = GetTickCount() / 1000 - tm->start_cpu; dt_elapsed = GetTickCount() / 1000 - tm->start_elapsed; #else HANDLE pid; FILETIME t_create, t_exit, kst, ust; /* PC */ pid = GetCurrentProcess(); GetProcessTimes(pid, &t_create, &t_exit, &kst, &ust); dt_cpu = make_sec(&ust) + make_sec(&kst) - tm->start_cpu; dt_elapsed = ((float64) clock() / CLOCKS_PER_SEC) - tm->start_elapsed; #endif tm->t_cpu += dt_cpu; tm->t_elapsed += dt_elapsed; tm->t_tot_cpu += dt_cpu; tm->t_tot_elapsed += dt_elapsed; } void ptmr_reset(ptmr_t * tm) { tm->t_cpu = 0.0; tm->t_elapsed = 0.0; } void ptmr_init(ptmr_t * tm) { tm->t_cpu = 0.0; tm->t_elapsed = 0.0; tm->t_tot_cpu = 0.0; tm->t_tot_elapsed = 0.0; } void ptmr_reset_all(ptmr_t * tm) { for (; tm->name; tm++) ptmr_reset(tm); } void ptmr_print_all(FILE * fp, ptmr_t * tm, float64 norm) { if (norm != 0.0) { norm = 1.0 / norm; for (; tm->name; tm++) fprintf(fp, " %6.2fx %s", tm->t_cpu * norm, tm->name); } } int32 host_endian(void) { FILE *fp; int32 BYTE_ORDER_MAGIC; char *file; char buf[8]; int32 k, endian; file = "/tmp/__EnDiAn_TeSt__"; if ((fp = fopen(file, "wb")) == NULL) { E_ERROR("Failed to open file '%s' for writing", file); return -1; } BYTE_ORDER_MAGIC = (int32) 0x11223344; k = (int32) BYTE_ORDER_MAGIC; if (fwrite(&k, sizeof(int32), 1, fp) != 1) { E_ERROR("Failed to write to file '%s'\n", file); fclose(fp); unlink(file); return -1; } fclose(fp); if ((fp = fopen(file, "rb")) == NULL) { E_ERROR_SYSTEM("Failed to open file '%s' for reading", file); unlink(file); return -1; } if (fread(buf, 1, sizeof(int32), fp) != sizeof(int32)) { E_ERROR("Failed to read from file '%s'\n", file); fclose(fp); unlink(file); return -1; } fclose(fp); unlink(file); /* If buf[0] == lsB of BYTE_ORDER_MAGIC, we are little-endian */ endian = (buf[0] == (BYTE_ORDER_MAGIC & 0x000000ff)) ? 1 : 0; return (endian); } <file_sep>/src/include/sphinxbase/filename.h #define _LIBUTIL_FILENAME_H_ /** * Returns the last part of the path, without modifying anything in memory. */ const char *path2basename(const char *path); /** * Strip off filename from the given path and copy the directory name into dir * Caller must have allocated dir (hint: it's always shorter than path). */ void path2dirname(const char *path, char *dir); /** * Strip off the smallest trailing file-extension suffix and copy * the rest into the given root argument. Caller must have * allocated root. */ void strip_fileext(const char *file, char *root); /** * Test whether a pathname is absolute for the current OS. */ int path_is_absolute(const char *file); <file_sep>/src/mdef_convert.c /** * mdef_convert.c - convert text to binary model definition files (and vice versa) * * Author: <NAME> <<EMAIL>> **/ #include <stdio.h> #include <string.h> #include <pocketsphinx.h> #include "bin_mdef.h" int main(int argc, char *argv[]) { const char *infile, *outfile; bin_mdef_t *bin; int tobin = 1; if (argc < 3 || argc > 4) { fprintf(stderr, "Usage: %s [-text | -bin] INPUT OUTPUT\n", argv[0]); return 1; } if (argv[1][0] == '-') { if (strcmp(argv[1], "-text") == 0) { tobin = 0; ++argv; } else if (strcmp(argv[1], "-bin") == 0) { tobin = 1; ++argv; } else { fprintf(stderr, "Unknown argument %s\n", argv[1]); fprintf(stderr, "Usage: %s [-text | -bin] INPUT OUTPUT\n", argv[0]); return 1; } } infile = argv[1]; outfile = argv[2]; if (tobin) { if ((bin = bin_mdef_read_text(NULL, infile)) == NULL) { fprintf(stderr, "Failed to read text mdef from %s\n", infile); return 1; } if (bin_mdef_write(bin, outfile) < 0) { fprintf(stderr, "Failed to write binary mdef to %s\n", outfile); return 1; } } else { if ((bin = bin_mdef_read(NULL, infile)) == NULL) { fprintf(stderr, "Failed to read binary mdef from %s\n", infile); return 1; } if (bin_mdef_write_text(bin, outfile) < 0) { fprintf(stderr, "Failed to write text mdef to %s\n", outfile); return 1; } } return 0; } <file_sep>/src/filename.c /* * filename.c -- File and path name operations. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "sphinxbase/filename.h" const char * path2basename(const char *path) { const char *result; result = strrchr(path, '/'); return (result == NULL ? path : result + 1); } /* Return all leading pathname components */ void path2dirname(const char *path, char *dir) { size_t i, l; l = strlen(path); for (i = l - 1; (i > 0) && !(path[i] == '/'); --i); if (i == 0) { dir[0] = '.'; dir[1] = '\0'; } else { memcpy(dir, path, i); dir[i] = '\0'; } } /* Strip off the shortest trailing .xyz suffix */ void strip_fileext(const char *path, char *root) { size_t i, l; l = strlen(path); for (i = l - 1; (i > 0) && (path[i] != '.'); --i); if (i == 0) { strcpy(root, path); /* Didn't find a . */ } else { strncpy(root, path, i); } } /* Test if this path is absolute. */ int path_is_absolute(const char *path) { return path[0] == '/'; } <file_sep>/test/vad.c #include <alsa/asoundlib.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <unistd.h> short myabs(short v) { if(v<0) return -1*v; else return v; } void write_wave_header(FILE* outf, int len) { int bytes = 2*len; int file_size = 2*len+36; int data_header_length = 16; short format_type = 1; short number_of_channels = 1; int sample_rate = 16000; int bytes_per_second = 32000; short bytes_per_frame = 2; short bits_per_sample = 16; fwrite("RIFF", 4, sizeof(char), outf); fwrite(&file_size, 4, sizeof(char), outf); fwrite("WAVE", 4, sizeof(char), outf); fwrite("fmt ", 4, sizeof(char), outf); fwrite(&data_header_length, 4, sizeof(char), outf); fwrite(&format_type, 2, sizeof(char), outf); fwrite(&number_of_channels, 2, sizeof(char), outf); fwrite(&sample_rate, 4, sizeof(char), outf); fwrite(&bytes_per_second, 4, sizeof(char), outf); fwrite(&bytes_per_frame, 2, sizeof(char), outf); fwrite(&bits_per_sample, 2, sizeof(char), outf); fwrite("data", 4, sizeof(char), outf); fwrite(&bytes, 4, sizeof(char), outf); } void save_wave(char* dir, short* utt, int uttlen, int cnt, char *uttid) { FILE* outf; char filename[128]; if(cnt<10) { sprintf(filename, "%s/recording-000%i.wav", dir, cnt); sprintf(uttid, "recording-000%i", cnt); } else if(cnt<100) { sprintf(filename, "%s/recording-00%i.wav", dir, cnt); sprintf(uttid, "recording-00%i", cnt); } else if(cnt<1000) { sprintf(filename, "%s/recording-0%i.wav", dir, cnt); sprintf(uttid, "recording-0%i", cnt); } else { sprintf(filename, "%s/recording-%i.wav", dir, cnt); sprintf(uttid, "recording-%i", cnt); } outf = fopen(filename, "wb"); write_wave_header(outf, uttlen); fwrite(utt, uttlen, sizeof(short), outf); fclose(outf); } int vad(short *utt) { int err; int size; snd_pcm_t *handle; snd_pcm_hw_params_t *params; unsigned int sampleRate = 16000; int dir; snd_pcm_uframes_t frames = 320; const char *device = "plughw:1,0"; // USB microphone //const char *device = "default"; // Integrated system microphone //char *buffer; short buffer[320]; // vad vars float HiLoRate = 10.0; // rate for voicing // end silence length (default 40 frames, 1 frame = 160 samples) int esl = 40; // average, lo, floor and hi values of each 320 samples of up to 40 sec. short avg; float floor; // global sil floor short lo; // local lo of every second short hi; // hi to floor ratio float r; // end of sentence cnt int ecnt = 0; // beginning of sentence cnt //int bcnt = 0; // voice cnt int vcnt = 0; // high energy voice counter int hvcnt = 0; // voice state int vs = 0; // frame (320 samples) counter int fcnt = 0; // utt index int idx = 0; union abc { char c[2]; short s; } u; int i,j,k,sum; /* Open PCM device for recording (capture). */ err = snd_pcm_open(&handle, device, SND_PCM_STREAM_CAPTURE, 0); if (err) { fprintf(stderr, "Unable to open PCM device: %s\n", snd_strerror(err)); return err; } /* Allocate a hardware parameters object. */ snd_pcm_hw_params_alloca(&params); /* Fill it in with default values. */ snd_pcm_hw_params_any(handle, params); /* ### Set the desired hardware parameters. ### */ /* Interleaved mode */ err = snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED); if (err) { fprintf(stderr, "Error setting interleaved mode: %s\n", snd_strerror(err)); snd_pcm_close(handle); return err; } /* Signed 16-bit little-endian format */ err = snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE); if (err) { fprintf(stderr, "Error setting format: %s\n", snd_strerror(err)); snd_pcm_close(handle); return err; } /* mono channel */ err = snd_pcm_hw_params_set_channels(handle, params, 1); if (err) { fprintf(stderr, "Error setting channels: %s\n", snd_strerror(err)); snd_pcm_close(handle); return err; } /* 16000 bits/second sampling rate */ err = snd_pcm_hw_params_set_rate_near(handle, params, &sampleRate, &dir); if (err) { fprintf(stderr, "Error setting sampling rate (%d): %s\n", sampleRate, snd_strerror(err)); snd_pcm_close(handle); return err; } /* Set period size*/ err = snd_pcm_hw_params_set_period_size_near(handle, params, &frames, &dir); if (err) { fprintf(stderr, "Error setting period size: %s\n", snd_strerror(err)); snd_pcm_close(handle); return err; } /* Write the parameters to the driver */ err = snd_pcm_hw_params(handle, params); if (err < 0) { fprintf(stderr, "Unable to set HW parameters: %s\n", snd_strerror(err)); snd_pcm_close(handle); return err; } /* Use a buffer large enough to hold one period */ err = snd_pcm_hw_params_get_period_size(params, &frames, &dir); if (err) { fprintf(stderr, "Error retrieving period size: %s\n", snd_strerror(err)); snd_pcm_close(handle); return err; } //size = frames * 2 * 1; /* 2 bytes/sample, 1 channel */ err = snd_pcm_hw_params_get_period_time(params, &sampleRate, &dir); if (err) { fprintf(stderr, "Error retrieving period time: %s\n", snd_strerror(err)); snd_pcm_close(handle); //free(buffer); return err; } // stabalize mic static int run_cnt = 0; if(run_cnt == 0) { for(i=0; i<30; i++) snd_pcm_readi(handle, buffer, frames); run_cnt = 1; } // init floor by 5 buffers sum = 0; int byteread; for(i=0; i<5; i++) { byteread = snd_pcm_readi(handle, buffer, frames); //printf("byteread: %i\n", byteread); for(j=0; j<320; j++) { sum += myabs(buffer[j]); //printf("%i ",buffer[j]); } //printf("\n\n"); memcpy(&(utt[idx]),buffer,320*sizeof(short)); idx+=320; } floor = (sum/(5*320.0)); printf("noise floor: %.3f\n", floor); // the loop to capture one utt lo = 32000; hi = 0; for(;;) { sum = 0; hi = 0; snd_pcm_readi(handle, buffer, frames); for(i=0; i<320; i++) { if(buffer[i] > hi) hi = buffer[i]; sum += myabs(buffer[i]); } avg = (short) (sum/320.0); if(avg < lo) lo = avg; // capture local lo's if((fcnt % 40) == 0) // update floor each 0.5 second { floor = (0.6*floor) + (0.4*lo); lo = 32000; } fcnt++; r = hi / floor; //printf("hi: %i, floor: %.3f, rate: %.3f\n", hi, floor, r); // utt begin if(r > 10 && vs == 0) { vs = 1; vcnt ++; memcpy(&(utt[idx]),buffer,320*sizeof(short)); idx+=320; } else if(r > 10 && vs == 1) { ecnt = 0; vcnt ++; memcpy(&(utt[idx]),buffer,320*sizeof(short)); idx+=320; } else if(vs == 1 && r <= 10 && ecnt < 20) { ecnt ++; memcpy(&(utt[idx]),buffer,320*sizeof(short)); idx+=320; } else if(vs == 1 && ecnt == 20) { break; } if(r > 30) hvcnt ++; if(idx>160000) break; } snd_pcm_drain(handle); snd_pcm_close(handle); //if(hvcnt > 15) if(hvcnt > 0) return idx; else return -1; } int main(int argc, char** argv) { int utt_len; int uttcnt = 0; char uttid[100]; FILE* namefile; short utt[1000000]; while(1) { utt_len = vad(utt); if(utt_len > 9600) // 0.3 sec { uttcnt++; printf("Voice captured %.2f sec.\n", utt_len/16000.0 ); save_wave("audio/", utt, utt_len, uttcnt, uttid); namefile = fopen("tt","w"); printf("uttid: %s\n", uttid); fprintf(namefile,"%s\n", uttid); fclose(namefile); system("mv tt namefile.txt"); } } return 0; }
1dacb262c86023ef6311869c3f4587457bf9c89a
[ "Markdown", "C" ]
6
Markdown
jasoncd/sphinx-small
29ee3341f9b28cbf2e14e680aca22053edac18d9
c341236177232363c3157bf6d0b974924474e8ac
refs/heads/master
<file_sep>(function($) { $.fn.tagInput = function(options) { var opt = $.extend({ cls: "tag_input" }, options); var dragObj = null; var dragObjStartPoint = null; var src = this; var cls = opt.cls; var value = src.val(); src.addClass("hidden"); var editor = $("<div/>", { "class": cls, click: function() { $("." + cls + " input").focus(); } }); var tokens = $("<div/>", { "class": "tokens" }).appendTo(editor); var wrap = $("<div/>", { "class": "wrap" }); var input = $("<input/>", { type: "text", blur: function() { insertTag($(this).val()); updateSource(); }, keydown: function(event) { if ((event.keyCode == 8) && !$(this).val()) { var tags = $("." + cls + " .token"); if (tags && tags.length && tags[tags.length - 1]) { removeTag($(tags[tags.length - 1])); } } } }).appendTo(wrap); wrap.appendTo(editor); src.after(editor); function updateSource() { var val = ""; $("." + cls + " .tag").each(function(index, obj) { val += (val ? "," : "") + $(obj).text(); }); src.val(val); } function removeTag(tag) { tag.remove(); updateSource(); } function insertTag(name) { name = name.replace(/[",#]/g, '').replace(/</g, "&lt;"); if (name.replace(/,/g, '')) { input.val(""); var token = $("<div/>", { "class": "token label", mousedown: function(event) { event.preventDefault(); dragObj = $(this); dragObj.css({ position: "relative", left: 0, cursor: "move" }); dragObj.addClass("draggable"); dragObjStartPoint = {x: event.pageX, y: event.pageY}; } }); $("<span/>", { "class": "tag", text: name }).appendTo(token); $("<span/>", { title: "Remove", "class": "close", text: "x", click: function() { removeTag($(this).parent()); } }).appendTo(token); token.appendTo(tokens); } } function checkUserInput() { var val = input.val(); if ((val != '"' && val.match(',')) || (val == '"' && val.substr( - 2) == '",')) { insertTag(val.replace(/(",$)|(,$)/, '').replace('"', '')); updateSource(); } } var tags = []; var match; while (match = value.match(/"(.*?)"/m)) { value = value.replace(match[0], ''); tags[tags.length] = match[1] } $.each(value.split(','), function(index, value) { value = value.replace(/^\s+|\s+$/g, ""); if (value) { tags[tags.length] = value; } }); $.each(tags, function(index, value) { insertTag(value); }); var timer = setInterval(checkUserInput, 100); $(document).mouseup(function() { if (dragObj != null) { dragObj.removeClass("draggable"); dragObj.css({ position: "static", left: 0, cursor: "default" }); } dragObj = null; dragObjStartPoint = null; }); $(document).mousemove(function(event) { var update = false; if ((dragObj != null) && (dragObjStartPoint != null)) { var target = null; var delta = event.pageX - dragObjStartPoint.x; if (delta > 0) { target = dragObj.next(); } else { target = dragObj.prev(); } if (target != null) { dragObj.css({ left: delta }); var threshold = target.width() / 2; if (delta > threshold) { target.after(dragObj); update = true; } else if (delta < -1 * threshold) { target.before(dragObj); update = true; } if (update) { $(document).mouseup(); updateSource(); } } } }); }; })(jQuery);
04c3f7fc301a0f4abd680a3d9a68272706d65cdd
[ "JavaScript" ]
1
JavaScript
rodiontsev/jquery-taginput
30c17bf039e1a82984808163271959ffbb7e1500
e71f7cfb04608f0326566c1c571885c1d60614d4
refs/heads/master
<repo_name>burakyildiz07/discountCalculator<file_sep>/index.php <?php require_once 'DiscountCalculator.php'; $items =" [ {\"title\":\"Deneme Urun 1\",\"price\":47.2,\"count\":1,\"is_outlet\":true}, {\"title\":\"Deneme Urun 2\",\"price\":7.3,\"count\":3,\"is_outlet\":true}, {\"title\":\"Deneme Urun 3\",\"price\":234.63,\"count\":1,\"is_outlet\":false}, {\"title\":\"Deneme Urun 4\",\"price\":14.1,\"count\":1,\"is_outlet\":false}, {\"title\":\"Deneme Urun 5\",\"price\":54.3,\"count\":5,\"is_outlet\":false}, {\"title\":\"Deneme Urun 6\",\"price\":4.89,\"count\":2,\"is_outlet\":false}, {\"title\":\"Deneme Urun 7\",\"price\":48.4,\"count\":1,\"is_outlet\":false}, {\"title\":\"Deneme Urun 8\",\"price\":782.2,\"count\":1,\"is_outlet\":true}, {\"title\":\"Deneme Urun 9\",\"price\":15.5,\"count\":1,\"is_outlet\":true}, {\"title\":\"Deneme Urun 10\",\"price\":17.2,\"count\":4,\"is_outlet\":false}, {\"title\":\"Deneme Urun 11\",\"price\":73.5,\"count\":5,\"is_outlet\":false}, {\"title\":\"Deneme Urun 12\",\"price\":43.2,\"count\":2,\"is_outlet\":false}, {\"title\":\"Deneme Urun 13\",\"price\":29.75,\"count\":1,\"is_outlet\":false}, {\"title\":\"Deneme Urun 14\",\"price\":47.2,\"count\":3,\"is_outlet\":false}, {\"title\":\"Deneme Urun 15\",\"price\":17.25,\"count\":1,\"is_outlet\":true}, {\"title\":\"Deneme Urun 16\",\"price\":46.2,\"count\":1,\"is_outlet\":false}, {\"title\":\"Deneme Urun 17\",\"price\":23.4,\"count\":1,\"is_outlet\":true}, {\"title\":\"Deneme Urun 18\",\"price\":57.2,\"count\":1,\"is_outlet\":false}, {\"title\":\"Deneme Urun 19\",\"price\":43.2,\"count\":1,\"is_outlet\":false} ]"; $discount = new DiscountCalculator(); echo $discount->discountCalulator($items); <file_sep>/DiscountCalculator.php <?php class DiscountCalculator{ public function discountCalulator($json=""){ $items = json_decode($json); $notOutlet=array(); $notOutletItemPrice=array(); $discountPercent=0; $discount=0; $itemCount=0; $freeItem=0; $discountItem=0; $totalPrice=0; $notOutletTotalPrice=0; foreach ($items as $item) { if(!$item->is_outlet){ //Not Outlet Items for($k=0;$k < $item->count;$k++){ $itemCount++; if($itemCount%3 == 0){ $discountPercent += 10; if($discountPercent>=100){ $freeItem++; }else{ // Discount Percent < 100 $discountItem++; } } } $notOutlet[] = $item; $notOutletItemPrice[] =$item->price; $notOutletTotalPrice +=$item->price; } $totalPrice +=$item->price; } // Not Outlet Item Asc Sorting sort($notOutletItemPrice); for ($i=0;$i < $freeItem;$i++){ $discount += $notOutletItemPrice[$i]; // Free Item Add Discount } $k=$discountItem; for ($i=$freeItem;$i < $discountItem; $i++){ if($k!=0){ $discount += $notOutletItemPrice[$i] *(10*$k) / 100; $k = $k-1; } } return $discount; } }
3e761e4b905bb6dd580323c4438c4c3866f00109
[ "PHP" ]
2
PHP
burakyildiz07/discountCalculator
972f3822f7c68c1d76dc61c84a97cc80710a1eed
534be7541f27fb5b0ff23eaa15a855374084eac9
refs/heads/main
<repo_name>darranhayes/bayesian-forecasting<file_sep>/BC/Program.cs using ProbCSharp; using System; using System.Linq; using static ProbCSharp.ProbBase; namespace BC { class Program { static Func<bool, Dist<bool>> EuVetosExtensionRequest = isBorisInPower => from franceVetos in isBorisInPower ? Bernoulli(0.8) : Bernoulli(0.20) from germanyVetos in Bernoulli(0.01) from italyVetos in Bernoulli(0.1) from otherVetos in Bernoulli(0.01) select franceVetos || germanyVetos || italyVetos || otherVetos; static void Main(string[] args) { var willWeExtend = from johnsonInPower in Bernoulli(0.7) from askForExtension in johnsonInPower ? Bernoulli(0.2) : Bernoulli(0.95) from euExercisesVeto in EuVetosExtensionRequest(johnsonInPower) select askForExtension ? !euExercisesVeto : false; var samples = willWeExtend.SampleN(10000); var extending = samples.Count(x => x) / (double)samples.Count(); Console.WriteLine($"Probably of extending beyond deadline: {extending.ToString("##0%")}"); Console.ReadLine(); } } }
8c977be5e8c1b1e20c97b47f5916e9589e9403f5
[ "C#" ]
1
C#
darranhayes/bayesian-forecasting
49fd366e7c02b1f50789c56c4d3038e73dfff420
e2ca39421e1309160c30c0a168a5aa3354c43034
refs/heads/main
<repo_name>Tadeo25/ListaDeTareas-3-A<file_sep>/src/components/ItemTarea.js import React from 'react' import ListGroup from "react-bootstrap/ListGroup"; export default function ItemTarea(props) { return ( <div> <ListGroup.Item>{props.nombreTarea}</ListGroup.Item> </div> ) } <file_sep>/src/App.js import "bootstrap/dist/css/bootstrap.min.css"; import "./App.css"; import Titulo from "./components/Titulo"; import Subtitulo from "./components/Subtitulo"; import Header from "./components/Header"; import Formtarea from "./components/Formtarea"; function App() { return ( <> <Header logo="https://rollingcodeschool.com/wp-content/uploads/2019/12/ingenia-logo-transparencia_Mesa-de-trabajo-1-copia-e1575648427572.png" /> <Titulo emoji="📒" /> <Subtitulo comision="3A" /> <Formtarea/> </> ); } export default App; <file_sep>/src/components/Titulo.js import React from "react"; export default function Titulo(props) { return ( <> <h1 className="text-center display-2 text-dark"> Lista de Tareas {props.emoji} </h1> </> ); } <file_sep>/src/components/Lista.js import React from "react"; import ListGroup from "react-bootstrap/ListGroup"; import ItemTarea from "./ItemTarea"; export default function Lista(props) { return ( <> <ListGroup> { props.listaTareas.map((dato, indice)=> <ItemTarea nombreTarea={dato}></ItemTarea>) } </ListGroup> </> ); }
b35146c8e080ecb78f93d2725551c430719a5e58
[ "JavaScript" ]
4
JavaScript
Tadeo25/ListaDeTareas-3-A
831df792f97f31752c56060e0ba2b2b70bdf8cf2
cd1eb89621ec573f0e9e1749711ff7ba9c4fd174
refs/heads/master
<file_sep>/* This javascript validate whether user is logged in or not. If user is not logged in then it will open the login page else continue with current page to load. */ var is_logged_in = sessionStorage.getItem("is_logged_in"); if(is_logged_in==null || is_logged_in==false){ location.href="index.html"; }<file_sep>var database = openDatabase("lmsdb","1.0","This Database stores application data",3*1024*1024); if(database!=null){ /* Creating require Database table */ database.transaction(function(tx){ tx.executeSql("CREATE TABLE STUDENT (id unique,name,father_name,email,gender,dob,tel_no,course)"); }); } function save_student(){ var rollno = document.getElementById("rollno").value; var name=document.getElementById("sname").value; var fname = document.getElementById("fname").value; var email = document.getElementById("email").value; var dob = document.getElementById("dob").value; var tel = document.getElementById("telephone").value; var course =document.getElementById("course").value; var gender = document.getElementsByName("gender"); var selected_gender = ''; /* Looping through all gender element to verify Checked gender value */ for (let index = 0; index < gender.length; index++) { const element = gender[index]; if(element.checked){ selected_gender = element.value; } } if (rollno==null || rollno==undefined || rollno.trim().length==0) { alert("Please enter enrollment number"); document.getElementById("rollno").focus(); return false; } if (name==null || name==undefined || name.trim().length==0) { alert("Please enter Student name"); document.getElementById("sname").focus(); return false; } if (fname==null || fname==undefined || fname.trim().length==0) { alert("Please enter Father name"); document.getElementById("fname").focus(); return false; } if (email==null || email==undefined || email.trim().length==0) { alert("Please enter Student email"); document.getElementById("email").focus(); return false; } if (dob==null || dob==undefined || dob.trim().length==0) { alert("Please enter Student Date of Birth"); document.getElementById("dob").focus(); return false; } if (tel==null || tel==undefined || tel.trim().length==0) { alert("Please enter Student telephone number"); document.getElementById("tel").focus(); return false; } if (course==null || course==undefined || course.trim().length==0) { alert("Please select Student enrolled course"); document.getElementById("course").focus(); return false; } if (selected_gender==null || selected_gender==undefined || selected_gender.trim().length==0){ alert("Please select Gender"); return false; } if(database!=null){ database.transaction(function(tx){ tx.executeSql("INSERT INTO STUDENT (id,name,father_name,gender,email,dob,tel_no,course) VALUES(?,?,?,?,?,?,?,?)", [rollno,name,fname,selected_gender,email,dob,tel,course]); alert("Hurray!! Record saved Successfully."); location.href="students.html"; }); } } function get_student_records(){ if(database!=null){ database.transaction(function(tx){ tx.executeSql("SELECT * FROM STUDENT",[],function(tx,results){ for(i=0;i<results.rows.length;i++){ var record = results.rows.item(i); console.log(record); var table_element = document.getElementById("student_table"); var tr = document.createElement("tr"); /* TD for Roll No */ var td=document.createElement("td"); var textnode = document.createTextNode(record.id); td.appendChild(textnode); tr.appendChild(td); /* TD for name */ var td = document.createElement("td"); var textnode=document.createTextNode(record.name); td.appendChild(textnode); tr.appendChild(td); /* TD for Father name */ var td = document.createElement("td"); var textnode=document.createTextNode(record.father_name); td.appendChild(textnode); tr.appendChild(td); /* TD for Telephone No*/ var td = document.createElement("td"); textnode = document.createTextNode(record.tel_no); td.appendChild(textnode); tr.appendChild(td); /* TD for email */ var td = document.createElement("td"); var textnode=document.createTextNode(record.email); td.appendChild(textnode); tr.appendChild(td); /* TD for gender */ var td = document.createElement("td"); td.className="text_center proper_case_text"; var textnode=document.createTextNode(record.gender); td.appendChild(textnode); tr.appendChild(td); /* TD for course */ var td = document.createElement("td"); td.setAttribute("class","text_center proper_case_text"); var textnode=document.createTextNode(record.course); td.appendChild(textnode); tr.appendChild(td); /* TD for dob */ var td = document.createElement("td"); var textnode=document.createTextNode(record.dob); td.appendChild(textnode); tr.appendChild(td); var td = document.createElement("td"); td.innerHTML="<button id='delete' onclick='delete_student("+record.id+")'>Delete</button>"; tr.appendChild(td); //Appending row into table element table_element.appendChild(tr); } },null); }); } } function delete_student(param) { var c = confirm("Are you sure you want to delete record"+param); if (c==true){ if (database!=null){ database.transaction(function (tx){ tx.executeSql("DELETE FROM STUDENT WHERE id='"+param+"'"); alert("Record Deleted"); window.location.href="students.html"; }) } } }<file_sep>var database = openDatabase("lmsdb","1.0","This Database stores application data",3*1024*1024); if(database!=null){ /* Creating require Database table */ database.transaction(function(tx){ tx.executeSql("CREATE TABLE ISSUE (id,name,book,issue_date,textarea)"); }); } function save_issue(){ var name = document.getElementById("name").value; var book=document.getElementById("book").value; var textarea = document.getElementById("textarea").value; var issue_date = document.getElementById("issue_date").value; if (name==null || name==undefined || name.trim().length==0) { alert("Please select Student name"); document.getElementById("name").focus(); return false; } if (book==null || book==undefined || book.trim().length==0) { alert("Please select book name "); document.getElementById("book").focus(); return false; } if(database!=null){ database.transaction(function(tx){ var id = new Date(); id = id.getTime(); tx.executeSql("INSERT INTO ISSUE (id,name,book,issue_date,textarea) VALUES(?,?,?,?,?)", [id,name,book,issue_date,textarea]); alert("Hurray!! Record saved Successfully."); location.href="book_issue1.html"; }); } } function fetch_student_books(){ if(database != null){ elmstudent = document.getElementById("name"); elmbook = document.getElementById("book"); database.transaction( function(tx){ tx.executeSql("SELECT * FROM STUDENT",[], function(tx,results){ for(i=0;i<results.rows.length;i++){ var record = results.rows.item(i); var elm = document.createElement("OPTION"); elm.value = record.id; elm.innerText= record.name; elmstudent.appendChild(elm); } }); tx.executeSql("SELECT * FROM BOOK",[], function(tx,results){ for(i=0;i<results.rows.length;i++){ var record = results.rows.item(i); var elm = document.createElement("OPTION"); elm.value = record.id; elm.innerText= record.book_title; elmbook.appendChild(elm); } }); } ); } } function get_issue_records(){ if(database!=null){ database.transaction(function(tx){ tx.executeSql("SELECT * FROM ISSUE i, STUDENT S, BOOK B WHERE S.id = i.name and B.id+'' = i.book+''",[],function(tx,results){ for(i=0;i<results.rows.length;i++){ var record = results.rows.item(i); var table_element = document.getElementById("book_issue"); var tr = document.createElement("tr"); /* TD for Remark */ var td = document.createElement("td"); var textnode=document.createTextNode(record.issue_date); td.appendChild(textnode); tr.appendChild(td); /* TD for Name */ var td=document.createElement("td"); var textnode = document.createTextNode(record.name); td.appendChild(textnode); tr.appendChild(td); /* TD for Book */ var td = document.createElement("td"); var textnode=document.createTextNode(record.book_title); td.appendChild(textnode); tr.appendChild(td); /* TD for Remark */ var td = document.createElement("td"); var textnode=document.createTextNode(record.textarea); td.appendChild(textnode); tr.appendChild(td); var td = document.createElement("td"); td.innerHTML="<button id='delete' onclick='delete_student("+record.id+")'>Delete</button>"; tr.appendChild(td); //Appending row into table element table_element.appendChild(tr); } },null); }); } } function delete_student(param) { var c = confirm("Are you sure you want to delete record"); if (c==true){ if (database!=null){ database.transaction(function (tx){ tx.executeSql("DELETE FROM STUDENT WHERE id='"+param+"'"); alert("Record Deleted"); window.location.href="book_issue1.html"; }) } } }<file_sep>function validate_login(){ var username; var password; username = document.getElementById("username").value; password = document.getElementById("password").value; if(username==null || username==undefined || username.trim().length==0){ alert("Please enter your username"); document.getElementById("username").focus(); return false; } if(password==null || password==undefined || password.trim().length==0){ alert("Please enter password"); document.getElementById("password").focus(); return false; } if((username=="admin" && password=="<PASSWORD>")|| (username=="manasvi" && password=="<PASSWORD>")){ localStorage.setItem("logged_user",username); sessionStorage.setItem("is_logged_in",true); return true; } else{ alert("Incorrect Username and password"); return false; } return true; } function logout(){ sessionStorage.setItem("is_logged_in",false); location.href="index.html"; return false; }<file_sep>var database = openDatabase("lmsdb","1.0","This Database stores application data",3*1024*1024); if(database!=null){ database.transaction(function(tx){ tx.executeSql("CREATE TABLE BOOK (id,book_title,author,publication,quantity,description,classification,category)"); }); } function save_book(){ var btitle = document.getElementById("btitle").value; var author=document.getElementById("bauthor").value; var publication = document.getElementById("bpublication").value; var quantity = document.getElementById("bquantity").value; var description = document.getElementById("textarea").value; var classification = document.getElementById("classification").value; var category= document.getElementsByName("category"); for (let index = 0; index < category.length; index++) { const element = category[index]; if(element.checked){ category = element.value; console.log(category); } } if (btitle==null|| btitle==undefined || btitle.trim().length==0){ alert("Please enter book title"); document.getElementById("btitle").focus(); return false; } if (author==null|| author==undefined || author.trim().length==0){ alert("Please enter book author"); document.getElementById("bauthor").focus(); return false; } if (publication==null|| publication==undefined || publication.trim().length==0){ alert("Please enter book publication"); document.getElementById("bpublication").focus(); return false; } if (quantity==null|| quantity==undefined || quantity.trim().length==0){ alert("Please enter quantity"); document.getElementById("bquantity").focus(); return false; } if (classification==null || classification==undefined || classification.trim().length==0) { alert("Please select Book classfication"); document.getElementById("classification").focus(); return false; } if(database!=null){ database.transaction(function(tx){ var id = new Date(); id = id.getTime(); tx.executeSql("INSERT INTO BOOK (id,book_title,author,publication,quantity,description,classification,category) VALUES(?,?,?,?,?,?,?,?)", [id,btitle,author,publication,quantity,description,classification,category]); alert("Hurray!! Record saved Successfully."); location.href="books.html"; }); } } function get_books_records(){ if(database!=null){ database.transaction(function(tx){ tx.executeSql("SELECT * FROM BOOK",[],function(tx,results){ for(i=0;i<results.rows.length;i++){ var record = results.rows.item(i); console.log(record); var table_element = document.getElementById("book_table"); var tr = document.createElement("tr"); /* TD for roll no */ var td=document.createElement("td"); var textnode = document.createTextNode(record.id); td.appendChild(textnode); tr.appendChild(td); /* TD for book title */ var td = document.createElement("td"); var textnode=document.createTextNode(record.book_title); td.appendChild(textnode); tr.appendChild(td); /* TD for author */ var td = document.createElement("td"); var textnode=document.createTextNode(record.author); td.appendChild(textnode); tr.appendChild(td); /* TD for publication*/ var td = document.createElement("td"); textnode = document.createTextNode(record.publication); td.appendChild(textnode); tr.appendChild(td); /* TD for quantity */ var td = document.createElement("td"); td.className="text_center" var textnode=document.createTextNode(record.quantity); td.appendChild(textnode); tr.appendChild(td); /* TD for description */ // var td = document.createElement("td"); //var textnode=document.createTextNode(record.description); //td.appendChild(textnode); //tr.appendChild(td); /* TD for classification*/ var td = document.createElement("td"); //Assigning stylesheet td.className="text_center"; var textnode=document.createTextNode(record.classification); td.appendChild(textnode); tr.appendChild(td); /* TD for category */ var td = document.createElement("td"); td.setAttribute("class","text_center proper_case_text"); var textnode=document.createTextNode(record.category); td.appendChild(textnode); tr.appendChild(td); var td=document.createElement("td"); td.innerHTML="<button id='delete' onclick='delete_book("+record.id+")'>Delete</button>"; tr.appendChild(td); //Appending row into table element table_element.appendChild(tr); } },null); }); } } function delete_book(params){ var c = confirm("Are you sure you want to delete record? "); if (c==true){ if (database!=null){ database.transaction(function (tx){ tx.executeSql("DELETE FROM BOOK WHERE id="+params); alert("Record Deleted"); window.location.href="books.html"; }) } } }
6993527981d307f068471e683b7b6d733c83f5ad
[ "JavaScript" ]
5
JavaScript
manasvipatel20/LMS1_2121009
f68c3f2fda1b115d0b91dd4f41c821f043ddbe0d
bb936e874b92c4e5b1afec037783eafb08be1e69
refs/heads/master
<repo_name>withphonex/telecor<file_sep>/src/rabbit.js import amqp from 'amqp' import log from './logger'; const { RABBIT_HOST, RABBIT_USER, RABBIT_PASSWORD } = process.env; const rabbit = amqp.createConnection({ host: RABBIT_HOST, login: RABBIT_USER, password: <PASSWORD> }); rabbit.on('error', e => log.error(`Error from AMQP on RabbitMQ host: ${RABBIT_HOST}`, e)); export default rabbit; <file_sep>/src/bootstrap.js import mongoose from 'mongoose'; import semver from 'semver'; const { MONGO_URI='', APP_NAME} = process.env; mongoose.Promise = global.Promise; // configure mongodb mongoose.connect(MONGO_URI, { useMongoClient: true }); mongoose.connection.on('open', err => console.log(`${APP_NAME} is now connected to the Mongo Database`)); mongoose.connection.on('error', err => { console.error(`MongoDB error: ${err.message}`); console.error('Make sure a mongoDB server is running and accessible by this application'); process.exit(1); }); export default mongoose; <file_sep>/src/api/controllers/exchange.js import {getRates, convert} from '../services/exchange'; import log from '../../logger' const exchangeRates = async (req, res) => { const rates = await getRates({}); res.json(rates); } const exchangeAirtime = async (req, res) => { const { amount } = req.body; const usd = await convert({to: 'HTG', amount}); res.json(usd) } export default { '/': { get: { action: exchangeRates, level: 'public' }, post: { action: exchangeAirtime, level: 'public' } } }; <file_sep>/README.md # Base Api This is the sample service to use as a starting point for building an API with node.js ## Getting Started 1. Create a `.env` file similar to the `.env.sample` file for RabbitMQ. 2. Run the below commands ```sh $ npm install $ npm start ``` ### Prerequisites - Requires Node version 6.11 or greater installed ## Running the tests ```sh $ npm test # to execute test on file changes $ npm run test:watch ``` ## What does this do ## Deployment In order to leverage the latest language features, we are using Babel to transpile our code to ES5 in order to ensure backwards compatibility with older versions of node.js. ```sh npm run build ``` * On Linux/Unix * Use a process manager to serve up the application. `pm2` or `forever` * On Windows Server * If the application is being run on a windows server, `iismode` is a required dependency that would need to be installed on that machine. Include the `iisnode.yml` and `Web.config` so that IIS can serve the app ## Built With * [node](https://nodejs.org/en/) ## Contributing Send us a pull request on [bitbucket] ## Versioning We use [SemVer](guide/how-tos/versioning.md) for versioning. For the versions available, see the [tags on this repository](https://github.com/your/project/tags). ## Authors * <NAME> <file_sep>/src/api/services/exchange.js import axios from 'axios'; import log from '../../logger'; const { FIXER_API_URL, FIXER_API_KEY } = process.env; const api = axios.create({ baseURL: FIXER_API_URL, timeout: 150000, params: { access_key: FIXER_API_KEY } }); export async function getRates({ from = 'USD', to: currencies='' }) { try { const rates = await api.get('live', { currencies }); return rates.data; } catch (err) { log.error(err); return err; } } export async function convert({from='USD', to, amount}){ try { const rates = await getRates({ from, to }) const rate = rates.quotes[`${from}${to}`]; return amount / rate; } catch(err){ return -1; } } <file_sep>/src/api/index.js import path from 'path'; import express from 'express'; import helmet from 'helmet'; import cors from 'cors'; import morgan from 'morgan'; import bodyParser from 'body-parser'; import endpoints from 'express-list-endpoints'; import correlator from 'express-correlation-id'; import lumie from 'lumie'; import log from '../logger'; const app = express(); app.use(cors()); app.use(helmet()); app.use(correlator()); app.use(morgan('dev', {stream: log.stream})); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // Routes app.get('/', (req, res) => res.json(endpoints(app))) lumie.load(app, { preURL: 'api', verbose: true, ignore: ['*.spec', '*.action'], controllers_path: path.join(__dirname, 'controllers') }); export default app; <file_sep>/src/index.js import fs from 'fs'; import api from './api'; import log from './logger'; // import mongoose from './bootstrap'; const { PORT=3000, APP_NAME='API'} = process.env; api.listen(PORT, () => log.info(`${APP_NAME} is up & running on port: ${PORT}`)); <file_sep>/__test__/utils.spec.js import { multiply } from '../src/api/utils'; describe('Utils', () =>{ describe('multiply():', () => { test('should return 4', () => { var res = multiply(2, 3); expect(res).toEqual(6); }); }); });
7ab37dcbf2b7efd767092cc7505a21006190afc7
[ "JavaScript", "Markdown" ]
8
JavaScript
withphonex/telecor
f0107a642c546049ec78b8270adfe514c4ed43b1
f20b04607991642a19ff3f1992ac133b342b3416
refs/heads/master
<repo_name>AravinthV/notesclone<file_sep>/notes_list_app/migrations/0003_list_title.py # Generated by Django 3.0.7 on 2020-07-11 09:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notes_list_app', '0002_auto_20200710_1605'), ] operations = [ migrations.AddField( model_name='list', name='title', field=models.CharField(default='No Title', max_length=32), ), ] <file_sep>/notes_list_app/templates/welcome.html {% extends 'base.html' %} {% block content %} <h1>Welcome to Notes!</h1> <br/> <h3>Login:</h3> <br/> <form> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="<PASSWORD>" class="form-control" id="exampleInputPassword1"> </div> <a class="btn btn-primary" href="{% url 'home' %}" role="button">Submit</a> </form> {% endblock %}<file_sep>/notes_list_app/migrations/0006_auto_20200711_1737.py # Generated by Django 3.0.7 on 2020-07-11 12:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notes_list_app', '0005_auto_20200711_1537'), ] operations = [ migrations.RemoveField( model_name='list', name='completed', ), migrations.AlterField( model_name='list', name='title', field=models.CharField(max_length=32), ), ] <file_sep>/notes_list_app/apps.py from django.apps import AppConfig class NotesListAppConfig(AppConfig): name = 'notes_list_app' <file_sep>/notes_list_app/migrations/0005_auto_20200711_1537.py # Generated by Django 3.0.7 on 2020-07-11 10:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notes_list_app', '0004_auto_20200711_1533'), ] operations = [ migrations.AlterField( model_name='list', name='item', field=models.CharField(max_length=1023), ), ] <file_sep>/notes_list_app/migrations/0008_remove_list_heading.py # Generated by Django 3.0.7 on 2020-07-11 12:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('notes_list_app', '0007_auto_20200711_1745'), ] operations = [ migrations.RemoveField( model_name='list', name='heading', ), ] <file_sep>/notes_list_app/migrations/0007_auto_20200711_1745.py # Generated by Django 3.0.7 on 2020-07-11 12:15 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('notes_list_app', '0006_auto_20200711_1737'), ] operations = [ migrations.RenameField( model_name='list', old_name='title', new_name='heading', ), ] <file_sep>/notes_list_app/migrations/0004_auto_20200711_1533.py # Generated by Django 3.0.7 on 2020-07-11 10:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notes_list_app', '0003_list_title'), ] operations = [ migrations.AlterField( model_name='list', name='item', field=models.CharField(default='No notes', max_length=1023), ), ] <file_sep>/requirements.txt dj-database-url==0.5.0 Django==3.0.5 djongo==1.3.3 gunicorn==20.0.4 pymongo==3.10.1 psycopg2-binary==2.7.7
b63448b486254332242d2f2d4d7b3a7969c0116c
[ "Python", "Text", "HTML" ]
9
Python
AravinthV/notesclone
4d53c5cd3a9e2199fd31fc9d27edad522c80678e
37b07e17e0cb4d85c71f3d75b71fc19c61e2cda5
refs/heads/master
<file_sep>import os AEROSPIKE_EVIDENCE_URL = os.getenv('AEROSPIKE_EVIDENCE_URL') AEROSPIKE_EVIDENCE_TTL = os.getenv('AEROSPIKE_EVIDENCE_TTL', 2592000) AEROSPIKE_EVIDENCE_TIMEOUT = os.getenv('AEROSPIKE_EVIDENCE_TIMEOUT', 0.800) SPLUNK_URL = os.getenv('SPLUNK_URL') SPLUNK_LOG_FORMAT = os.getenv('SPLUNK_LOG_FORMAT') SPLUNK_LOG_HANDLER_NAME = os.getenv('SPLUNK_LOG_HANDLER_NAME', 'Log') <file_sep>Simple Splunk module for logging ================================ This is a package for internal use only. Use with Python 3.8+. Usage ----- On command line: ``$ pip install pysplunk`` Add this code to the entryfile: .. code:: python from pysplunk import splunk splunk.configure_logger( index="index_name", token="splunk_token", version="1.0.0", env="production", level="DEBUG") To log something: .. code:: python splunk.loginfo( account=account_id, workflowtype="workflow_type", workflowinstance="workflow_instance", msg="message", customfields={"customField1": 3}) splunk.logdebug( account=account_id, workflowtype="workflow_type", workflowinstance="workflow_instance", msg="message", customfields={"customField1": 3}) splunk.logwarn( account=account_id, workflowtype="workflow_type", workflowinstance="workflow_instance", msg="message", customfields={"customField1": 1, "customField2": "2"}) splunk.logerror( account=account_id, workflowtype="workflow_type", workflowinstance="workflow_instance", msg="message", customfields={"customField1": 1}, evidencia="Exception traceback") Definitions ----------- * *account*: An integer representing the ID of the logged account. * *workflowtype*: Some identification for the overall operation, example: "login". * *workflowinstance*: Some identification for the specific part of the operation, examples "start_login", "login_error", "superuser_login", etc * *msg*: A desciptive message of the log. * *customfields*: Additional fields, examples: "operation_id", "user_id", "product_id", etc. * *evidencia*: Some string evidence (can be multiline) to attach into the log. This is convenient to add exceptions or API responses. Configuration ------------- * ``AEROSPIKE_EVIDENCE_URL`` URL for aerospike * ``AEROSPIKE_EVIDENCE_TTL`` TTL for aerospike evidence, default: 2592000 seconds * ``AEROSPIKE_EVIDENCE_TIMEOUT`` Timetou for sending data to aerospike, default: 0.800 seconds * ``SPLUNK_URL`` URL for splunk * ``SPLUNK_LOG_FORMAT`` Splunk log format, default is set in splunk.py * ``SPLUNK_LOG_HANDLER_NAME`` Handler for splunk log, default: Log Requirements ------------ splunkfowarder is required for this package work. <file_sep>import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() PACKAGE = "pysplunk" NAME = "pysplunk" DESCRIPTION = "Simple splunk log python package." AUTHOR = "<NAME>" AUTHOR_EMAIL = "<EMAIL>" URL = "http://www.lojaintegrada.com.br" VERSION = __import__(PACKAGE).__version__ setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=read("README.rst"), author=AUTHOR, author_email=AUTHOR_EMAIL, license="MIT", url=URL, packages=find_packages(exclude=["tests.*", "tests"]), classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Internet", ], install_requires=['aiohttp==0.21.0', 'requests==2.9.1'] ) <file_sep>import logging import os import sys import traceback from datetime import datetime from urllib.parse import urlencode from uuid import uuid4 import requests from . import aerospikeclient from .settings import * SPLUNK_CHANNEL = str(uuid4()) if not SPLUNK_LOG_FORMAT: SPLUNK_LOG_FORMAT = '%(customasctime)s ' + SPLUNK_LOG_HANDLER_NAME + \ ',%(logindex)s,%(instance)s,%(logtype)s,%(logtype)s,'\ '"%(workflow_type)s","%(workflow_instance)s",%(account)s,'\ '%(version)s message="%(message)s" %(custom_fields)s' class Level(object): debug = ["DEBUG"] info = ["DEBUG", "INFO"] warn = ["DEBUG", "INFO", "WARN"] error = ["DEBUG", "INFO", "WARN", "ERROR"] class Settings(object): LOG_NAME = 'splunk' LOG_LEVEL = logging.DEBUG INDEX = os.getenv('SPLUNK_INDEX') VERSION = '0.0.1' INSTANCE = 'local' ENV = 'beta' TOKEN = os.getenv('SPLUNK_TOKEN') class SplunkLogHandler(logging.Handler): def emit(self, record): if not Settings.INDEX or not Settings.TOKEN: return params = {'channel': SPLUNK_CHANNEL} splunk_url = '{}?{}'.format(SPLUNK_URL, urlencode(params)) log_entry = self.format(record) headers = { 'Content-Type': 'text/plain', 'Authorization': 'Splunk ' + Settings.TOKEN } return requests.post( splunk_url, data=log_entry, verify=False, headers=headers) # Make a global logging object. log = logging.getLogger(Settings.LOG_NAME) # Max 50mb splunk_handler = SplunkLogHandler() splunk_handler.setFormatter(logging.Formatter(SPLUNK_LOG_FORMAT)) log.addHandler(splunk_handler) def datetimeparsed(): return datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] + 'Z' def format_custom_fields(custom_fields): fields = ['{}="{}"'.format(k, str(v).replace('"', r'\"')) for k, v in custom_fields.items()] return ' '.join(fields) async def pack_exception(e, account): stack_trace = None exc_type, exc_value, trace_back = sys.exc_info() try: if exc_type: stack_trace_list = traceback.format_exception( exc_type, exc_value, trace_back) stack_trace = "".join(stack_trace_list) except Exception as ex: stack_trace = "Error packaging exception: {}".format(ex) if not stack_trace: return "" # Send to aerospike. return await aerospikeclient.saveAsync( str(Settings.INDEX), str(account), str(stack_trace)) def configure_logger(index, token, version, env, level=logging.DEBUG): if level: Settings.LOG_LEVEL = level log.setLevel(Settings.LOG_LEVEL) if index: Settings.INDEX = index.lower().strip() if token: Settings.TOKEN = token.strip() if version: Settings.VERSION = version.lower().strip() if env: Settings.ENV = env.lower().strip() get_instance() def get_instance(): try: url = 'http://169.254.169.254/latest/meta-data/instance-id' r = requests.get(url, timeout=0.8) instance = r.text except Exception: instance = 'local' Settings.INSTANCE = instance async def _log(level, account, workflow_type, workflow_instance, msg, custom_fields=None, evidence=None): if custom_fields is None: custom_fields = {} custom_fields["env"] = Settings.ENV evidence_hash = None if evidence is not None and Settings.LOG_LEVEL in Level.warn: evidence_hash = await aerospikeclient.saveAsync( Settings.INDEX, account, evidence) elif evidence is not None and Settings.LOG_LEVEL in Level.error: evidence_hash = await pack_exception(evidence, account) if evidence_hash: custom_fields["evidence"] = evidence_hash custom = format_custom_fields(custom_fields) _log_function = getattr(log, level) _log_function(msg.replace('"', r'\"'), extra={ 'customasctime': datetimeparsed(), 'logindex': Settings.INDEX, 'logtype': level, 'instance': Settings.INSTANCE, 'version': Settings.VERSION, 'workflow_type': str(workflow_type).strip(), 'workflow_instance': str(workflow_instance).strip(), 'account': str(account).lower().strip(), 'custom_fields': custom, }) async def logdebug(account, workflow_type, workflow_instance, msg, custom_fields=None, evidence=None): await _log( 'debug', account, workflow_type, workflow_instance, msg, custom_fields, evidence) async def loginfo(account, workflow_type, workflow_instance, msg, custom_fields=None, evidence=None): await _log( 'info', account, workflow_type, workflow_instance, msg, custom_fields, evidence) async def logwarn(account, workflow_type, workflow_instance, msg, custom_fields=None, evidence=None): await _log( 'warn', account, workflow_type, workflow_instance, msg, custom_fields, evidence) async def logerror(account, workflow_type, workflow_instance, msg, custom_fields=None, evidence=None): await _log( 'error', account, workflow_type, workflow_instance, msg, custom_fields, evidence) <file_sep>import asyncio import hashlib import json import traceback from urllib.parse import urlencode import aiohttp from .settings import * def gethash(evidence): try: byts = evidence.encode() md5bytes = hashlib.md5() md5bytes.update(byts) return md5bytes.hexdigest() except Exception as e: return "error-hash:{}".format(e) async def saveAsync(index, account, evidence): try: params = { 'application': index, 'expirationInSeconds': AEROSPIKE_EVIDENCE_TTL } url = "{}?{}".format(AEROSPIKE_EVIDENCE_URL, urlencode(params)) data = json.dumps(evidence) headers = {"Content-Type": "text/plain"} timeout = aiohttp.ClientTimeout(AEROSPIKE_EVIDENCE_TIMEOUT) async with aiohttp.ClientSession(timeout=timeout) as session: async with session.put(url, data=data, headers=headers) as r: return await r.text() except asyncio.TimeoutError as t: print('timeout: {}'.format(t)) except Exception: msg = "Error in save to aerospike: {}".format(traceback.print_exc()) print(msg) return '' <file_sep>import asyncio from pysplunk import splunk async def main(): try: print('configuring...') splunk.configure_logger( 'my_app', '1.0.1', 'test', 'DEBUG') print('logdebug...') await splunk.logdebug( 'account', 'workflow type', 'workflow instance', '"logdebug"', {'custom1': 'test'}, "evidence") print('loginfo...') await splunk.loginfo( 'account', 'workflow type', 'workflow instance', 'loginfo', evidence="evid info") print('logwarn...') await splunk.logwarn( 'account', 'workflow type', 'workflow instance', 'logwarn', evidence="evid warn") i = 1 / 0 except Exception as ex: print('logerror...') await splunk.logerror( 'account', 'workflow type', 'workflow instance', 'logerror', {'custom1': 'test'}, ex) if __name__ == '__main__': print('testing...') loop = asyncio.get_event_loop() loop.run_until_complete(main()) print('end!') <file_sep>aiohttp==0.21.0 requests==2.9.1
749aa7d9a248508a5669c6fbee435307007cd1de
[ "Python", "Text", "reStructuredText" ]
7
Python
lojaintegrada/pysplunk
ee6c3b43f94dcc8c2b20fc7116289baa08a343e3
80855f44dd8a8c7cef5629bf6d9c6eb325d883f3
refs/heads/main
<file_sep>import java.util.Scanner; import javax.management.relation.RelationSupport; class SingleLinkedList { public int data; public SingleLinkedList next; public SingleLinkedList(int data) { this.data = data; } @Override public String toString() { return "SingleLinkedList [data=" + data + "]"; } public static SingleLinkedList removeDuplicate(SingleLinkedList list){ SingleLinkedList result = list; while(list != null && list.next != null){ if(list.data == list.next.data){ list.next = list.next.next; } else list = list.next; } return result; } } class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); int t = Integer.parseInt(sc.nextLine()); SingleLinkedList llist = new SingleLinkedList(t); SingleLinkedList head = llist; llist.next=null; for (int i = 1; i < n; i++) { int temp = Integer.parseInt(sc.nextLine()); llist.next = new SingleLinkedList(temp); llist = llist.next; } SingleLinkedList result = SingleLinkedList.removeDuplicate(head); while(result != null) { System.out.println(result.data); result = result.next; } } } <file_sep>package set; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Random; import java.util.Set; import java.util.TreeSet; public class SetDemo { public static void main(String[] args) { Random random = new Random(); // This stores the value in random order. Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < 10; i++) { set.add(random.nextInt(10)); } System.out.println(set); // LinkedHashSet maintains the order. Set<Integer> lset = new LinkedHashSet<Integer>(); for (int i = 0; i < 10; i++) { int temp = random.nextInt(10); // System.out.println(temp); lset.add(temp); } System.out.println(lset); // It stores the value in sorted order. Set<Integer> tset = new TreeSet<Integer>(); for (int i = 0; i < 10; i++) { int temp = random.nextInt(10); // System.out.println(temp); tset.add(temp); } System.out.println(tset); } } <file_sep>package array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; public class ArrayListDemo { public static void main(String[] args) { // All the methods works with object not with stereotype Integer arr[] = { 11, 23, 32 }; // Comparator and streams only works with Objects not with stereotype Arrays.sort(arr, Collections.reverseOrder()); List<Integer> list = new ArrayList<Integer>(); list.add(10); list.add(30); list.add(20); Collections.sort(list, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1 - o2; } }); // this is general sort Collections.sort(list,(a,b)->a-b); System.out.println(list); // You can also use this but in this case comparator is compulsory list.sort((a,b)->a-b); System.out.println(list); for (int i : arr) System.out.println(i); } } <file_sep>package map; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; public class MapDemo { public static void main(String[] args) { // We cannot guarantee the order in HashMap Map<Integer,String> map = new HashMap<Integer,String>(); map.put(2, "niwas"); map.put(1,"reeta"); map.put(3, "pratiksha"); map.put(4, "moon"); System.out.println(map); // This guarantee the order in which they are entered Map<Integer,String> lmap = new LinkedHashMap<Integer,String>(); lmap.put(2, "niwas"); lmap.put(1,"reeta"); lmap.put(3, "pratiksha"); lmap.put(4, "moon"); lmap.put(2, "<NAME>"); // System.out.println(lmap.get(8)+1); // It returns null when key is not present System.out.println(lmap); // This stores the data in sorted order Map<Integer,String> tmap = new TreeMap<Integer,String>(); tmap.put(2, "niwas"); tmap.put(1,"reeta"); tmap.put(3, "pratiksha"); tmap.put(4, "moon"); System.out.println(tmap); } }
4920620e4e1081a5221eba7fd5184e950e19749d
[ "Java" ]
4
Java
nkumar9733/Skill_Training
85e64bd594ad57a6348c805e970f8aa626dc2021
6cb64d84f1cb96fbdb9c190583b8331777ef6255
refs/heads/master
<file_sep>window.onload = function() { var React = { createElement: ( tagName, props, children = [] ) => { var elem = document.createElement(tagName); for (var i in props) { if ( i === 'style' && typeof props[i] === 'object'){ for (var prop in props[i]){ elem.style[prop] = props.style[prop]; } } else if (i === 'textContent') { elem.innerHTML = props[i]; } } if (typeof children == 'string') { elem.appendChild(document.createTextNode(children)); } else { for (var child of children){ if (typeof child === 'string'){ elem.appendChild(document.createTextNode(child)); } else { elem.appendChild(child)} } } return elem; }, render: (myTag , to) => { to.appendChild(myTag); } } const app = React.createElement('div', { style: { backgroundColor: 'red' } }, [ React.createElement('span', undefined, 'Hello world'), React.createElement('br'), 'This is just a text node', React.createElement('div', { textContent: 'Text content' }), ]); React.render( app, document.body ); }
fa26c81c717bfa8dc52bdfb0d7c378c99165d88d
[ "JavaScript" ]
1
JavaScript
AlexRom000/apiko-lesson_1
e087e66bfdb1cfba9ad4d350410286198a2b19a3
f9edcd4f5a0af314cc8adb0aacf6c41576d65a14
refs/heads/main
<repo_name>Nastya880/IndustialProg<file_sep>/Source.cpp #include "Header.h" using namespace std; string to_str(double val) { char val_str[20] = { 0 }; snprintf(val_str, sizeof(val_str), "%.0lf", val); return val_str; } string AnyX(double y) { string y_str = to_str(y); return "4 " + y_str; } string AnyY(double x) { string x_str = to_str(x); return "3 " + x_str; } string EndlessAnswers(double firstArg, double SecondArg, double ThirdArg) { string first_number_str = to_str(-firstArg / SecondArg); string second_number_str = to_str(ThirdArg / SecondArg); return "1 " + first_number_str + " " + second_number_str; } string Solve(double a, double b, double c, double d, double e, double f, string output) { double firstComposition = a * d - c * b; double secondComposition = e * d - b * f; double thirdComposition = a * f - c * e; if ((a == 0) && (b == 0) && (c == 0) && (d == 0) && (e == 0) && (f == 0)) { output = "5"; } else if ((firstComposition != 0) && ((secondComposition != 0) || (thirdComposition != 0))) { string y = to_str(thirdComposition / firstComposition); string x = to_str(secondComposition / firstComposition); output = "2 " + x + " " + y; } else if (((firstComposition == 0) && ((secondComposition != 0) || (thirdComposition != 0))) || (a == 0 && c == 0 && e / b != f / d) || (b == 0 && d == 0 && e / a != f / c) || (a == 0 && b == 0 && c == 0 && d == 0 && (e / f > 0))) { if ((a == 0 && b == 0 && e == 0 && d != 0 && c == 0) || (c == 0 && d == 0 && f == 0 && b != 0 && a == 0)) { if (b == 0) output = AnyX(f / d); else if (d == 0) output = AnyX(e / b); else if (e == 0 || f == 0) output = AnyX(0); } else if ((a == 0 && b == 0 && e == 0 && c != 0 && d == 0) || (c == 0 && d == 0 && f == 0 && a != 0 && b == 0)) { if (a == 0) output = AnyY(f / c); else if (c == 0) output = AnyY(e / a); else if (e == 0 || f == 0) output = AnyY(0); } else output = "0"; } else if (a == 0 && c == 0) { if (e == 0) output = AnyX(f / d); else if (f == 0) output = AnyX(e / b); else output = AnyX(e / b); } else if (b == 0 && d == 0) { if (e == 0) output = AnyY(f / c); else if (f == 0) output = AnyY(e / a); else output = AnyY(e / a); } else if (b == 0 && e == 0) { output = EndlessAnswers(c, d, f); } else if (d == 0 && f == 0) { output = EndlessAnswers(a, b, e); } else if (a == 0 && e == 0) { output = EndlessAnswers(d, c, f); } else if (c == 0 && f == 0) { output = EndlessAnswers(b, a, e); } else if ((a / b == c / d)) { output = EndlessAnswers(c, d, f); } else { output = "Are you kidding me?"; } return output; } int main() { double a, b, c, d, e, f; string output = ""; cin >> a >> b >> c >> d >> e >> f; output = Solve(a, b, c, d, e, f, output); cout << output; return 0; } <file_sep>/Header.h #pragma once #include <iostream> #include <cmath> #include <string> using namespace std; string to_str(double val); string AnyX(double y); string AnyY(double x); string EndlessAnswers(double firstArg, double SecondArg, double ThirdArg); string Solve(double a, double b, double c, double d, double e, double f, string output); <file_sep>/UnitTestMyLab2.cpp #include "pch.h" #include "CppUnitTest.h" #include "../MyLab2/Header.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace std; namespace UnitTestMyLab2 { TEST_CLASS(UnitTestMyLab2) { public: //unit тесты для функций TEST_METHOD(AnyY_4_Returned4X) { double x = 4; Assert::IsTrue(AnyY(x) == "3 4", L"Assert"); } TEST_METHOD(AnyX_4_Returned4Y) { double y = 4; Assert::IsTrue(AnyX(y) == "4 4", L"Assert"); } TEST_METHOD(EndlessAnswers_Returned123) { //arrange double firstArg = -2; double secondArg = 1; double thirdArg = 3; //act Assert::IsTrue(EndlessAnswers(firstArg, secondArg, thirdArg) == "1 2 3", L"Assert"); } //проверка условий TEST_METHOD(Solve_allZero_Returned5) { //arrange double a = 0; double b = 0; double c = 0; double d = 0; double e = 0; double f = 0; std::string string = ""; Assert::IsTrue(Solve(a, b, c, d, e, f, string) == "5", L"Assert"); } TEST_METHOD(Solve_firstAnswer_Returned215) { //arrange double a = 4; double b = 1; double c = 4; double d = 5; double e = 9; double f = 29; std::string string = ""; //1*4+1*5 = 9 //1*4 + 5*5 = 29 Assert::IsTrue(Solve(a, b, c, d, e, f, string) == "2 1 5", L"Assert"); } TEST_METHOD(Solve_noAnswer_Returned0) { //arrange double a = 2; double b = 2; double c = 2; double d = 2; double e = 2; double f = 9; //2*x + 2*y = 2 //2*x + 2*y = 9 std::string string = ""; Assert::IsTrue(Solve(a, b, c, d, e, f, string) == "0", L"Assert"); } TEST_METHOD(Solve_kidding_Returned5) { //arrange double a = 2; double b = 2; double c = 1; double d = 4; double e = 0; double f = 0; //2*x + 2*y = 0 //1*x + 4*y = 0 std::string string = ""; Assert::IsTrue(Solve(a, b, c, d, e, f, string) == "Are you kidding me?", L"Assert"); } TEST_METHOD(Solve_lotsAnswer_Returned1) { //arrange double a = 5; double b = 5; double c = 25; double d = 25; double e = 0; double f = 0; //5*x + 5*y = 0 //25*x +25*0 = 0 std::string string = ""; Assert::IsTrue(Solve(a, b, c, d, e, f, string) == "1 -1 0", L"Assert"); } }; } <file_sep>/README.md # IndustialProg Workshop on industrial programming Lab1 done
867a1bc2fb8c437659874e81398b248aef0637ff
[ "Markdown", "C++" ]
4
C++
Nastya880/IndustialProg
bd9e0d0b975294f542b7f38ad68a7a461749307a
b6d6766c7d2b0240e79d045e00e6653faa1d8cb2
refs/heads/master
<file_sep>/* eslint-disable */ import { wrapUrlWithProxy } from '../services/proxy-service.js'; async function copyToClipboard(imageUrl) { navigator.permissions.query({ name: "clipboard-write" }).then(async result => { if (result.state == "granted" || result.state == "prompt") { const image = await fetch(wrapUrlWithProxy(imageUrl)) const blob = await image.blob() const data = [new ClipboardItem({ [blob.type]: blob })]; await navigator.clipboard.write(data) } else { console.warn("Clipboard write is not accessible") } }); } export { copyToClipboard };<file_sep>const proxyUrl = process.env.VUE_APP_PROXY_URL function wrapUrlWithProxy(originalUrl) { return proxyUrl + (proxyUrl.endsWith("/") ? "" : "/") + originalUrl; } export { wrapUrlWithProxy };<file_sep>import axios from 'axios'; const baseApiUrl = process.env.VUE_APP_API_BASE_URL async function getImages(searchTerm, searchIndex = 1) { const url = `${baseApiUrl}?&searchTerm=${searchTerm}&index=${searchIndex}` return await getData(url); } async function getData(url) { const result = await axios.get(url) if (result.status != 200) { throw `Images API failed with code ${result.status}.` } return result.data.data } export { getImages };<file_sep># alpha-img - SPA A simple web project that has one simple goal: provide a quick search of images with transparent backgrounds. A good example of usage is for presentations that require various images with transparent backgrounds, or product/company logos. ![alpha-img screenshot](docs/img/app_screenshot.png) The project consists of two applicaitons: - [SPA built with Vue.js 3](**THIS REPO**) - [Web API built with .NET 5](https://github.com/Loreno10/alpha-img.webapi-dotnet) The SPA communicates with the Web API to get the images. The only reason for introducting the Web API (and not calling Google API directly) was to protect the Google API Key. Initially, the WebAPI was not a part of the project, and the SPA was communicating directly with the Google APIs (the service for that is in the `src/services/direct-google-images-service.js` - it is not currently used). The app is deployed to Heroku at https://alpha-imgs-spa.herokuapp.com/. ## Features - search for images using searchbar - look through the results in a simple gallery, with pagination - maximize the image by clicking on it or on the "eye" button - copy the image into the clipboard with a click of a button - open the image in its full size in another tab (again, with a click of a button) The copy-to-clipboard functionality requires the SPA to download the images. To enable that and get past CORS issues, the SPA needs some proxy service that will add the rquired CORS headers to the GET request for each image. Currently, a publicly available endpoint https://cors-anywhere.herokuapp.com/ is being used. ## Project setup ``` npm install ``` ### Compiles and hot-reloads for development ``` npm run serve ``` ### Compiles and minifies for production ``` npm run build ``` ### Configuration To enable SPA and Web API to work together, you need to set the correct `VUE_APP_API_BASE_URL` value in `.env`. It is the URL of your Web API deployment.<file_sep>import axios from 'axios'; const apiKey = process.env.VUE_APP_GOOGLE_API_KEY const cx = process.env.VUE_APP_GOOGLE_API_CX const baseApiUrl = process.env.VUE_APP_GOOGLE_API_BASE_URL async function getImages(searchTerm, searchIndex = 1) { const urls = getApiUrls(searchIndex, searchTerm) const results = (await Promise.all([getData(urls[0]), getData(urls[1])])).flat() return removeNonPngImages(results).sort((a, b) => (a.width < b.width) ? 1 : -1) // For testing purposes // const fakeUrl = "http://placekitten.com/300/200" // return [{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl}, // {thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl}, // {thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl}, // {thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl},{thumbnailUrl: fakeUrl}] } function getApiUrls(searchIndex, searchTerm) { const commonUrl = `${baseApiUrl}?cx=${cx}&q=${searchTerm}&key=${apiKey}&filter=1&imgColorType=trans&searchType=image` const index1 = (searchIndex - 1) * 20 + 1 const index2 = (searchIndex - 1) * 20 + 11 const url1 = `${commonUrl}&start=${index1}` const url2 = `${commonUrl}&start=${index2}` return [url1, url2] } function removeNonPngImages(images) { return images.filter(n => n.imageUrl.endsWith(".png") || n.imageUrl.endsWith(".PNG")) } async function getData(url) { const result = await axios.get(url) if (result.status != 200) { throw `Google API failed with code ${result.status}.` } return transformResult(result.data) } function transformResult(result) { let images = [] console.log(result) result.items.forEach(item => { images.push({ title: item.title, imageUrl: item.link, thumbnailUrl: item.image.thumbnailLink, fileFormat: item.fileFormat, height: item.image.height, width: item.image.width }) }) console.log(images) return images } export { getImages };
0d8fd2c1ac711baa46b853ebad6f7dfbf0ace0c6
[ "JavaScript", "Markdown" ]
5
JavaScript
marcinjahn/alpha-img.spa-vue
3787181b43be64c3d2b52a16a2c5423f332b0a63
7ae0199940fbe6315bb087effc16645f94221bbf
refs/heads/master
<file_sep>package webapi import ( "encoding/json" "log" "net/http" "github.com/gorilla/mux" "github.com/gorilla/websocket" ) var ( upgrader = websocket.Upgrader{} ) func Router() *mux.Router { router := mux.NewRouter() router.HandleFunc("/api/health", handleHealthCheck) router.HandleFunc("/api/stream", handleStreamTrans) return router } func handleHealthCheck(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(map[string]bool{"ok": true}) } func handleStreamTrans(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { json.NewEncoder(w).Encode(map[string]interface{}{"ok": false, "message": "failed to upgrade to websocket"}) return } for { messageType, p, err := conn.ReadMessage() if err != nil { log.Println(err) break } if err := conn.WriteMessage(messageType, p); err != nil { log.Println(err) break } } } <file_sep>package fns import ( "context" "log" "strings" "sync" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/yuekcc/fns/fnspec" ) type Machine struct { cli *client.Client sync.Mutex } func getDockerClient() (*client.Client, error) { return client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) } func (m *Machine) useClient() *client.Client { m.Lock() defer m.Unlock() if m.cli == nil { cli, err := getDockerClient() if err != nil { panic(err) } m.cli = cli } return m.cli } func (m *Machine) createContainer(ctx context.Context, imageName string, labels map[string]string) (string, error) { config := &container.Config{ Image: imageName, Labels: labels, } resp, err := m.useClient().ContainerCreate(ctx, config, nil, nil, nil, "") if err != nil { log.Println("ContainerCreate Error:", err) return "", err } return resp.ID, nil } func (m *Machine) Install(ctx context.Context, spec *fnspec.FunctionSpec) (string, error) { labels := generateContainerLabels(spec) imageName := "yuekcc/node-demo-app" return m.createContainer(ctx, imageName, labels) } func (m *Machine) Spawn(ctx context.Context, containerId string) error { err := m.useClient().ContainerStart(ctx, containerId, types.ContainerStartOptions{}) if err != nil { log.Println("ContainerStart Error:", err) return err } return nil } func (m *Machine) Kill(ctx context.Context, containerId string) error { err := m.useClient().ContainerStop(ctx, containerId, nil) if err != nil { log.Println("ContainerStop Error:", err) return err } return nil } func (m *Machine) Uninstall(ctx context.Context, containerId string) error { info, err := m.Inspect(ctx, containerId) if err != nil { log.Println("ContainerStats Error:", err) return err } containerStatus := strings.ToLower(info.State.Status) if containerStatus == "running" { log.Println("killing a running app") err := m.Kill(ctx, containerId) if err != nil { return err } } err = m.useClient().ContainerRemove(ctx, containerId, types.ContainerRemoveOptions{}) if err != nil { log.Println("ContainerRemove Error:", err) return err } return nil } func (m *Machine) List(ctx context.Context) ([]types.Container, error) { list, err := m.useClient().ContainerList(ctx, types.ContainerListOptions{All: true}) if err != nil { return nil, err } result := []types.Container{} for _, c := range list { _, exists := c.Labels["fns-spec-version"] // 只显示包含 fns-spec-version 标签的容器 if exists { result = append(result, c) } } return result, nil } func (m *Machine) Inspect(ctx context.Context, containerId string) (types.ContainerJSON, error) { return m.useClient().ContainerInspect(ctx, containerId) } func (m *Machine) Shutdown() error { return m.useClient().Close() } func GetMachine() *Machine { return &Machine{} } <file_sep>package main import ( "fmt" "log" "time" "github.com/shirou/gopsutil/v3/cpu" "github.com/shirou/gopsutil/v3/mem" ) func formatNumber(num uint64) uint64 { return uint64(num / 1024 / 1014) } func main() { v, err := mem.VirtualMemory() if err != nil { log.Fatalln(err) } fmt.Printf("Total: %vM, Free: %vM, Used: %.2f%%\n", formatNumber(v.Total), formatNumber(v.Free), v.UsedPercent) cs, err := cpu.Counts(true) if err != nil { log.Fatalln(err) } cp, _ := cpu.Percent(1*time.Second, false) fmt.Printf("Cpu count: %d, Cpu Percent: %v\n", cs, cp) } <file_sep># fns fns 是一个 FAAS。 ## 特性 - [x] docker - [x] 服务自动注册(traefik + 容器 labels 实现) - [ ] cli 开发工具 - [ ] sdk - [ ] nodejs - [ ] go - [ ] wasm - [ ] 文档 ## LICENSE [MIT](LICENSE)<file_sep>package main import ( "flag" "log" "net/http" "github.com/gorilla/mux" "github.com/yuekcc/fns/web" "github.com/yuekcc/fns/webapi" ) var ( hostFlag string ) func init() { flag.StringVar(&hostFlag, "addr", "0.0.0.0:10086", "set web server host") } func main() { flag.Parse() router := mux.NewRouter() router.PathPrefix("/api").Handler(webapi.Router()) router.PathPrefix("/").Handler(http.FileServer(http.FS(web.Assets))) server := &http.Server{ Handler: router, Addr: hostFlag, } log.Printf("Server host on: %s\n", hostFlag) err := server.ListenAndServe() if err != nil { log.Fatalln(err) } } <file_sep>module github.com/yuekcc/fns go 1.17 require ( github.com/Microsoft/go-winio v0.5.0 // indirect github.com/containerd/containerd v1.4.4 // indirect github.com/docker/distribution v2.7.1+incompatible // indirect github.com/docker/docker v20.10.6+incompatible github.com/docker/go-connections v0.4.0 // indirect github.com/docker/go-units v0.4.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/gorilla/mux v1.8.0 github.com/gorilla/websocket v1.4.2 github.com/moby/term v0.0.0-20201216013528-df9cb8a40635 // indirect github.com/morikuni/aec v1.0.0 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.0.1 // indirect github.com/shirou/gopsutil/v3 v3.21.3 github.com/sirupsen/logrus v1.8.1 // indirect github.com/spf13/cobra v1.1.3 github.com/tklauser/go-sysconf v0.3.5 // indirect golang.org/x/sys v0.0.0-20210426230700-d19ff857e887 // indirect golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba // indirect google.golang.org/grpc v1.37.0 // indirect gotest.tools/v3 v3.0.3 // indirect sigs.k8s.io/yaml v1.2.0 ) require ( github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect github.com/go-ole/go-ole v1.2.4 // indirect github.com/golang/protobuf v1.4.2 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/tklauser/numcpus v0.2.2 // indirect golang.org/x/net v0.0.0-20201021035429-f5854403a974 // indirect google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 // indirect google.golang.org/protobuf v1.25.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) <file_sep>package fns import ( "fmt" "github.com/yuekcc/fns/fnspec" ) func generateContainerLabels(spec *fnspec.FunctionSpec) map[string]string { labels := map[string]string{ "fns-spec-version": fmt.Sprintf("%d", fnspec.SPEC_VERSION), "fns-route": fmt.Sprintf("/%s/v%d/%s", spec.Metadata.ServiceName, spec.Metadata.Version, spec.Metadata.Name), "traefik.enable": "true", "traefik.http.middlewares.response-compress.compress": "true", } return labels } <file_sep>package fnspec const ( SPEC_VERSION = 1 ) type Spec struct { SpecVersion int `json:"specVersion,omitempty"` // 默认值 1 } type FunctionSpec struct { Spec Metadata struct { Name string `json:"name"` // 命名 ^[A-Za-z][A-za-z0-9_]*$ Version int `json:"version"` // 函数服务版本号 ServiceName string `json:"serviceName"` // 命名 ^[A-Za-z][A-za-z0-9_]*$ Sdk string `json:"sdk"` // 值 ^[nodejs|go|wasm]-\d*$ LaunchCommandLine string `json:"launchCommandLine"` // 启动命令行 } } <file_sep>package main import ( "context" "fmt" "log" "os" "github.com/spf13/cobra" "github.com/yuekcc/fns" "github.com/yuekcc/fns/fnspec" "sigs.k8s.io/yaml" ) func main() { rootCmd := &cobra.Command{ Use: "fns", Short: "a function service", } rootCmd.AddCommand( &cobra.Command{ Use: "install", Short: "install a function", Run: install, }, &cobra.Command{ Use: "uninstall", Short: "kill and uninstall a function", Run: uninstall, }, &cobra.Command{ Use: "ps", Short: "list all functions", Run: listFunctions, }, ) if err := rootCmd.Execute(); err != nil { os.Exit(1) } } func listFunctions(cmd *cobra.Command, args []string) { machine := fns.GetMachine() defer machine.Shutdown() ctx := context.Background() containers, err := machine.List(ctx) if err != nil { log.Fatalln(err) return } for i := 0; i < len(containers); i++ { c := containers[i] fmt.Println(c.ID, c.Labels["fns-route"], c.State) } } func install(cmd *cobra.Command, args []string) { if len(args) == 0 { log.Fatalln("require a functionspec file") } specFile, err := os.ReadFile(args[0]) if err != nil { log.Fatalln(err) } functionSpec := fnspec.FunctionSpec{} err = yaml.Unmarshal(specFile, &functionSpec) if err != nil { log.Fatalln("unable to read yaml file, ", err) } machine := fns.GetMachine() defer machine.Shutdown() ctx := context.Background() log.Printf("start install function: %s %d\n", functionSpec.Metadata.Name, functionSpec.Metadata.Version) id, err := machine.Install(ctx, &functionSpec) if err != nil { log.Fatalln(err) } log.Printf("install success\n") log.Printf("launch app\n") err = machine.Spawn(ctx, id) if err != nil { log.Fatalln(err) } fmt.Printf("%s run on %s\n", functionSpec.Metadata.Name, id) } func uninstall(cmd *cobra.Command, args []string) { machine := fns.GetMachine() defer machine.Shutdown() ctx := context.Background() for _, id := range args { err := machine.Uninstall(ctx, id) if err != nil { log.Fatalln(err) } log.Printf("%s uninstalled\n", id) } } <file_sep>package web import "embed" var ( //go:embed index.html dist Assets embed.FS ) <file_sep>#!/bin/env bash docker run -d --rm \ -p 80:80 \ -p 9090:8080 \ -v $PWD/traefik.yml:/etc/traefik/traefik.yml \ -v /var/run/docker.sock:/var/run/docker.sock \ --label "traefik.enable=false" \ traefik:v2.5
8b61e4cf2c7a305177f7cb301c7d1580a382bdd2
[ "Markdown", "Go Module", "Go", "Shell" ]
11
Go
yuekcc/fns
656ad0de5a0eaf69b7f2f046a941f233d527e870
fcf9d95e9dc1b0a85b75bf73a5fb6c4bd8b19702
refs/heads/master
<repo_name>IvashchenkoArtem/Page<file_sep>/js/script.js $(function () { $('.js-nav-toggle').on('click', function () { $(this).toggleClass('toggler__icon--open'); $('.js-nav').toggleClass('nav--open'); }); }); $(function () { $('.js-date').on('click', function () { $(this).toggleClass('header-right__date--active'); $('.sl__slide-js').toggleClass('sl__slide--active'); }); }); let submit = document.getElementById("submit"); let info = document.getElementById("info"); submit.onmouseover = function () { info.style.visibility = "visible" }; submit.onmouseout = function () { info.style.visibility = "hidden" }; info.onmouseover = function () { info.style.visibility = "visible" }; info.onmouseout = function () { info.style.visibility = "hidden" }; $(function () { $('.js-access').on('click', function () { $(this).toggleClass('header-right__wrap-access--active'); $('.js-quickAccess').toggleClass('row__quickAccess--active'); }); $('.js-access').hover(function () { $('.js-quickAccess').toggleClass('row__quickAccess--open'); }); }); $(document).ready(function () { $('.sl').slick({ slidesToShow: 4, infinite: false, slidesToScroll: 1, responsive: [ { breakpoint: 1125, settings: { slidesToShow: 3, slidesToScroll: 1, } }, { breakpoint: 900, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] }); });
f4303acfdaba6558fa9fe97ab83c6adb0a2f57cf
[ "JavaScript" ]
1
JavaScript
IvashchenkoArtem/Page
478fc1cb42f061eba1430f9521bb68fdc71626eb
d173d00c772519dcbd328b94b0340f98370b9b21
refs/heads/master
<file_sep>import { Mesh } from "@babylonjs/core"; import GameComponent from "./game"; export default class BallComponent extends Mesh { /** * Redefine the scene as GameComponent as the scene as a script attached to it. * @override */ _scene: GameComponent; private _startPosition; private _startHeight; private _player; /** * Override constructor. * @warn do not fill. */ protected constructor(); /** * Called on the node is being initialized. * This function is called immediatly after the constructor has been called. */ onInitialize(): void; /** * Called on the scene starts. */ onStart(): void; /** * Called each frame. */ onUpdate(): void; /** * Resets the ball component. Called typically when the player loses the ball. */ reset(): void; /** * Applies the start impulse. This is called on the game is started when the user presses * the space key on the keyboard. */ applyStartImpulse(): void; } <file_sep># A published examples from Babylon.js Editor v4.0 beta2 # Background Babylon.js Editor has been updated as wonderful WebGL contents editor like Unity. The repository is an example of Babylon.js Editor project. Environment : Babylon.js Editor v4.0 beta7 or later # Make environment of Babylon.js Editor ![overview](./forReadme/BJSEditor_main_screen.jpg) 1. Get Babylon.js Editor source ```bash $ git clone https://github.com/BabylonJS/Editor.git ``` 2. Switch release branch and build ```bash $ git checkout -b release/4.0.0 origin/release/4.0.0 $ npm install $ npm run build ``` 3. Run Babylon.js Editor.exe ( or Babylon.js Editor.app if you use Mac) ``` electron-packages / windows /Babylon.js Editor.exe ``` ``` electron-packages / mac /Babylon.js Editor.app ``` # Run the sample project 1. Put the repo on any floder 2. Run Babylon.js Editor and select "workspace.editorworkspace" file ![](./forReadme/select_existing_workspace.jpg) 3. Press Play button ![](./forReadme/playbutton_on_babylonjseditor.jpg) Another preview window is showed. You can also check your own browser by accessing "http://<IP address>:1338" # About the sample - A simple ping pong game - Key A: left move D: right move space : Start play / Shoot sphere ![](./forReadme/game_scene.gif) The repo is an experimental trial of Babylon.js Editor. Therefore each of code are not refactored. # Reference Currently all support posts below are only Japanese. English version will be posted soon. [UnityのようにBabylon.jsコンテンツが作れる「Babylon.js Editor」が大幅アップデートしていたので使い方を調べてみました](https://www.crossroad-tech.com/entry/babylonjs-editor-4beta2-review) [Unityライクの操作になったBabylon.js Editorで簡単なゲームを作ります Vol.1(ステージ作成、操作)](https://www.crossroad-tech.com/entry/babylonjs-editor-4beta2-make-game1) [Unityライクの操作になったBabylon.js Editorで簡単なゲームを作ります Vol.2(物理エンジン)](https://www.crossroad-tech.com/entry/babylonjs-editor-4beta2-make-game2) [Unityライクの操作になったBabylon.js Editorで簡単なゲームを作ります Vol.3(衝突判定)](https://www.crossroad-tech.com/entry/babylonjs-editor-4beta2-make-game3) [Unityライクの操作になったBabylon.js Editorで簡単なゲームを作ります Vol.4(GUIの追加)](https://www.crossroad-tech.com/entry/babylonjs-editor-4beta2-make-game4) [Unityライクの操作になったBabylon.js Editorで簡単なゲームを作ります Vol.5(得点加算、ライフ変更、テキスト表示)](https://www.crossroad-tech.com/entry/babylonjs-editor-4beta2-make-game5) [Unityライクの操作になったBabylon.js Editorで簡単なゲームを作ります Vol.6(サーバに格納して実行)](https://www.crossroad-tech.com/entry/babylonjs-editor-4beta2-make-game6) <file_sep>import { Mesh } from "@babylonjs/core"; export default class PlayerComponent extends Mesh { /** * Override constructor. * @warn do not fill. */ protected constructor(); private _wall_left; private _wall_right; /** * Called on the node is being initialized. * This function is called immediatly after the constructor has been called. */ onInitialize(): void; /** * Called on the scene starts. */ onStart(): void; /** * Called each frame. */ onUpdate(): void; /** * Moves the player on the left */ protected moveLeft(): void; /** * Moves the player on the right. */ protected moveRight(): void; } <file_sep>import { Mesh, KeyboardEventTypes, PhysicsImpostor } from "@babylonjs/core"; import { onKeyboardEvent,fromScene } from "../tools"; export default class PlayerComponent extends Mesh { /** * Override constructor. * @warn do not fill. */ // @ts-ignore ignoring the super call as we don't want to re-init protected constructor() { } @fromScene("wall_left") private _wall_left: Mesh; @fromScene("wall_right") private _wall_right: Mesh; /** * Called on the node is being initialized. * This function is called immediatly after the constructor has been called. */ public onInitialize(): void { // ... } /** * Called on the scene starts. */ public onStart(): void { this.physicsImpostor = new PhysicsImpostor(this, PhysicsImpostor.BoxImpostor, { mass: 0, friction: 0, restitution: 1 }); } /** * Called each frame. */ public onUpdate(): void { // ... } /** * Moves the player on the left */ @onKeyboardEvent(65, KeyboardEventTypes.KEYDOWN) protected moveLeft(): void { if (this.intersectsMesh(this._wall_left)){ }else{ this.position.z += 5; } } /** * Moves the player on the right. */ @onKeyboardEvent(68, KeyboardEventTypes.KEYDOWN) protected moveRight(): void { if (this.intersectsMesh(this._wall_right)){ }else{ this.position.z -= 5; } } } <file_sep>import { Scene } from "@babylonjs/core"; import { AdvancedDynamicTexture, TextBlock, Control, Image, StackPanel } from "@babylonjs/gui"; import { fromScene } from "../tools"; import BallComponent from "./ball"; export default class GameComponent extends Scene { /** * Defines the reference to the GUI advanced texture. */ public gui: AdvancedDynamicTexture = null; @fromScene("ball") private _ball: BallComponent; private _collidedBlocksCount: number = 0; private _gameMessageControl: TextBlock = null; private _counterControl: TextBlock = null; private _lifesStackControl: StackPanel = null; private _isPlaying: boolean = true; /** * Override constructor. * @warn do not fill. */ // @ts-ignore ignoring the super call as we don't want to re-init protected constructor() { } /** * Called on the node is being initialized. * This function is called immediatly after the constructor has been called. */ public onInitialize(): void { this.gui = AdvancedDynamicTexture.CreateFullscreenUI("ui", true, this); // Create start game text this._gameMessageControl = new TextBlock("startGame", "Please press space bar to start"); this._gameMessageControl.color = "white"; this._gameMessageControl.fontSize = 40; this._gameMessageControl.fontFamily ="Viga"; this.gui.addControl(this._gameMessageControl); // Create blocks counter this._counterControl = new TextBlock("counter", "Blocks 0 / 8"); this._counterControl.color = "white"; this._counterControl.fontSize = 24; this._counterControl.textHorizontalAlignment = Control.HORIZONTAL_ALIGNMENT_CENTER; this._counterControl.textVerticalAlignment = Control.VERTICAL_ALIGNMENT_TOP; this._counterControl.paddingTop = 20; this._counterControl.fontFamily ="Viga"; this.gui.addControl(this._counterControl); // Create lifes controls this._lifesStackControl = new StackPanel("lifes"); this._lifesStackControl.isVertical = false; this._lifesStackControl.adaptHeightToChildren = true; this._lifesStackControl.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_CENTER; this._lifesStackControl.verticalAlignment = Control.VERTICAL_ALIGNMENT_TOP; this._lifesStackControl.top = 50; this.gui.addControl(this._lifesStackControl); for (let i = 0; i < 3; i++) { const lifeControl = new Image("life", "./scenes/scene/files/heart.png"); lifeControl.width = "64px"; lifeControl.height = "64px"; lifeControl.left = 100 * i; this._lifesStackControl.addControl(lifeControl); } } /** * Called on the scene starts. */ public onStart(): void { this._registerStartGameEvent(); } /** * Called each frame. */ public onUpdate(): void { // ... } /** * THe player lose, let's retry :) */ public retry(): void { if (!this._isPlaying) { return; } this._gameMessageControl.isVisible = true; // Remove one life this._lifesStackControl.removeControl(this._lifesStackControl.children[0]); // Check lose the game if (!this._lifesStackControl.children.length) { this._gameMessageControl.isVisible = true; this._gameMessageControl.text = "You lose!"; this._isPlaying = false; } else { //this._ball.reset(); this._registerStartGameEvent(); } } /** * Called on the ball intersects a block to udpate the current score. */ public updateScore(): void { this._collidedBlocksCount++; this._counterControl.text = `Blocks ${this._collidedBlocksCount} / 8`; if (this._collidedBlocksCount === 8) { this._gameMessageControl.isVisible = true; this._gameMessageControl.text = "You won!!"; } } /** * Registers the keyboard event to start game. */ private _registerStartGameEvent(): void { // Register the space keyboard event to start the game. const spaceObservable = this.onKeyboardObservable.add((ev) => { if (ev.event.keyCode === 32) { // space bar this._ball.reset(); this._ball.applyStartImpulse(); this.onKeyboardObservable.remove(spaceObservable); this._gameMessageControl.isVisible = false; } }); } } <file_sep>/** * Generated by the Babylon.JS Editor v4.0.0-beta.7 */ import { Scene, Node, Mesh, SSAO2RenderingPipeline, DefaultRenderingPipeline, StandardRenderingPipeline, Vector2, Vector3, Vector4, Color3, Color4, SerializationHelper, } from "@babylonjs/core"; export type NodeScriptConstructor = (new (...args: any[]) => Node); export type GraphScriptConstructor = (new (scene: Scene) => any); export type ScriptMap = { [index: string]: { IsGraph?: boolean; default: (new (...args: any[]) => NodeScriptConstructor | GraphScriptConstructor); } }; /** * Requires the nedded scripts for the given nodes array and attach them. * @param nodes the array of nodes to attach script (if exists). */ function requireScriptForNodes(scriptsMap: ScriptMap, nodes: Node[] | Scene[]): void { const initializedNodes: { node: Node | Scene; exports: any; }[] = []; // Initialize nodes for (const n of nodes) { if (!n.metadata || !n.metadata.script || !n.metadata.script.name || n.metadata.script.name === "None") { continue; } const exports = scriptsMap[n.metadata.script.name]; if (!exports) { continue; } // Add prototype. const prototype = exports.default.prototype; for (const key in prototype) { if (!prototype.hasOwnProperty(key) || key === "constructor") { continue; } n[key] = prototype[key].bind(n); } // Call constructor prototype.constructor.call(n); // Call onInitialize prototype.onInitialize?.call(n); initializedNodes.push({ node: n, exports }); } // Configure initialized nodes for (const i of initializedNodes) { const n = i.node; const e = i.exports; const scene = i.node instanceof Scene ? i.node : i.node.getScene(); // Check start if (e.default.prototype.onStart) { scene.onBeforeRenderObservable.addOnce(() => n["onStart"]()); } // Check update if (e.default.prototype.onUpdate) { scene.onBeforeRenderObservable.add(() => n["onUpdate"]()); } // Check properties const properties = n.metadata.script.properties ?? { }; for (const key in properties) { const p = properties[key]; switch (p.type) { case "Vector2": n[key] = new Vector2(p.value.x, p.value.y); break; case "Vector3": n[key] = new Vector3(p.value.x, p.value.y, p.value.z); break; case "Vector4": n[key] = new Vector4(p.value.x, p.value.y, p.value.z, p.value.w); break; case "Color3": n[key] = new Color3(p.value.r, p.value.g, p.value.b); break; case "Color4": n[key] = new Color4(p.value.r, p.value.g, p.value.b, p.value.a); break; default: n[key] = p.value; break; } } // Check linked children. if (n instanceof Node) { const childrenLinks = (e.default as any)._ChildrenValues ?? []; for (const link of childrenLinks) { const child = n.getChildren((node => node.name === link.nodeName), true)[0]; n[link.propertyKey] = child; } } // Check linked nodes from scene. const sceneLinks = (e.default as any)._SceneValues ?? []; for (const link of sceneLinks) { const node = scene.getNodeByName(link.nodeName); n[link.propertyKey] = node; } // Check particle systems const particleSystemLinks = (e.default as any)._ParticleSystemValues ?? []; for (const link of particleSystemLinks) { const ps = scene.particleSystems.filter((ps) => ps.emitter === n && ps.name === link.particleSystemName)[0]; n[link.propertyKey] = ps; } // Check pointer events const pointerEvents = (e.default as any)._PointerValues ?? []; for (const event of pointerEvents) { scene.onPointerObservable.add((e) => { if (e.type !== event.type) { return; } if (!event.onlyWhenMeshPicked) { return n[event.propertyKey](e); } if (e.pickInfo?.pickedMesh === n) { n[event.propertyKey](e); } }); } // Check keyboard events const keyboardEvents = (e.default as any)._KeyboardValues ?? []; for (const event of keyboardEvents) { scene.onKeyboardObservable.add((e) => { if (event.type && e.type !== event.type) { return; } if (!event.keys.length) { return n[event.propertyKey](e); } if (event.keys.indexOf(e.event.keyCode) !== -1) { n[event.propertyKey](e); } }); } // Retrieve impostors if (n instanceof Mesh && !n.physicsImpostor) { n.physicsImpostor = n._scene.getPhysicsEngine()?.getImpostorForPhysicsObject(n); } } } /** * Attaches all available scripts on nodes of the given scene. * @param scene the scene reference that contains the nodes to attach scripts. */ export function attachScripts(scriptsMap: ScriptMap, scene: Scene): void { requireScriptForNodes(scriptsMap, scene.meshes); requireScriptForNodes(scriptsMap, scene.lights); requireScriptForNodes(scriptsMap, scene.cameras); requireScriptForNodes(scriptsMap, scene.transformNodes); requireScriptForNodes(scriptsMap, [scene]); // Graphs for (const scriptKey in scriptsMap) { const script = scriptsMap[scriptKey]; if (script.IsGraph) { const instance = new script.default(scene); scene.executeWhenReady(() => instance["onStart"]()); scene.onBeforeRenderObservable.add(() => instance["onUpdate"]()); } } } /** * Configures and attaches the post-processes of the given scene. * @param scene the scene where to create the post-processes and attach to its cameras. * @param rootUrl the root Url where to find extra assets used by pipelines. Should be the same as the scene. */ export function configurePostProcesses(scene: Scene, rootUrl: string = null): void { if (rootUrl === null || !scene.metadata?.postProcesses) { return; } // Load post-processes configuration const data = scene.metadata.postProcesses; if (data.ssao) { const ssao = SSAO2RenderingPipeline.Parse(data.ssao.json, scene, rootUrl); if (data.ssao.enabled) { scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(ssao.name, scene.cameras); } } if (data.standard) { const standard = StandardRenderingPipeline.Parse(data.standard.json, scene, rootUrl); if (!data.standard.enabled) { scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(standard.name, scene.cameras); } } if (data.default) { const def = DefaultRenderingPipeline.Parse(data.default.json, scene, rootUrl); if (!data.default.enabled) { scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(def.name, scene.cameras); } } } /** * Overrides the texture parser. */ (function overrideTextureParser(): void { const textureParser = SerializationHelper._TextureParser; SerializationHelper._TextureParser = (sourceProperty, scene, rootUrl) => { const texture = textureParser.call(SerializationHelper, sourceProperty, scene, rootUrl); if (sourceProperty.url) { texture.url = rootUrl + sourceProperty.url; } return texture; }; })(); import { PointerEventTypes, KeyboardEventTypes } from "@babylonjs/core"; export type VisiblityPropertyType = "number" | "string" | "boolean" | "Vector2" | "Vector3" | "Vector4" | "Color3" | "Color4" | "KeyMap"; /** * Sets the decorated member visible in the inspector. * @param type the property type. * @param name optional name to be shown in the editor's inspector. * @param defaultValue optional default value set in the TS code. */ export function visibleInInspector(type: VisiblityPropertyType, name?: string, defaultValue?: any): any { return (target: any, propertyKey: string | symbol) => { const ctor = target.constructor; ctor._InspectorValues = ctor._InspectorValues ?? []; ctor._InspectorValues.push({ type, name: name ?? propertyKey.toString(), propertyKey: propertyKey.toString(), defaultValue, }); }; } /** * Sets the decorated member linked to a child node. * @param nodeName defines the name of the node in children to retrieve. */ export function fromChildren(nodeName?: string): any { return (target: any, propertyKey: string | symbol) => { const ctor = target.constructor; ctor._ChildrenValues = ctor._ChildrenValues ?? []; ctor._ChildrenValues.push({ nodeName: nodeName ?? propertyKey.toString(), propertyKey: propertyKey.toString(), }); }; } /** * Sets the decorated member linked to a node in the scene. * @param nodeName defines the name of the node in the scene to retrieve. */ export function fromScene(nodeName?: string): any { return (target: any, propertyKey: string | symbol) => { const ctor = target.constructor; ctor._SceneValues = ctor._SceneValues ?? []; ctor._SceneValues.push({ nodeName: nodeName ?? propertyKey.toString(), propertyKey: propertyKey.toString(), }); } } /** * Sets the decorated member linked to a particle system which has the current Mesh attached. * @param particleSystemname the name of the attached particle system to retrieve. */ export function fromParticleSystems(particleSystemname?: string): any { return (target: any, propertyKey: string | symbol) => { const ctor = target.constructor; ctor._ParticleSystemValues = ctor._ParticleSystemValues ?? []; ctor._ParticleSystemValues.push({ particleSystemName: particleSystemname ?? propertyKey.toString(), propertyKey: propertyKey.toString(), }); } } /** * Sets the decorated member function to be called on the given pointer event is fired. * @param type the event type to listen to execute the decorated function. * @param onlyWhenMeshPicked defines wether or not the decorated function should be called only when the mesh is picked. default true. */ export function onPointerEvent(type: PointerEventTypes, onlyWhenMeshPicked: boolean = true): any { return (target: any, propertyKey: string | symbol) => { if (typeof(target[propertyKey]) !== "function") { throw new Error(`Decorated propery "${propertyKey.toString()}" in class "${target.constructor.name}" must be a function.`); } const ctor = target.constructor; ctor._PointerValues = ctor._PointerValues ?? []; ctor._PointerValues.push({ type, onlyWhenMeshPicked, propertyKey: propertyKey.toString(), }); }; } /** * Sets the decorated member function to be called on the given keyboard key(s) is/are pressed. * @param key the key or array of key to listen to execute the decorated function. */ export function onKeyboardEvent(key: number | number[], type?: KeyboardEventTypes): any { return (target: any, propertyKey: string | symbol) => { if (typeof(target[propertyKey]) !== "function") { throw new Error(`Decorated propery "${propertyKey.toString()}" in class "${target.constructor.name}" must be a function.`); } const ctor = target.constructor; ctor._KeyboardValues = ctor._KeyboardValues ?? []; ctor._KeyboardValues.push({ type, keys: Array.isArray(key) ? key : [key], propertyKey: propertyKey.toString(), }); }; } <file_sep>import { Mesh, PhysicsImpostor, Vector3 } from "@babylonjs/core"; import GameComponent from "./game"; import { fromScene } from "../tools"; export default class BallComponent extends Mesh { /** * Redefine the scene as GameComponent as the scene as a script attached to it. * @override */ public _scene: GameComponent; private _startPosition: Vector3 = null; private _startHeight: number = 0; @fromScene("player") private _player: Mesh; /** * Override constructor. * @warn do not fill. */ // @ts-ignore ignoring the super call as we don't want to re-init protected constructor() { } /** * Called on the node is being initialized. * This function is called immediatly after the constructor has been called. */ public onInitialize(): void { this.physicsImpostor = new PhysicsImpostor(this, PhysicsImpostor.SphereImpostor, { mass: 1, friction: 0, restitution: 1 }); this.physicsImpostor.sleep(); } /** * Called on the scene starts. */ public onStart(): void { this._startPosition = this.position.clone(); this._startHeight = this.position.y; } /** * Called each frame. */ public onUpdate(): void { this.position.y = this._startHeight; if (this.position.x < -30) { this._scene.retry(); } } /** * Resets the ball component. Called typically when the player loses the ball. */ public reset(): void { //this.position.copyFrom(this._startPosition); this.position.copyFrom(this._player.getAbsolutePosition()); this.physicsImpostor.setAngularVelocity(Vector3.Zero()); this.physicsImpostor.setLinearVelocity(Vector3.Zero()); this.physicsImpostor.sleep(); } /** * Applies the start impulse. This is called on the game is started when the user presses * the space key on the keyboard. */ public applyStartImpulse(): void { this.physicsImpostor.wakeUp(); this.applyImpulse(new Vector3(45, 0, 45), this.getAbsolutePosition()); } }
aeab020f6a268f3942fd80371f2994107e8abd20
[ "Markdown", "TypeScript" ]
7
TypeScript
remiceres/pingponggame_from_bjseditorv4beta2
41bb5d998008c07fe93ee8c449473adc19baa71a
0c41bc5c6ec10b9ac96ef9dbe3c077e810d36039
refs/heads/master
<repo_name>KumarReddy409/instagramclone<file_sep>/src/App.js import React from 'react'; import pic from './assets/instagram.png'; import Post from './Post' import './App.css'; function App() { return ( <div className="app"> <div className="header"> <img src={pic} className="headerimg" alt="hello"></img> </div> <Post username="kumar"></Post> <Post/> <Post/> </div> ); } export default App;
5d9208b505c75dd872bc837e6a67376aea88c784
[ "JavaScript" ]
1
JavaScript
KumarReddy409/instagramclone
e2bf838bf8e5ab303a4ea680a2d223011d0ed3c6
196dc054ac4928f9bc07235ec26df6ad4bb9ae58
refs/heads/master
<repo_name>sajadmsNew/react-usereducer<file_sep>/README.md # react-usereducer A React app that manages data using the reducer and context APIs. Based on the following tutorials: - [<NAME>: React Hooks: useReducer](https://www.youtube.com/watch?v=cKzrgB6MqqM) - [<NAME>: React Hooks: useContext](https://www.youtube.com/watch?v=u06qAON66iw) ## Get started ``` yarn yarn start open http://localhost:3000/ ``` <file_sep>/src/MyProvider.js import MyContext from "./MyContext" import { allData, perPage } from "./allData" import types from "./types" import reducer from "./reducer" import React from "react" export default function MyProvider({ children }) { const [state, dispatch] = React.useReducer(reducer, { loading: false, more: true, data: [], after: 0 }) const { loading, more, data, after } = state const loadMore = () => { dispatch({ type: types.start }) setTimeout(() => { const newData = allData.slice(after, after + perPage) dispatch({ type: types.loaded, newData }) }, 500) } return ( <MyContext.Provider value={{ loading, data, more, loadMore }}> {children} </MyContext.Provider> ) } <file_sep>/src/types.js export default { start: "START", loaded: "LOADED" } <file_sep>/src/LoadMore.js import MyContext from "./MyContext" import React from "react" export default function LoadMore() { const { loadMore } = React.useContext(MyContext) return ( <li> <button onClick={loadMore}>Load more</button> </li> ) } <file_sep>/src/reducer.js import { perPage } from "./allData" import types from "./types" export default (state, action) => { switch (action.type) { case types.start: return { ...state, loading: true } case types.loaded: return { ...state, loading: false, data: [...state.data, ...action.newData], more: action.newData.length === perPage, after: state.after + action.newData.length } default: throw new Error("Unknown action") } }
5de1e59e293f52d10378dde639153031d4c81c03
[ "Markdown", "JavaScript" ]
5
Markdown
sajadmsNew/react-usereducer
398701f108d3ac6c7d2b19f4e3c1586f1ae3c97d
e7918758eb882f722356b13fa8a125ee99db8f75
refs/heads/master
<repo_name>OmarBanoun/projet_stage<file_sep>/src/Form/SubscriptionType.php <?php namespace App\Form; use App\Entity\PsSubscriptionDetail; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; class SubscriptionType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('subscription') ->remove('start_date') ->remove('end_date') ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => PsSubscriptionDetail::class, ]); } }<file_sep>/src/Entity/PsAvis.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * PsAvis * * @ORM\Table(name="ps_avis") * @ORM\Entity */ class PsAvis { /** * @var int * * @ORM\Column(name="id", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="content", type="text", length=65535, nullable=false) */ private $content; /** * @var int * * @ORM\Column(name="annonceId", type="integer", nullable=false, options={"unsigned"=true}) */ private $annonceid; /** * @var int * * @ORM\Column(name="user_id", type="integer", nullable=false, options={"unsigned"=true}) */ private $userId; /** * @var string * * @ORM\Column(name="name_guest", type="string", length=20, nullable=false) */ private $nameGuest; /** * @var \DateTime * * @ORM\Column(name="date", type="datetime", nullable=false) */ private $date; public function getId(): ?int { return $this->id; } public function getContent(): ?string { return $this->content; } public function setContent(string $content): self { $this->content = $content; return $this; } public function getAnnonceid(): ?int { return $this->annonceid; } public function setAnnonceid(int $annonceid): self { $this->annonceid = $annonceid; return $this; } public function getUserId(): ?int { return $this->userId; } public function setUserId(int $userId): self { $this->userId = $userId; return $this; } public function getNameGuest(): ?string { return $this->nameGuest; } public function setNameGuest(string $nameGuest): self { $this->nameGuest = $nameGuest; return $this; } public function getDate(): ?\DateTimeInterface { return $this->date; } public function setDate(\DateTimeInterface $date): self { $this->date = $date; return $this; } } <file_sep>/src/Controller/ProfilController.php <?php namespace App\Controller; use App\Entity\PsUser; use App\Form\UserType; use App\Entity\Annonce; use App\Form\ProfilType; use App\Form\AnnonceType; use App\Entity\PsSubscription; use App\Entity\PsSubscriptionDetail; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Security; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Security\Http\Controller\UserValueResolver; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; class ProfilController extends AbstractController { /** * @Route("/inscription", name="inscription") */ public function inscription(Request $request, UserPasswordEncoderInterface $encoder): Response { // Mise en place des éléments pour renvoyer un formulaire à la vue $user = new PsUser(); $form = $this->createForm(UserType::class, $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // On ajoute le rôle user à l'utilisateur $user->setRoles(["ROLE_USER"]); // On prend en charge l'encodage du password // $passwordOrigine = $user->getPassword(); // $passwordEncode = $encoder->encodePassword($user, $passwordOrigine); $user->setPassword('<PASSWORD>'); // On récupère ensuite le manager d'entity qui permet les transactions avec la BDD $entityManager = $this->getDoctrine()->getManager(); // On mémorise le contact pour une mise en base de données future $entityManager->persist($user); // On envoie en bdd $entityManager->flush(); // return new Response("Utilisateur correctement ajouté"); return $this->redirectToRoute('home'); } // X. On retourne le rendu de la vue en lui passant en paramètre la création de la vue html correspondant au modèle du formulaire($form) return $this->render('profil/inscription.html.twig', [ "form" => $form->createView() ]); } /** * @Route("/profil", name="profil") */ public function profil(Security $security, Request $request, UserPasswordEncoderInterface $encoder, ValidatorInterface $validator, UserInterface $user): Response { // Avec le service Security, on récupère le user connecté pour obtenir ses infos à modifier $id = $security->getUser()->getId(); // On récupère la repository des User et on va chercher l'utilisateur par son id $repository = $this->getDoctrine()->getRepository(PsUser::class); $user = $repository->find($id); // Mise en place du formulaire $form = $this->createForm(ProfilType::class, $user); // On vérifie si on a des données postées dans la requête, ce qui signifierait que l'on est en mode vérification de formulaire et pas affichage simple $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // dd($user); // On récupère ensuite le manager d'entity qui permet les transactions avec la BDD $entityManager = $this->getDoctrine()->getManager(); // Prise en charge d'un changement potentiel de password $newPassword = $request->request->get('newPassword'); // On vérifie si la donnée n'est pas vide if(!empty($newPassword)){ // On encode le nouveau password $password = $encoder->encodePassword($user, $newPassword); // On met à jour la propriété du user $user->setPassword($password); } // On mémorise le contact pour une mise en base de données future $entityManager->persist($user); // On envoie en bdd $entityManager->flush(); // On met en place un flashMessage de Symfony $this->addFlash('success', 'Vos modifications ont bien été enregistrées.'); return $this->redirectToRoute('profil'); } $repository = $this->getDoctrine()->getRepository(Annonce::class); $annonces = $repository->findBy(array('user'=>$user)); $abonnement = $user->getSubscription(); // dump($userAbo); // dump('toto'); // Rendu return $this->render('profil/profil.html.twig', [ 'form' => $form->createView(), 'annonces' => $annonces, 'abonnement' => $abonnement, ]); } /** * @Route("/profil/new_annonce", name="new_annonce") */ public function addAnnonce(Security $security, Request $request): Response { $user = $security->getUser(); $addAnnonce = new Annonce(); // 2. On instancie un formulaire de contact $form = $this->createForm(AnnonceType::class, $addAnnonce); // 3. On hydrate le formulaire avec les potentielles données se trouvant dans la requête $form->handleRequest($request); // 4. On vérifie s'il y a des données conformes dans le formulaire if ($form->isSubmitted() && $form->isValid()) { // Mise en base de données $addAnnonce->setUser($user); // On demande au contrôleur ($this) de récupérer l'instance de Doctrine à l'aide de la méthode getDoctrine() héritée de AbstractController(le contrôleur étant // AbstractController) // On récupère ensuite le manager d'entity qui permet les transactions avec la BDD $entityManager = $this->getDoctrine()->getManager(); // On mémorise le contact pour une mise en base de données future $entityManager->persist($addAnnonce); // On envoie en bdd $entityManager->flush(); // On redirige vers la page de confirmation return $this->redirectToRoute('profil'); } if (!is_null($security->getUser())) { // Avec le service Security, on récupère le user connecté pour obtenir ses infos à modifier $id = $security->getUser()->getId(); // On récupère la repository des User et on va chercher l'utilisateur par son id $repository = $this->getDoctrine()->getRepository(PsUser::class); $user = $repository->find($id); return $this->render('profil/new_annonce.html.twig', [ 'form' => $form->createView(), ]); } } } <file_sep>/src/Repository/PsUserAttributRepository.php <?php namespace App\Repository; use App\Entity\PsUserattribut; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; /** * @method PsUserattribut|null find($id, $lockMode = null, $lockVersion = null) * @method PsUserattribut|null findOneBy(array $criteria, array $orderBy = null) * @method PsUserattribut[] findAll() * @method PsUserattribut[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class PsUserAttributRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, PsUserattribut::class); } // /** // * @return PsUserattribut[] Returns an array of PsUserattribut objects // */ /* public function findByExampleField($value) { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->orderBy('p.id', 'ASC') ->setMaxResults(10) ->getQuery() ->getResult() ; } */ /* public function findOneBySomeField($value): ?PsUserattribut { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->getQuery() ->getOneOrNullResult() ; } */ } <file_sep>/src/Repository/PsUserRepository.php <?php namespace App\Repository; use App\Entity\PsUser; use Doctrine\Persistence\ManagerRegistry; use Symfony\Component\Security\Core\User\UserInterface; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\User\PasswordUpgraderInterface; /** * @method PsUser|null find($id, $lockMode = null, $lockVersion = null) * @method PsUser|null findOneBy(array $criteria, array $orderBy = null) * @method PsUser[] findAll() * @method PsUser[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class PsUserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, PsUser::class); } /** * Used to upgrade (rehash) the user's password automatically over time. */ public function upgradePassword(UserInterface $user, string $newEncodedPassword): void { if (!$user instanceof PsUser) { throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user))); } $user->setPassword($newEncodedPassword); $this->_em->persist($user); $this->_em->flush(); } public function adminQuery() { return $this->createQueryBuilder('u') ->where('u.roles LIKE :role') ->setParameter('role', '%"' . 'ROLE_ADMIN' . '"%'); } static public function findByExampleField( PsUserRepository $repository) { return $repository->createQueryBuilder('u') ->andWhere('u.roles LIKE :role') ->setParameter('role', 'ROLE_ADMIN') ->getQuery() ->getResult() ; } // /** // * @return PsUser[] Returns an array of PsUser objects // */ /* public function findByExampleField($value) { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->orderBy('p.id', 'ASC') ->setMaxResults(10) ->getQuery() ->getResult() ; } */ /* public function findOneBySomeField($value): ?PsUser { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->getQuery() ->getOneOrNullResult() ; } */ } <file_sep>/src/Repository/PsSubscriptionRepository.php <?php namespace App\Repository; use App\Entity\PsSubscription; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; /** * @method PsSubscription|null find($id, $lockMode = null, $lockVersion = null) * @method PsSubscription|null findOneBy(array $criteria, array $orderBy = null) * @method PsSubscription[] findAll() * @method PsSubscription[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class PsSubscriptionRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, PsSubscription::class); } // /** // * @return PsSubscription[] Returns an array of PsSubscription objects // */ /* public function findByExampleField($value) { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->orderBy('p.id', 'ASC') ->setMaxResults(10) ->getQuery() ->getResult() ; } */ /* public function findOneBySomeField($value): ?PsSubscription { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->getQuery() ->getOneOrNullResult() ; } */ } <file_sep>/src/Entity/PsSubscription.php <?php namespace App\Entity; use Serializable; use App\Entity\PsUser; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\Collection; use App\Repository\PsSubscriptionRepository; use Symfony\Component\HttpFoundation\File\File; use Doctrine\Common\Collections\ArrayCollection; use Vich\UploaderBundle\Mapping\Annotation as Vich; /** * @ORM\Entity(repositoryClass=PsSubscriptionRepository::class) * @Vich\Uploadable * @ORM\HasLifecycleCallbacks */ class PsSubscription implements Serializable { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $name; /** * @ORM\Column(type="string", length=10) */ private $prix; /** * @ORM\Column(type="text") */ private $description; /** * @ORM\Column(type="string", length=100) */ private $image; /** * NOTE: This is not a mapped field of entity metadata, just a simple property. * * @Vich\UploadableField(mapping="subscription_upload", fileNameProperty="image", ) * * @var File|null */ private $imageFile; public function serialize() { $this->imageFile = base64_encode($this->imageFile); } public function unserialize($serialized) { $this->imageFile = base64_decode($this->imageFile); } /** * @ORM\OneToMany(targetEntity=PsUser::class, mappedBy="subscription") */ private $Users; /** * @ORM\Column(type="dateinterval") */ private $duration; /** * @ORM\OneToMany(targetEntity=PsSubscriptionDetail::class, mappedBy="subscription") */ private $PsSubscriptionDetail; public function __toString() { return $this->name; } public function __construct() { $this->Users = new ArrayCollection(); $this->PsSubscriptionDetail = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getPrix(): ?string { return $this->prix; } public function setPrix(string $prix): self { $this->prix = $prix; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } public function getImage(): ?string { return $this->image; } public function setImage(string $image): self { $this->image = $image; return $this; } public function setImageFile(?File $imageFile = null): void { $this->imageFile = $imageFile; if (null !== $imageFile) { // It is required that at least one field changes if you are using doctrine // otherwise the event listeners won't be called and the file is lost $this->updatedAt = new \DateTimeImmutable(); } } public function getImageFile(): ?File { return $this->imageFile; } /** * @return Collection|PsUser[] */ public function getUsers(): Collection { return $this->Users; } public function addUser(PsUser $user): self { if (!$this->Users->contains($user)) { $this->Users[] = $user; $user->setSubscription($this); } return $this; } public function removeUser(PsUser $user): self { if ($this->Users->removeElement($user)) { // set the owning side to null (unless already changed) if ($user->getSubscription() === $this) { $user->setSubscription(null); } } return $this; } public function getDuration(): ?\DateInterval { return $this->duration; } public function setDuration(\DateInterval $duration): self { $this->duration = $duration; return $this; } /** * @return Collection|PsSubscriptionDetail[] */ public function getPsSubscriptionDetail(): Collection { return $this->PsSubscriptionDetail; } public function addPsSubscriptionDetail(PsSubscriptionDetail $psSubscriptionDetail): self { if (!$this->PsSubscriptionDetail->contains($psSubscriptionDetail)) { $this->PsSubscriptionDetail[] = $psSubscriptionDetail; $psSubscriptionDetail->setSubscription($this); } return $this; } public function removePsSubscriptionDetail(PsSubscriptionDetail $psSubscriptionDetail): self { if ($this->PsSubscriptionDetail->removeElement($psSubscriptionDetail)) { // set the owning side to null (unless already changed) if ($psSubscriptionDetail->getSubscription() === $this) { $psSubscriptionDetail->setSubscription(null); } } return $this; } } <file_sep>/src/Entity/PsUserattribut.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * PsUserattribut * * @ORM\Table(name="ps_userattribut") * @ORM\Entity */ class PsUserattribut { /** * @var int * * @ORM\Column(name="id", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var int * * @ORM\Column(name="userId", type="integer", nullable=false, options={"unsigned"=true}) */ private $userid; /** * @var string|null * * @ORM\Column(name="telephone", type="string", length=20, nullable=true) */ private $telephone; /** * @var string|null * * @ORM\Column(name="email", type="string", length=150, nullable=true) */ private $email; /** * @var string|null * * @ORM\Column(name="fax", type="string", length=20, nullable=true) */ private $fax; public function getId(): ?int { return $this->id; } public function getUserid(): ?int { return $this->userid; } public function setUserid(int $userid): self { $this->userid = $userid; return $this; } public function getTelephone(): ?string { return $this->telephone; } public function setTelephone(?string $telephone): self { $this->telephone = $telephone; return $this; } public function getEmail(): ?string { return $this->email; } public function setEmail(?string $email): self { $this->email = $email; return $this; } public function getFax(): ?string { return $this->fax; } public function setFax(?string $fax): self { $this->fax = $fax; return $this; } } <file_sep>/src/Repository/PsAdminRepository.php <?php namespace App\Repository; use App\Entity\PsAdmin; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; /** * @method PsAdmin|null find($id, $lockMode = null, $lockVersion = null) * @method PsAdmin|null findOneBy(array $criteria, array $orderBy = null) * @method PsAdmin[] findAll() * @method PsAdmin[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class PsAdminRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, PsAdmin::class); } // /** // * @return PsAdmin[] Returns an array of PsAdmin objects // */ /* public function findByExampleField($value) { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->orderBy('p.id', 'ASC') ->setMaxResults(10) ->getQuery() ->getResult() ; } */ /* public function findOneBySomeField($value): ?PsAdmin { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->getQuery() ->getOneOrNullResult() ; } */ } <file_sep>/src/Controller/AnnonceController.php <?php namespace App\Controller; use App\Entity\PsUser; use App\Entity\Annonce; use App\Form\AnnonceType; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Security; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\File\Exception\FileException; class AnnonceController extends AbstractController { /** * @Route("/annonce", name="annonce") */ public function index(): Response { $repository = $this->getDoctrine()->getRepository(Annonce::class); $annonces = $repository->findAll(); return $this->render('annonce/index.html.twig', [ 'annonces' => $annonces, ]); } /** * @Route("/annonce/coiffure", name="annonce_coiffure") */ public function coiffure(): Response { $repository = $this->getDoctrine()->getRepository(Annonce::class); $annonces = $repository->findBy(array("category" => 1)); return $this->render('annonce/index.html.twig', [ 'annonces' => $annonces, ]); } /** * @Route("/annonce/traiteur", name="annonce_traiteur") */ public function traiteur(): Response { $repository = $this->getDoctrine()->getRepository(Annonce::class); $annonces = $repository->findBy(array("category" => 2)); return $this->render('annonce/index.html.twig', [ 'annonces' => $annonces, ]); } /** * @Route("/annonce/salle", name="annonce_salle") */ public function salle(): Response { $repository = $this->getDoctrine()->getRepository(Annonce::class); $annonces = $repository->findBy(array("category" => 3)); return $this->render('annonce/index.html.twig', [ 'annonces' => $annonces, ]); } /** * Requête à la base de données pour obtenir le détail d'une annonce * @Route("/annonce/{slug}", name="annonce-detail") * @return Response */ public function annonceDetail($slug): Response { $repository = $this->getDoctrine()->getRepository(Annonce::class); $annonce = $repository->find($slug); return $this->render('annonce/annonce_detail.html.twig', ["annonce" => $annonce]); } /** * @Route("/modifier-annonce/{id}", name="annonce-update") */ public function editAnnonce(Annonce $annonce, Request $request): Response { // Mise en place du formulaire $form = $this->createForm(AnnonceType::class, $annonce); // On vérifie si on a des données postées dans la requête, ce qui signifierait que l'on est en mode vérification de formulaire et pas affichage simple $form->handleRequest($request); dump($request->query->get('parameters')); $test = $request->get('parameters'); dump($test); if ($form->isSubmitted() && $form->isValid()) { $annonce = $form->getData(); $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($annonce); $entityManager->flush(); // On met en place un flashMessage de Symfony $this->addFlash('success', 'Vos modifications ont bien été enregistrées.'); return $this->redirectToRoute('profil', [ 'id' => $annonce->getId(), ]); } return $this->render('profil/update_annonce.html.twig', [ 'form' => $form->createView(), ]); } // remove an article /** * @Route("annonce/supprimer/{id}", name="annonce-delete") * @param int $id */ public function deleteAnnonce(int $id): Response { $annonce = $this->getDoctrine()->getRepository(Annonce::class)->find($id); $manager = $this->getDoctrine()->getManager(); $manager->remove($annonce); $manager->flush(); $this->addFlash('success', 'L\'article a bien été supprimé'); return $this->redirectToRoute('profil'); } } <file_sep>/src/Entity/PsAnnonce.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\HttpFoundation\File\File; use Vich\UploaderBundle\Mapping\Annotation as Vich; /** * PsAnnonce * * @ORM\Table(name="ps_annonce") * @ORM\Entity * @Vich\Uploadable * @ORM\HasLifecycleCallbacks */ class PsAnnonce { /** * @var int * * @ORM\Column(name="id", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="description", type="text", length=65535, nullable=false) */ private $description; /** * @var int * * @ORM\Column(name="societymainId", type="integer", nullable=false, options={"unsigned"=true}) */ private $societymainid; /** * @var int * * @ORM\Column(name="societyannexeId", type="integer", nullable=false, options={"unsigned"=true}) */ private $societyannexeid; /** * @var string * * @ORM\Column(name="title", type="string", length=100, nullable=false) */ private $title; /** * @var \DateTime * * @ORM\Column(name="created_at", type="datetime", nullable=false) */ private $createdAt; /** * @var string * * @ORM\Column(name="image", type="string", length=50, nullable=false) */ private $image; /** * NOTE: This is not a mapped field of entity metadata, just a simple property. * * @Vich\UploadableField(mapping="annonce", fileNameProperty="image", ) * * @var File|null */ private $imageFile; public function getId(): ?int { return $this->id; } public function getDescription(): ?string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } public function getSocietymainid(): ?int { return $this->societymainid; } public function setSocietymainid(int $societymainid): self { $this->societymainid = $societymainid; return $this; } public function getSocietyannexeid(): ?int { return $this->societyannexeid; } public function setSocietyannexeid(int $societyannexeid): self { $this->societyannexeid = $societyannexeid; return $this; } public function getTitle(): ?string { return $this->title; } public function setTitle(string $title): self { $this->title = $title; return $this; } public function getCreatedAt(): ?\DateTimeInterface { return $this->createdAt; } public function setCreatedAt(\DateTimeInterface $createdAt): self { $this->createdAt = $createdAt; return $this; } public function getImage(): ?string { return $this->image; } public function setImage(string $image): self { $this->image = $image; return $this; } public function setImageFile(?File $imageFile = null): void { $this->imageFile = $imageFile; if (null !== $imageFile) { // It is required that at least one field changes if you are using doctrine // otherwise the event listeners won't be called and the file is lost $this->updatedAt = new \DateTimeImmutable(); } } public function getImageFile(): ?File { return $this->imageFile; } } <file_sep>/src/Entity/PsContrat.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * PsContrat * * @ORM\Table(name="ps_contrat") * @ORM\Entity */ class PsContrat { /** * @var int * * @ORM\Column(name="id", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="label", type="string", length=200, nullable=false) */ private $label; /** * @var string * * @ORM\Column(name="reference", type="string", length=50, nullable=false) */ private $reference; /** * @var int * * @ORM\Column(name="societymainId", type="integer", nullable=false, options={"unsigned"=true}) */ private $societymainid; /** * @var int|null * * @ORM\Column(name="societyannexeId", type="integer", nullable=true, options={"unsigned"=true}) */ private $societyannexeid; /** * @var string * * @ORM\Column(name="pathcontrat", type="string", length=250, nullable=false) */ private $pathcontrat; /** * @var \DateTime * * @ORM\Column(name="createdate", type="datetime", nullable=false) */ private $createdate; /** * @var \DateTime|null * * @ORM\Column(name="updatedate", type="datetime", nullable=true) */ private $updatedate; /** * @var int * * @ORM\Column(name="status", type="integer", nullable=false, options={"unsigned"=true}) */ private $status; public function getId(): ?int { return $this->id; } public function getLabel(): ?string { return $this->label; } public function setLabel(string $label): self { $this->label = $label; return $this; } public function getReference(): ?string { return $this->reference; } public function setReference(string $reference): self { $this->reference = $reference; return $this; } public function getSocietymainid(): ?int { return $this->societymainid; } public function setSocietymainid(int $societymainid): self { $this->societymainid = $societymainid; return $this; } public function getSocietyannexeid(): ?int { return $this->societyannexeid; } public function setSocietyannexeid(?int $societyannexeid): self { $this->societyannexeid = $societyannexeid; return $this; } public function getPathcontrat(): ?string { return $this->pathcontrat; } public function setPathcontrat(string $pathcontrat): self { $this->pathcontrat = $pathcontrat; return $this; } public function getCreatedate(): ?\DateTimeInterface { return $this->createdate; } public function setCreatedate(\DateTimeInterface $createdate): self { $this->createdate = $createdate; return $this; } public function getUpdatedate(): ?\DateTimeInterface { return $this->updatedate; } public function setUpdatedate(?\DateTimeInterface $updatedate): self { $this->updatedate = $updatedate; return $this; } public function getStatus(): ?int { return $this->status; } public function setStatus(int $status): self { $this->status = $status; return $this; } } <file_sep>/src/Entity/PsUser.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\ArrayCollection; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface; /** * PsUser * * @ORM\Table(name="ps_user") * @ORM\Entity */ class PsUser implements UserInterface { /** * @var int * * @ORM\Column(name="id", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @ORM\Column(type="json") */ private $role = []; /** * @var string * * @ORM\Column(name="name", type="string", length=150, nullable=false) */ private $name; /** * @var string * * @ORM\Column(name="firstname", type="string", length=150, nullable=false) */ private $firstname; /** * @var string * * @ORM\Column(name="login", type="string", length=150, nullable=false) */ private $login; /** * @var string The hashed password * * @ORM\Column(name="password", type="string", length=250, nullable=false) */ private $password; /** * @var string * * @ORM\Column(name="number", type="string", length=10, nullable=false) */ private $number; /** * @var string|null * * @ORM\Column(name="number_complement", type="string", length=5, nullable=true) */ private $numberComplement; /** * @var string * * @ORM\Column(name="street", type="string", length=250, nullable=false) */ private $street; /** * @var string * * @ORM\Column(name="city", type="string", length=150, nullable=false) */ private $city; /** * @var string * * @ORM\Column(name="country", type="string", length=150, nullable=false) */ private $country; /** * @var string * * @ORM\Column(name="postal_code", type="string", length=20, nullable=false) */ private $postalCode; /** * @ORM\OneToMany(targetEntity=Annonce::class, mappedBy="user", orphanRemoval=true) */ private $annonces; /** * @ORM\ManyToOne(targetEntity=PsSubscription::class, inversedBy="Users") */ private $subscription; /** * @return string */ public function __toString() { return (string) $this->getId(); } public function __construct() { $this->annonces = new ArrayCollection(); $this->subscription = new ArrayCollection(); } public function getId(): ?int { return $this->id; } /** * A visual identifier that represents this user. * * @see UserInterface */ public function getUsername(): string { return (string) $this->login; } /** * Returning a salt is only needed, if you are not using a modern * hashing algorithm (e.g. bcrypt or sodium) in your security.yaml. * * @see UserInterface */ public function getSalt(): ?string { return null; } /** * @see UserInterface */ public function eraseCredentials() { // If you store any temporary, sensitive data on the user, clear it here // $this->plainPassword = null; } /** * @see UserInterface */ public function getRoles(): array { $role = $this->role; // guarantee every user at least has ROLE_USER $role[] = 'ROLE_USER'; return array_unique($role); } public function setRoles(array $role): self { $this->role = $role; return $this; } public function getRole(): ?array { return $this->role; } public function setRole(array $role): self { $this->role = $role; return $this; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getFirstname(): ?string { return $this->firstname; } public function setFirstname(string $firstname): self { $this->firstname = $firstname; return $this; } public function getLogin(): ?string { return $this->login; } public function setLogin(string $login): self { $this->login = $login; return $this; } /** * @see UserInterface */ public function getPassword(): string { return (string) $this->password; } public function setPassword(string $password): self { global $kernel; if (method_exists($kernel, 'getKernel')) $kernel = $kernel->getKernel(); $this->password = $kernel->getContainer()->get('security.password_encoder')->encodePassword($this, $password); return $this; } public function getNumber(): ?string { return $this->number; } public function setNumber(string $number): self { $this->number = $number; return $this; } public function getNumberComplement(): ?string { return $this->numberComplement; } public function setNumberComplement(?string $numberComplement): self { $this->numberComplement = $numberComplement; return $this; } public function getStreet(): ?string { return $this->street; } public function setStreet(string $street): self { $this->street = $street; return $this; } public function getCity(): ?string { return $this->city; } public function setCity(string $city): self { $this->city = $city; return $this; } public function getCountry(): ?string { return $this->country; } public function setCountry(string $country): self { $this->country = $country; return $this; } public function getPostalCode(): ?string { return $this->postalCode; } public function setPostalCode(string $postalCode): self { $this->postalCode = $postalCode; return $this; } // Relation /** * @return Collection|Annonce[] */ public function getAnnonces(): Collection { return $this->annonces; } public function addAnnonce(Annonce $annonce): self { if (!$this->annonces->contains($annonce)) { $this->annonces[] = $annonce; $annonce->setUser($this); } return $this; } public function removeAnnonce(Annonce $annonce): self { if ($this->annonces->removeElement($annonce)) { // set the owning side to null (unless already changed) if ($annonce->getUser() === $this) { $annonce->setUser(null); } } return $this; } public function getSubscription(): ?psSubscription { return $this->subscription; } public function setSubscription(?psSubscription $subscription): self { $this->subscription = $subscription; return $this; } /** * @return Collection|PsSubscription[] */ public function getSubscriptions(): Collection { return $this->subscriptions; } public function addSubscription(PsSubscription $subscription): self { if (!$this->subscriptions->contains($subscription)) { $this->subscriptions[] = $subscription; } return $this; } public function removeSubscription(PsSubscription $subscription): self { if ($this->annonces->removeElement($subscription)) { // set the owning side to null (unless already changed) if ($subscription->getUsers() === $this) { } } return $this; } } <file_sep>/src/Entity/PsCategory.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\ArrayCollection; /** * PsCategory * * @ORM\Table(name="ps_category") * @ORM\Entity */ class PsCategory { /** * @var int * * @ORM\Column(name="id", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=50, nullable=false) */ private $name; /** * @var int * * @ORM\Column(name="parentId", type="integer", nullable=false, options={"unsigned"=true}) */ private $parentid; /** * @var string * * @ORM\Column(name="toto", type="string", length=50, nullable=false) */ private $toto; /** * @ORM\Column(type="string", length=255) */ private $totoBis; public function __construct() { $this->annonces = new ArrayCollection(); } public function __toString() { return $this->nom; } public function getId(): ?int { return $this->id; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getParentid(): ?int { return $this->parentid; } public function setParentid(int $parentid): self { $this->parentid = $parentid; return $this; } /** * @return Collection|Annonce[] */ public function getAnnonce(): Collection { return $this->postChats; } public function addAnnonce(PsAnnonce $annonce): self { if (!$this->postChats->contains($annonce)) { $this->postChats[] = $annonce; $annonce->setCategorie($this); } return $this; } public function removePostChat(PsAnnonce $annonce): self { if ($this->postChats->removeElement($annonce)) { // set the owning side to null (unless already changed) if ($annonce->getCategorie() === $this) { $annonce->setCategorie(null); } } return $this; } public function getTotoBis(): ?string { return $this->totoBis; } public function setTotoBis(string $totoBis): self { $this->totoBis = $totoBis; return $this; } } <file_sep>/src/Entity/Annonce.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use App\Repository\AnnonceRepository; use Doctrine\Common\Collections\Collection; use Symfony\Component\HttpFoundation\File\File; use Doctrine\Common\Collections\ArrayCollection; use Vich\UploaderBundle\Mapping\Annotation as Vich; /** * @ORM\Entity(repositoryClass=AnnonceRepository::class) * @Vich\Uploadable * @ORM\HasLifecycleCallbacks */ class Annonce { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $title; /** * @ORM\Column(type="text") */ private $description; /** * @ORM\Column(type="string", length=50) */ private $image; /** * NOTE: This is not a mapped field of entity metadata, just a simple property. * * @Vich\UploadableField(mapping="annonce_upload", fileNameProperty="image", ) * * @var File|null */ private $imageFile; /** * @ORM\Column(type="datetime") */ private $createdAt; /** * @ORM\ManyToOne(targetEntity=PsUser::class, inversedBy="annonces") * @ORM\JoinColumn(nullable=false) */ private $user; /** * @ORM\ManyToOne(targetEntity=CategoryAnnonce::class, inversedBy="annonces") * @ORM\JoinColumn(nullable=false) */ private $category; public function getId(): ?int { return $this->id; } public function getTitle(): ?string { return $this->title; } public function setTitle(string $title): self { $this->title = $title; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } public function getImage(): ?string { return $this->image; } public function setImage(?string $image): self { $this->image = $image; return $this; } public function setImageFile(?File $imageFile = null): void { $this->imageFile = $imageFile; if (null !== $imageFile) { // It is required that at least one field changes if you are using doctrine // otherwise the event listeners won't be called and the file is lost $this->updatedAt = new \DateTimeImmutable(); } } public function getImageFile(): ?File { return $this->imageFile; } public function getCreatedAt(): ?\DateTimeInterface { return $this->createdAt; } public function setCreatedAt(\DateTimeInterface $createdAt): self { $this->createdAt = $createdAt; return $this; } /** * @ORM\PrePersist * @ORM\PreUpdate */ public function updatedTimestamps(): void { if ($this->getCreatedAt() === null) { $this->setCreatedAt(new \DateTime('now')); } } public function getUser(): ?PsUser { return $this->user; } public function setUser(?PsUser $user): self { $this->user = $user; return $this; } public function getCategory(): ?CategoryAnnonce { return $this->category; } public function setCategory(?CategoryAnnonce $category): self { $this->category = $category; return $this; } } <file_sep>/src/Controller/SubscriptionController.php <?php namespace App\Controller; use App\Entity\PsSubscription; use App\Form\SubscriptionType; use App\Entity\PsSubscriptionDetail; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; class SubscriptionController extends AbstractController { /** * @Route("/subscription", name="subscription") */ public function index(): Response { $repository = $this->getDoctrine()->getRepository(PsSubscription::class); $premium = $repository->findOneBy(array("name" => "premium")); $decouverte = $repository->findOneBy(array("name" => "découverte")); return $this->render('subscription/index.html.twig', [ 'premium' => $premium, 'decouverte' => $decouverte, ]); } /** * @Route("/subscription/form", name="subscription_form") */ public function sub(Request $request): Response { $repository = $this->getDoctrine()->getRepository(PsSubscription::class); $premium = $repository->findOneBy(array("name" => "premium")); $subscription = new PsSubscriptionDetail(); $startDate = new \DateTime('now'); $endDate = clone $startDate; $endDate->add($premium->getDuration()); $now = new \DateTime('now'); $expire = $now > $endDate; if ($expire){ $subscription->setIsExpired(true); }else{ $subscription->setIsExpired(false); } dump($expire); $form = $this->createForm(SubscriptionType::class, $subscription); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $subscription->setStartDate($startDate); $subscription->setEndDate($endDate); // $subscription->setIsExpired($isExpired); $em = $this->getDoctrine()->getManager(); $em->persist($subscription); $em->flush(); // $this->addFlash('success', 'Vos modifications ont bien été enregistrées.'); return $this->redirectToRoute('home'); } return $this->render('subscription/form.html.twig', [ 'form' => $form->createView(), ]); } } <file_sep>/src/Repository/PsContratRepository.php <?php namespace App\Repository; use App\Entity\PsContrat; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; /** * @method PsContrat|null find($id, $lockMode = null, $lockVersion = null) * @method PsContrat|null findOneBy(array $criteria, array $orderBy = null) * @method PsContrat[] findAll() * @method PsContrat[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class PsContratRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, PsContrat::class); } // /** // * @return PsContrat[] Returns an array of PsContrat objects // */ /* public function findByExampleField($value) { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->orderBy('p.id', 'ASC') ->setMaxResults(10) ->getQuery() ->getResult() ; } */ /* public function findOneBySomeField($value): ?PsContrat { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->getQuery() ->getOneOrNullResult() ; } */ } <file_sep>/src/Entity/PsFactureprestation.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * PsFactureprestation * * @ORM\Table(name="ps_factureprestation") * @ORM\Entity */ class PsFactureprestation { /** * @var int * * @ORM\Column(name="id", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var int * * @ORM\Column(name="prestationId", type="integer", nullable=false, options={"unsigned"=true}) */ private $prestationid; /** * @var int * * @ORM\Column(name="factureId", type="integer", nullable=false, options={"unsigned"=true}) */ private $factureid; /** * @var int|null * * @ORM\Column(name="devisId", type="integer", nullable=true, options={"unsigned"=true}) */ private $devisid; public function getId(): ?int { return $this->id; } public function getPrestationid(): ?int { return $this->prestationid; } public function setPrestationid(int $prestationid): self { $this->prestationid = $prestationid; return $this; } public function getFactureid(): ?int { return $this->factureid; } public function setFactureid(int $factureid): self { $this->factureid = $factureid; return $this; } public function getDevisid(): ?int { return $this->devisid; } public function setDevisid(?int $devisid): self { $this->devisid = $devisid; return $this; } } <file_sep>/src/Entity/PsImageannonce.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * PsImageannonce * * @ORM\Table(name="ps_imageannonce") * @ORM\Entity */ class PsImageannonce { /** * @var int * * @ORM\Column(name="id", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var int * * @ORM\Column(name="imageId", type="integer", nullable=false, options={"unsigned"=true}) */ private $imageid; /** * @var int * * @ORM\Column(name="annonceId", type="integer", nullable=false, options={"unsigned"=true}) */ private $annonceid; public function getId(): ?int { return $this->id; } public function getImageid(): ?int { return $this->imageid; } public function setImageid(int $imageid): self { $this->imageid = $imageid; return $this; } public function getAnnonceid(): ?int { return $this->annonceid; } public function setAnnonceid(int $annonceid): self { $this->annonceid = $annonceid; return $this; } } <file_sep>/src/Form/AnnonceType.php <?php namespace App\Form; use App\Entity\Annonce; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\FileType; class AnnonceType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->remove('user') ->add('title') ->add('description') ->remove('createdAt') ->add('category') ->add('imageFile', FileType::class, ['required'=>true]) ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Annonce::class, ]); } }<file_sep>/src/Entity/PsSubscriptionDetail.php <?php namespace App\Entity; use App\Repository\PsSubscriptionDetailRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=PsSubscriptionDetailRepository::class) * @ORM\HasLifecycleCallbacks */ class PsSubscriptionDetail { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="datetime", nullable=true) */ private $startDate; /** * @ORM\Column(type="datetime", nullable=true) */ private $endDate; /** * @ORM\ManyToOne(targetEntity=PsSubscription::class, inversedBy="PsSubscriptionDetail") */ private $subscription; /** * @ORM\Column(type="boolean", nullable=true) */ private $isExpired; public function getId(): ?int { return $this->id; } public function getStartDate(): ?\DateTimeInterface { return $this->startDate; } public function setStartDate(?\DateTimeInterface $startDate): self { $this->startDate = $startDate; return $this; } /** * @ORM\PrePersist * @ORM\PreUpdate */ public function updatedTimestamps(): void { if ($this->getStartDate() === null) { $this->setStartDate(new \DateTime('now')); } if ($this->getEndDate() === null) { $this->setEndDate(new \DateTime('now')); } } public function getEndDate(): ?\DateTimeInterface { return $this->endDate; } public function setEndDate(?\DateTimeInterface $endDate): self { $this->endDate = $endDate; return $this; } public function getSubscription(): ?PsSubscription { return $this->subscription; } public function setSubscription(?PsSubscription $subscription): self { $this->subscription = $subscription; return $this; } public function getIsExpired(): ?bool { return $this->isExpired; } public function setIsExpired(?bool $isExpired): self { $this->isExpired = $isExpired; return $this; } } <file_sep>/src/Entity/PsMain.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\HttpFoundation\File\File; use Vich\UploaderBundle\Mapping\Annotation as Vich; /** * PsMain * * @ORM\Table(name="ps_main") * @ORM\Entity * @Vich\Uploadable * @ORM\HasLifecycleCallbacks */ class PsMain { /** * @var int * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="small_title", type="string", length=100, nullable=false) */ private $smallTitle; /** * @var string * * @ORM\Column(name="title", type="string", length=100, nullable=false) */ private $title; /** * @var string * * @ORM\Column(name="image", type="string", length=50, nullable=false) */ private $image; /** * NOTE: This is not a mapped field of entity metadata, just a simple property. * * @Vich\UploadableField(mapping="home_upload", fileNameProperty="image", ) * * @var File|null */ private $imageFile; /** * @var bool * * @ORM\Column(name="active", type="boolean", nullable=false) */ private $active; /** * @var \DateTime * * @ORM\Column(name="updated_at", type="datetime", nullable=false) */ private $updatedAt; public function getId(): ?int { return $this->id; } public function getSmallTitle(): ?string { return $this->smallTitle; } public function setSmallTitle(string $smallTitle): self { $this->smallTitle = $smallTitle; return $this; } public function getTitle(): ?string { return $this->title; } public function setTitle(string $title): self { $this->title = $title; return $this; } public function getImage(): ?string { return $this->image; } public function setImage(string $image): self { $this->image = $image; return $this; } public function setImageFile(?File $imageFile = null): void { $this->imageFile = $imageFile; if (null !== $imageFile) { // It is required that at least one field changes if you are using doctrine // otherwise the event listeners won't be called and the file is lost $this->updatedAt = new \DateTimeImmutable(); } } public function getImageFile(): ?File { return $this->imageFile; } public function getActive(): ?bool { return $this->active; } public function setActive(bool $active): self { $this->active = $active; return $this; } public function getUpdatedAt(): ?\DateTimeInterface { return $this->updatedAt; } public function setUpdatedAt(\DateTimeInterface $updatedAt): self { $this->updatedAt = $updatedAt; return $this; } } <file_sep>/src/Repository/PsPrestationRepository.php <?php namespace App\Repository; use App\Entity\PsPrestation; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; /** * @method PsPrestation|null find($id, $lockMode = null, $lockVersion = null) * @method PsPrestation|null findOneBy(array $criteria, array $orderBy = null) * @method PsPrestation[] findAll() * @method PsPrestation[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class PsPrestationRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, PsPrestation::class); } // /** // * @return PsPrestation[] Returns an array of PsPrestation objects // */ /* public function findByExampleField($value) { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->orderBy('p.id', 'ASC') ->setMaxResults(10) ->getQuery() ->getResult() ; } */ /* public function findOneBySomeField($value): ?PsPrestation { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->getQuery() ->getOneOrNullResult() ; } */ } <file_sep>/migrations/Version20210430092302.php <?php declare(strict_types=1); namespace DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20210430092302 extends AbstractMigration { public function getDescription(): string { return ''; } public function up(Schema $schema): void { // this up() migration is auto-generated, please modify it to your needs $this->addSql('CREATE TABLE ps_subscription_detail (id INT AUTO_INCREMENT NOT NULL, subscription_id INT DEFAULT NULL, start_date DATETIME DEFAULT NULL, end_date DATETIME DEFAULT NULL, INDEX IDX_848567EA9A1887DC (subscription_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); $this->addSql('ALTER TABLE ps_subscription_detail ADD CONSTRAINT FK_848567EA9A1887DC FOREIGN KEY (subscription_id) REFERENCES ps_subscription (id)'); } public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs $this->addSql('DROP TABLE ps_subscription_detail'); } } <file_sep>/src/Entity/PsAnnoncecategory.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * PsAnnoncecategory * * @ORM\Table(name="ps_annoncecategory") * @ORM\Entity */ class PsAnnoncecategory { /** * @var int * * @ORM\Column(name="annonceId", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $annonceid; /** * @var int * * @ORM\Column(name="categoryId", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $categoryid; public function getAnnonceid(): ?int { return $this->annonceid; } public function getCategoryid(): ?int { return $this->categoryid; } } <file_sep>/src/Entity/PsSocietyannexe.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * PsSocietyannexe * * @ORM\Table(name="ps_societyannexe") * @ORM\Entity */ class PsSocietyannexe { /** * @var int * * @ORM\Column(name="id", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="number", type="string", length=10, nullable=false) */ private $number; /** * @var string|null * * @ORM\Column(name="number_complement", type="string", length=10, nullable=true) */ private $numberComplement; /** * @var string * * @ORM\Column(name="street", type="string", length=250, nullable=false) */ private $street; /** * @var string * * @ORM\Column(name="city", type="string", length=50, nullable=false) */ private $city; /** * @var string * * @ORM\Column(name="country", type="string", length=50, nullable=false) */ private $country; /** * @var string * * @ORM\Column(name="postal_code", type="string", length=20, nullable=false) */ private $postalCode; /** * @var int * * @ORM\Column(name="societyMainId", type="integer", nullable=false, options={"unsigned"=true}) */ private $societymainid; public function getId(): ?int { return $this->id; } public function getNumber(): ?string { return $this->number; } public function setNumber(string $number): self { $this->number = $number; return $this; } public function getNumberComplement(): ?string { return $this->numberComplement; } public function setNumberComplement(?string $numberComplement): self { $this->numberComplement = $numberComplement; return $this; } public function getStreet(): ?string { return $this->street; } public function setStreet(string $street): self { $this->street = $street; return $this; } public function getCity(): ?string { return $this->city; } public function setCity(string $city): self { $this->city = $city; return $this; } public function getCountry(): ?string { return $this->country; } public function setCountry(string $country): self { $this->country = $country; return $this; } public function getPostalCode(): ?string { return $this->postalCode; } public function setPostalCode(string $postalCode): self { $this->postalCode = $postalCode; return $this; } public function getSocietymainid(): ?int { return $this->societymainid; } public function setSocietymainid(int $societymainid): self { $this->societymainid = $societymainid; return $this; } } <file_sep>/src/Entity/PsSocietymain.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * PsSocietymain * * @ORM\Table(name="ps_societymain") * @ORM\Entity */ class PsSocietymain { /** * @var int * * @ORM\Column(name="id", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=100, nullable=false) */ private $name; /** * @var string * * @ORM\Column(name="number", type="string", length=10, nullable=false) */ private $number; /** * @var string|null * * @ORM\Column(name="number_complement", type="string", length=10, nullable=true) */ private $numberComplement; /** * @var string * * @ORM\Column(name="street", type="string", length=150, nullable=false) */ private $street; /** * @var string * * @ORM\Column(name="city", type="string", length=100, nullable=false) */ private $city; /** * @var string * * @ORM\Column(name="country", type="string", length=50, nullable=false) */ private $country; /** * @var string * * @ORM\Column(name="postal_code", type="string", length=20, nullable=false) */ private $postalCode; /** * @var string * * @ORM\Column(name="siret", type="string", length=100, nullable=false) */ private $siret; /** * @var string * * @ORM\Column(name="naf_code", type="string", length=100, nullable=false) */ private $nafCode; public function getId(): ?int { return $this->id; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getNumber(): ?string { return $this->number; } public function setNumber(string $number): self { $this->number = $number; return $this; } public function getNumberComplement(): ?string { return $this->numberComplement; } public function setNumberComplement(?string $numberComplement): self { $this->numberComplement = $numberComplement; return $this; } public function getStreet(): ?string { return $this->street; } public function setStreet(string $street): self { $this->street = $street; return $this; } public function getCity(): ?string { return $this->city; } public function setCity(string $city): self { $this->city = $city; return $this; } public function getCountry(): ?string { return $this->country; } public function setCountry(string $country): self { $this->country = $country; return $this; } public function getPostalCode(): ?string { return $this->postalCode; } public function setPostalCode(string $postalCode): self { $this->postalCode = $postalCode; return $this; } public function getSiret(): ?string { return $this->siret; } public function setSiret(string $siret): self { $this->siret = $siret; return $this; } public function getNafCode(): ?string { return $this->nafCode; } public function setNafCode(string $nafCode): self { $this->nafCode = $nafCode; return $this; } }
e8f075f4c696f2011ba29670688d1e73d62122b9
[ "PHP" ]
27
PHP
OmarBanoun/projet_stage
70a9816470a2cc80603078cd5460043679cf3ce8
d3e010db011a9032ca5c8f444bc91d18237dacfe
refs/heads/master
<file_sep>package bancho import ( "log" "net/http" "time" "github.com/nsogame/common" ) type BanchoServer struct { config *Config db *common.DB rds *common.RedisAPI router http.Handler } func NewInstance(config *Config) (bancho *BanchoServer, err error) { // db db, err := common.ConnectDB(config.DbProvider, config.DbConnection) if err != nil { return } // redis rds := common.NewRedis(config.RedisAddr, config.RedisPass, config.RedisDB) bancho = &BanchoServer{ config: config, db: db, rds: rds, } // router router := bancho.Handlers() bancho.router = router return } func (bancho *BanchoServer) close() { bancho.db.Close() } func (bancho *BanchoServer) Run() { defer bancho.close() log.Println("starting...") server := &http.Server{ Handler: bancho.router, Addr: bancho.config.BindAddr, WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } log.Fatal(server.ListenAndServe()) } <file_sep>package bancho import ( "bytes" "fmt" "io/ioutil" "log" "net/http" "strings" "github.com/google/uuid" "github.com/nsogame/bancho/packets" "github.com/nsogame/common" "github.com/nsogame/common/models" "golang.org/x/crypto/bcrypt" ) const ( LoginFailed = -1 ClientOutdated = -2 LoginBanned = -3 LoginMultiAcc = -4 LoginException = -5 RequireSupporter = -6 RequireVerification = -8 ) func writeErr(err error, p packets.Packet, w http.ResponseWriter) { log.Println(err) w.Header().Add("cho-token", "error") packets.Write(p, w) } func (bancho *BanchoServer) LoginHandler(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { writeErr(err, packets.LoginReply(LoginException), w) return } fmt.Println("body:", body) lines := bytes.Split(body, []byte("\n")) fmt.Println("lines:", lines) if len(lines) < 3 { writeErr(err, packets.LoginReply(LoginException), w) return } // attempt to parse the login data now // line 1: username username := strings.Trim(string(lines[0]), "\n") fmt.Printf("username: '%s'\n", username) // line 2: md5(password) hash := strings.Trim(string(lines[1]), "\n") fmt.Printf("password: '%s'\n", hash) // line 3: BuildName|TimeZone|HasCity|ClientHash|BlockNonFriends // BuildName: str = build name of the client duh5f4dcc3b5aa765d61d8327deb882cf99 // TimeZone: int = number of hours off from UTC // HasCity: bool = whether or not city info is available // ClientHash: str = OsuMd5:Adapters:Md5(Adapters):Md5(UniqueId):Md5(UniqueId2): // BlockNonFriends: bool = whether or not to block non-friend DMs params := strings.Trim(string(lines[2]), "\n") fmt.Printf("params: '%s'\n", params) // attempt to auth to the db var user models.User bancho.db.Where("username = ?", strings.ToLower(username)).First(&user) if err = bcrypt.CompareHashAndPassword([]byte(user.OsuPassword), []byte(hash)); err != nil { fmt.Println("err: ", err) writeErr(err, packets.LoginReply(LoginFailed), w) return } // yay the user is authenticated! make some preparations choToken, err := uuid.NewRandom() if err != nil { writeErr(err, packets.LoginReply(LoginException), w) return } client, err := common.NewClient(choToken.String(), user) if err != nil { writeErr(err, packets.LoginReply(LoginException), w) return } fmt.Println("authenticated!") fmt.Println("client:", client) // tell the client the good news buf := new(bytes.Buffer) packets.Write(packets.ProtocolVersion(19), buf) packets.Write(packets.LoginReply(int32(user.ID)), buf) packets.Write(packets.UserPresencePacket{Username: user.UsernameCase}, buf) packets.Write(packets.FriendsList(bancho.GetOnlineFriends()), buf) packets.Write(packets.UserPresenceBundle(bancho.GetUserPresences()), buf) packets.Write(bancho.GetUserStats(int32(user.ID)), buf) packets.Write(packets.LoginPermissions(1), buf) packets.Write(packets.SilenceEnd(-1), buf) packets.Write(packets.ChannelJoinSuccess("#nso"), buf) fmt.Println("buf:", buf.Bytes()) w.Header().Add("cho-token", choToken.String()) w.Write(buf.Bytes()) } <file_sep>package bancho const ( Userperm = 1 << iota BAT Supporter Moderator Developer Administrator TourneyStuff ) <file_sep>package bancho import "github.com/nsogame/bancho/packets" func (bancho *BanchoServer) GetUserPresences() []uint32 { return []uint32{} } func (bancho *BanchoServer) GetOnlineFriends() []uint32 { return []uint32{} } func (bancho *BanchoServer) GetUserStats(id int32) packets.UserStatsPacket { return packets.UserStatsPacket{ UserID: uint32(id), Rank: 1, } } <file_sep>package bancho import ( "net/http" "os" gorrilaHandlers "github.com/gorilla/handlers" "github.com/gorilla/mux" ) func (bancho *BanchoServer) IndexHandler(w http.ResponseWriter, r *http.Request) { header := w.Header() header.Set("cho-protocol", "19") header.Set("connection", "keep-alive") header.Set("keep-alive", "timeout=5, max=100") header.Set("content-type", "text/html; charset=utf-8") if r.Header.Get("osu-token") == "" && r.Header.Get("user-agent") == "osu!" { bancho.LoginHandler(w, r) return } else if r.Header.Get("osu-token") != "" { } } func (bancho *BanchoServer) Handlers() (router http.Handler) { r := mux.NewRouter() r.HandleFunc("/", bancho.IndexHandler) router = gorrilaHandlers.LoggingHandler(os.Stdout, r) return } <file_sep>bancho ====== This serves as the main online, multiplayer server for the osu! client. Much of this content is based on [Gigamons/Kaoiji](https://github.com/Gigamons/Kaoiji) (also MIT-licensed to Mempler), so thanks for the reference! Contact ------- Author: <NAME> License: MIT <file_sep>package bancho import "github.com/spf13/viper" type Config struct { BindAddr string DbProvider string DbConnection string RedisAddr string RedisPass string RedisDB int } func GetConfig() (config Config, err error) { v := viper.New() v.SetConfigName("bancho") v.SetDefault("BindAddr", "127.0.0.1:6300") v.SetDefault("DbProvider", "sqlite3") v.SetDefault("DbConnection", "bancho.db") v.SetDefault("RedisAddr", "127.0.0.1:6379") v.SetDefault("RedisPass", "") v.SetDefault("RedisDB", "0") v.AddConfigPath(".") err = v.ReadInConfig() if err != nil { return } err = v.Unmarshal(&config) return } <file_sep>package main import ( "bufio" "os" ) func main() { reader := bufio.NewReader(os.Stdin) for { // read the first byte } } <file_sep>package main import ( "log" "github.com/nsogame/bancho" _ "github.com/jinzhu/gorm/dialects/mysql" _ "github.com/jinzhu/gorm/dialects/postgres" _ "github.com/jinzhu/gorm/dialects/sqlite" ) func main() { var err error config, err := bancho.GetConfig() if err != nil { log.Fatal(err) } server, err := bancho.NewInstance(&config) if err != nil { log.Fatal(err) } server.Run() }
5d964920c71d06e56bd5839c988af18566a40124
[ "Markdown", "Go" ]
9
Go
nsogame/bancho
7e5c467a392f694fc0f06f680a6f03d25a2077e3
73ae2d66ad89b8bb0d81ae0ee91c15538c60e34f
refs/heads/master
<file_sep>// to compile: //gcc -I/usr/ort/lib/ffmpeg-2.8.1/include -L/usr/ort/lib/ffmpeg-2.8.1/lib -Wl,-rpath=/usr/ort/lib/ffmpeg-2.8.1/lib demux.c -o demux -g -lavformat -lavcodec -lavutil extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswscale/swscale.h> } #define CHECK_ERR(ERR) {if ((ERR)<0) return -1; } int main(int argc, char *argv[]) { av_register_all(); avcodec_register_all(); int i = 0; AVFormatContext * ctx = NULL; AVPixelFormat pixFormat; AVCodecID codecID; char extension[5]; bool encode = true; if(strcmp(argv[2], "png") == 0 ) { pixFormat = AV_PIX_FMT_RGB24; codecID = CODEC_ID_PNG; sprintf(extension, "png"); } else if(strcmp(argv[2], "ppm") == 0) { pixFormat = AV_PIX_FMT_RGB24; encode = false; sprintf(extension, "ppm"); } else if(strcmp(argv[2], "jpg") == 0) { pixFormat = PIX_FMT_YUVJ420P; codecID = CODEC_ID_MJPEG; sprintf(extension, "jpg"); } else { CHECK_ERR(-1); } int err = avformat_open_input(&ctx, argv[1], NULL, NULL); CHECK_ERR(err); err = avformat_find_stream_info(ctx, NULL); CHECK_ERR(err); av_dump_format(ctx, 0, argv[1], 0); //find stream AVCodec * codec = NULL; int strm = av_find_best_stream(ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0); //open codecContext AVCodecContext * codecCtx = ctx->streams[strm]->codec; codec=avcodec_find_decoder(codecCtx->codec_id); err = avcodec_open2(codecCtx, codec, NULL); CHECK_ERR(err); AVFrame * outputFrame = av_frame_alloc(); uint8_t *buffer = NULL; int numBytes; numBytes = avpicture_get_size(pixFormat, codecCtx->width, codecCtx->height); buffer = (uint8_t *) av_malloc(numBytes * sizeof(uint8_t)); avpicture_fill((AVPicture*) outputFrame, buffer, pixFormat, codecCtx->width, codecCtx->height); SwsContext * swCtx = sws_getContext(codecCtx->width, codecCtx->height, codecCtx->pix_fmt, codecCtx->width, codecCtx->height, pixFormat, SWS_FAST_BILINEAR, 0, 0, 0); AVPacket pkt; i = 0; while(av_read_frame(ctx, &pkt) >= 0) { if (pkt.stream_index == strm) { int got = 0; AVFrame * frame = av_frame_alloc(); err = avcodec_decode_video2(codecCtx, frame, &got, &pkt); CHECK_ERR(err); if (got) { sws_scale(swCtx, frame->data, frame->linesize, 0, frame->height, outputFrame->data, outputFrame->linesize); AVCodec *outCodec = avcodec_find_encoder(codecID); AVCodecContext *outCodecCtx = avcodec_alloc_context3(outCodec); if (!codecCtx) { return -1; } if(!encode) { if(++i <= 5) { FILE *pFile; char szFilename[32]; int y; // Open file sprintf(szFilename, "frame%d.ppm", i); pFile=fopen(szFilename, "wb"); if(pFile==NULL) return -1; // Write header fprintf(pFile, "P6\n%d %d\n255\n", codecCtx->width, codecCtx->height); // Write pixel data for(y=0; y<codecCtx->height; y++) { fwrite(outputFrame->data[0]+y*outputFrame->linesize[0], 1, codecCtx->width*3, pFile); } // Close file fclose(pFile); } } else { outCodecCtx->width = codecCtx->width; outCodecCtx->height = codecCtx->height; outCodecCtx->pix_fmt = pixFormat; outCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO; outCodecCtx->time_base.num = codecCtx->time_base.num; outCodecCtx->time_base.den = codecCtx->time_base.den; if (!outCodec || avcodec_open2(outCodecCtx, outCodec, NULL) < 0) { return -1; } if(++i <= 5) { char szFilename[32]; AVPacket outPacket; av_init_packet(&outPacket); outPacket.size = 0; outPacket.data = NULL; int gotFrame = 0; outputFrame->format = pixFormat; outputFrame->height = codecCtx->height; outputFrame->width = codecCtx->width; int ret = avcodec_encode_video2(outCodecCtx, &outPacket, outputFrame, &gotFrame); if (ret >= 0 && gotFrame) { sprintf(szFilename, "frame%d.%s", i, extension); FILE * outPng = fopen(szFilename, "wb"); fwrite(outPacket.data, outPacket.size, 1, outPng); fclose(outPng); } } } avcodec_close(outCodecCtx); av_free(outCodecCtx); } av_free(frame); } } }
1d698db20524d5281f7ed09332a394d8c374fac3
[ "C++" ]
1
C++
whiack/ffmpeg
68b83e1379e62b66a2487c2350e02a06a7fa6ac1
6eae90bcc9b045e9cd2a6b054d3892fb5c93d8c8
refs/heads/master
<repo_name>marwis95/Aumatic-Database<file_sep>/AUMATIC_BAZA/add_model.php <html> <head> <meta http-equiv="Content-Language" content="pl"> <META NAME="Keywords" CONTENT=""> <meta http-equiv="Content-Type" content="text/html; charset=windows-1250"> <title>Dodaj sterownik</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <?php mysql_connect("localhost", "root", "123") or die("Nie można poł±czyć się z MySQL"); mysql_select_db("aumatic") or die("Nie można poł±czyć się z baza danych"); ?> <?php session_start(); //require_once('db.php'); ?> <?php if ($_SESSION['auth'] == TRUE) { $zapytanie="SELECT * from uzytkownicy where login = '" . $_SESSION['user'] . "'"; //query $wykonaj=mysql_query($zapytanie); // result while ($wiersz = mysql_fetch_array($wykonaj)){ if ($wiersz['prawa'] != ""){ $prawa = $wiersz['prawa']; } } } if ($prawa == "admin"){ $tablica_wyborow = array(); echo "<center><font size='7'>Dodaj model do istniejącego producenta</center><br></font>"; echo "<div style='float: left'><font size='7'><a href='hide.php'><--Wróć</a></div></font>"; echo "<center>"; echo "<div style='width: 350px; height:200px; background: #f0f0f0; text-align: left;'>"; echo "<br><br>"; $i=0; $tab = array(); $tab[0][1] = "==WYBIERZ ISTNIEJĄCEGO PRODUCENTA=="; $zapytanie_marka_lista="SELECT * from sterowniki order by marka asc"; //query $wykonaj_marka_lista=mysql_query($zapytanie_marka_lista); // result while ($wiersz_marka_lista = mysql_fetch_array($wykonaj_marka_lista)){ $tab[$i+1][1] = $wiersz_marka_lista['marka']; $tab[$i+1][0] = $wiersz_marka_lista['id']; $i++; } //<!--====================Wypełnianie tablicy z markami================================--> echo "<form action='add_model.php' method='post' enctype='multipart/form-data'>"; echo "<select name='marka' style='width: 350px' id='marka' onchange='this.form.submit()'>"; $flag = true; for ($i=0; $i<count($tab); $i++){ for($j=0; $j<$i; $j++){ if($tab[$j][1] == $tab[$i][1]){ $flag = false; } } if($flag == true){ echo "<option value='" . $tab[$i][1] . "'"; if($tab[$i][1] == $_POST['marka']) echo " selected='selected' "; echo ">"; echo $tab[$i][1]; echo "</option>"; } $flag = true; } echo "</select>"; echo "<br>"; echo "<br>Podaj nazwę modelu: "; echo "<input type='text' name='model' style='width: 200px; float: right;'/><br><br>"; echo "<input type='submit' name='button1' value='DODAJ' style='width: 350px; height: 40px;'>"; echo "</form>"; echo "</div>"; echo "</center>"; //var_dump($_POST); if(isset($_POST['button1'])){ if($_POST['model'] != ""){ $zapytanie_model="insert into sterowniki (id, marka, model) values ('', '" . $_POST['marka'] . "', '" . mysql_real_escape_string($_POST['model']) . "')"; //query $wykonaj_model=mysql_query($zapytanie_model); // result echo "<script>"; echo "alert('Sterownik został dodany poprawnie')"; echo "</script>"; }else{ echo "<script>"; echo "alert('Musisz podać model')"; echo "</script>"; } } }else{ echo "brak dostepu"; } ?> </body> </html> <file_sep>/AUMATIC_BAZA/accept.php <html> <head> <meta http-equiv="Content-Language" content="pl"> <META NAME="Keywords" CONTENT=""> <meta http-equiv="Content-Type" content="text/html; charset=windows-1250"> <title>Zatwierdź użytkownika</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <?php mysql_connect("localhost", "root", "123") or die("Nie można poł±czyć się z MySQL"); mysql_select_db("aumatic") or die("Nie można poł±czyć się z baza danych"); ?> <?php session_start(); //require_once('db.php'); ?> <?php if ($_SESSION['auth'] == TRUE) { $zapytanie="SELECT * from uzytkownicy where login = '" . $_SESSION['user'] . "'"; //query $wykonaj=mysql_query($zapytanie); // result while ($wiersz = mysql_fetch_array($wykonaj)){ if ($wiersz['prawa'] != ""){ $prawa = $wiersz['prawa']; } } } if ($prawa == "admin"){ if ($_POST['prawa'] == ""){ $_POST['prawa'] = "junior"; } //var_dump($_POST); if($_GET["usun"]) { $zapytanie_drop="DELETE FROM kandydaci where id='" . $_GET["usun"]. "';"; //query $wykonaj_drop=mysql_query($zapytanie_drop); // result echo "<script>"; echo "alert ('Prośba kandydata zastała odrzucona !')"; echo "</script>"; } if($_GET["dodaj"]) { //echo "Dodawanie id ".$_GET['dodaj']; //echo "Prawa ".$_GET['prawa']; $zapytanie_select="select * from kandydaci where id='" . $_GET['dodaj'] . "';"; //query $wykonaj_select=mysql_query($zapytanie_select); // result $wiersz_select = mysql_fetch_array($wykonaj_select); $zapytanie_add="INSERT INTO uzytkownicy (id, imie, nazwisko, mail, login, haslo, prawa, block) VALUES ('', '" . $wiersz_select['imie'] . "', '" . $wiersz_select['nazwisko'] . "', '" . $wiersz_select['mail'] . "', '" . $wiersz_select['login'] . "', '" . $wiersz_select['haslo'] . "', '" . $_GET['prawa'] . "', '0');"; $wykonaj_add=mysql_query($zapytanie_add); $zapytanie_getid="select * from uzytkownicy where login='" . $wiersz_select['login'] . "'"; //query $wykonaj_getid=mysql_query($zapytanie_getid); // result $wiersz_getid = mysql_fetch_array($wykonaj_getid); $zapytanie_programista="insert into programisci (id, imie, nazwisko, id_usera) values('', '" . $wiersz_select['imie'] ."', '" . $wiersz_select['nazwisko'] ."', '" . $wiersz_getid['id'] . "')"; //query $wykonaj_programista=mysql_query($zapytanie_programista); // result $zapytanie_drop="DELETE FROM kandydaci where id='" . $_GET["dodaj"]. "';"; //query $wykonaj_drop=mysql_query($zapytanie_drop); // result echo "<script>"; echo "alert ('Kandydat został dodany do bazy')"; echo "</script>"; } $zapytanie="SELECT * from kandydaci"; //query $wykonaj=mysql_query($zapytanie); // result echo "<center><font size='7'>Następujący użytkownicy proszą o dodanie ich do bazy</center><br></font>"; echo "<div style='float: left'><font size='7'><a href='hide.php'><--Wróć</a></div></font>"; echo "<div style='margin: 0 auto; width: 600px;'>"; while ($wiersz = mysql_fetch_array($wykonaj)){ echo "<table border='1' align='center' width='600'>"; echo "<tr>"; echo "<td width='80'>"; echo "ID:"; echo "</td>"; echo "<td>"; echo $wiersz['id']; echo "</td>"; echo "</tr>"; echo "<tr>"; echo "<td width='80'>"; echo "Imie:"; echo "</td>"; echo "<td>"; $temp_imie = $wiersz['id']; $zapytanie_imie="SELECT * from kandydaci where id=$temp_imie"; //query $wykonaj_imie=mysql_query($zapytanie_imie); // result $wiersz_imie = mysql_fetch_array($wykonaj_imie); echo $wiersz_imie['imie']; echo "</td>"; echo "</tr>"; ////////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Nazwisko:"; echo "</td>"; echo "<td>"; $temp_nazwisko = $wiersz['id']; $zapytanie_nazwisko="SELECT * from kandydaci where id=$temp_nazwisko"; //query $wykonaj_nazwisko=mysql_query($zapytanie_nazwisko); // result $wiersz_nazwisko = mysql_fetch_array($wykonaj_nazwisko); echo $wiersz_nazwisko['nazwisko']; //setcookie("typ", $wiersz_typ['typ']); echo "</td>"; echo "</tr>"; //////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Login:"; echo "</td>"; echo "<td>"; $temp_login = $wiersz['id']; $zapytanie_login="SELECT * from kandydaci where id=$temp_imie"; //query $wykonaj_login=mysql_query($zapytanie_login); // result $wiersz_login = mysql_fetch_array($wykonaj_login); echo $wiersz_login['login']; echo "</td>"; echo "</tr>"; //////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "E-mail:"; echo "</td>"; echo "<td>"; $temp_mail = $wiersz['id']; $zapytanie_mail="SELECT * from kandydaci where id=$temp_imie"; //query $wykonaj_mail=mysql_query($zapytanie_mail); // result $wiersz_mail = mysql_fetch_array($wykonaj_mail); echo $wiersz_mail['mail']; echo "</td>"; echo "</tr>"; ////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Usun/Zatwierdź:"; echo "</td>"; echo "<td>"; $nazwa = $wiersz['pobierz']; //echo $wiersz['pobierz']; echo "<a href='accept.php?usun=".$wiersz['id']."'>-->ODMÓW<--</a><br><br>"; echo "<form action='accept.php' method='post'>"; echo "<label for='prawa'>PRAWA:</label>"; echo "<select name='prawa' id='prawa' onchange='this.form.submit()'>"; if ($_POST['prawa'] == "junior"){ echo "<option value='junior' selected='selected'>Junior (tylko odczyt)</option>"; echo "<option value='senior' >Senior (odczyt + dopisywanie)</option>"; echo "<option value='vip' >Vip (odczyt + dopisywanie + usuwanie)</option>"; echo "<option value='admin'>Admin (wszystko)</option>"; } if ($_POST['prawa'] == "senior"){ echo "<option value='junior'>Junior (tylko odczyt)</option>"; echo "<option value='senior' selected='selected'>Senior (odczyt + dopisywanie)</option>"; echo "<option value='vip' >Vip (odczyt + dopisywanie + usuwanie)</option>"; echo "<option value='admin'>Admin (wszystko)</option>"; } if ($_POST['prawa'] == "vip"){ echo "<option value='junior'>Junior (tylko odczyt)</option>"; echo "<option value='senior'>Senior (odczyt + dopisywanie)</option>"; echo "<option value='vip' selected='selected'>Vip (odczyt + dopisywanie + usuwanie)</option>"; echo "<option value='admin'>Admin (wszystko)</option>"; } if ($_POST['prawa'] == "admin"){ echo "<option value='junior'>Junior (tylko odczyt)</option>"; echo "<option value='senior'>Senior (odczyt + dopisywanie)</option>"; echo "<option value='vip'>Vip (odczyt + dopisywanie + usuwanie)</option>"; echo "<option value='admin' selected='selected'>Admin (wszystko)</option>"; } echo "</select>"; echo "</form>"; echo "<a href='accept.php?dodaj=".$wiersz['id']. "&prawa=" . $_POST['prawa'] . "'>-->NADAJ PRAWA I DODAJ<--</a>"; echo "</td>"; echo "</tr>"; echo "</table>"; echo "<br><br><br>"; } echo "</div>"; echo "</center>"; echo "</div>"; }else{ echo "brak dostepu"; } ?> </body> </html> <file_sep>/AUMATIC_BAZA/add_premium.php <html> <head> <meta http-equiv="Content-Language" content="pl"> <META NAME="Keywords" CONTENT=""> <meta http-equiv="Content-Type" content="text/html; charset=windows-1250"> <title>Dodawanie</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <?php session_start(); //require_once('db.php'); ?> <?php function sprawdz_bledy() { if ($_FILES['nazwa_pliku']['error'] > 0) { echo 'problem: '; switch ($_FILES['nazwa_pliku']['error']) { // jest większy niż domyślny maksymalny rozmiar, // podany w pliku konfiguracyjnym case 1: {echo 'Rozmiar pliku jest zbyt duży.'; break;} // jest większy niż wartość pola formularza // MAX_FILE_SIZE case 2: {echo 'Rozmiar pliku jest zbyt duży.'; break;} // plik nie został wysłany w całości case 3: {echo 'Plik wysłany tylko częściowo.'; break;} // plik nie został wysłany case 4: {echo 'Nie wysłano żadnego pliku.'; break;} // pozostałe błędy default: {echo 'Wystąpił błąd podczas wysyłania.'; break;} } return false; } return true; } ?> <?php function sprawdz_bledy_2() { if ($_FILES['nazwa_pliku_2']['error'] > 0) { echo 'problem: '; switch ($_FILES['nazwa_pliku_2']['error']) { // jest większy niż domyślny maksymalny rozmiar, // podany w pliku konfiguracyjnym case 1: {echo 'Rozmiar pliku jest zbyt duży.'; break;} // jest większy niż wartość pola formularza // MAX_FILE_SIZE case 2: {echo 'Rozmiar pliku jest zbyt duży.'; break;} // plik nie został wysłany w całości case 3: {echo 'Plik wysłany tylko częściowo.'; break;} // plik nie został wysłany case 4: {echo 'Nie wysłano żadnego pliku.'; break;} // pozostałe błędy default: {echo 'Wystąpił błąd podczas wysyłania.'; break;} } return false; } return true; } ?> <?php function zapisz_plik() { $lokalizacja = "pliki" . chr(92) . $_FILES['nazwa_pliku']['name']; if(is_uploaded_file($_FILES['nazwa_pliku']['tmp_name'])) { if(!move_uploaded_file($_FILES['nazwa_pliku']['tmp_name'], $lokalizacja)) { echo 'problem: Nie udało się skopiować pliku do katalogu.'; return false; } } else { echo 'Plik nie został zapisany.'; return false; } return true; } ?> <?php function zapisz_plik_2() { $lokalizacja_2 = "Dokumentacje" . chr(92) . $_FILES['nazwa_pliku_2']['name']; if(is_uploaded_file($_FILES['nazwa_pliku_2']['tmp_name'])) { if(!move_uploaded_file($_FILES['nazwa_pliku_2']['tmp_name'], $lokalizacja_2)) { echo 'problem: Nie udało się skopiować pliku do katalogu.'; return false; } } else { echo 'Plik nie został zapisany.'; return false; } return true; } ?> <?php mysql_connect("localhost", "root", "123") or die("Nie można poł±czyć się z MySQL"); mysql_select_db("aumatic") or die("Nie można poł±czyć się z baza danych"); ?> <?php if ($_SESSION['auth'] == TRUE) { $zapytanie="SELECT * from uzytkownicy where login = '" . $_SESSION['user'] . "'"; //query $wykonaj=mysql_query($zapytanie); // result while ($wiersz = mysql_fetch_array($wykonaj)){ if ($wiersz['prawa'] != ""){ $prawa = $wiersz['prawa']; } } } if ($prawa == "admin"){ echo "<div style='float: left'><font size='7'><a href='hide.php'><--Wróć</a></div></font>"; echo "<center>"; $tablica_wyborow = array(); echo "<div style='width: 300px; height:600px; background: #f0f0f0; text-align: left;'>"; echo "<div style='margin: 0 auto'><font size='6'>Dodaj nowy program: </font><br><br></div>"; $i=0; $tab = array(); $tab[0][1] = "==WYBIERZ PRODUCENTA=="; $zapytanie_marka_lista="SELECT * from sterowniki order by marka asc"; //query $wykonaj_marka_lista=mysql_query($zapytanie_marka_lista); // result while ($wiersz_marka_lista = mysql_fetch_array($wykonaj_marka_lista)){ $tab[$i+1][1] = $wiersz_marka_lista['marka']; $tab[$i+1][0] = $wiersz_marka_lista['id']; $i++; } //<!--====================Wypełnianie tablicy z markami================================--> echo "<form action='add_premium.php' method='post' name='form1' enctype='multipart/form-data'>"; echo "<select name='marka' style='width: 300px' id='marka' onchange='this.form.submit()'>"; $flag = true; for ($i=0; $i<count($tab); $i++){ for($j=0; $j<$i; $j++){ if($tab[$j][1] == $tab[$i][1]){ $flag = false; } } if($flag == true){ echo "<option value='" . $tab[$i][1] . "'"; if($tab[$i][1] == $_POST['marka']) echo " selected='selected' "; echo ">"; echo $tab[$i][1]; echo "</option>"; } $flag = true; } echo "</select>"; echo "<br><br>"; //<!--====================Wypełnianie listy z markami============================--> echo "<select name='model' style='width: 300px'>"; echo "<option value='select'>"; echo "==WYBIERZ MODEL=="; echo "</option>"; $zapytanie_model_lista="SELECT * from sterowniki where marka='" . $_POST['marka'] . "'"; //query echo $zapytanie_model_lista; $wykonaj_model_lista=mysql_query($zapytanie_model_lista); // result while ($wiersz_model_lista = mysql_fetch_array($wykonaj_model_lista)){ echo "<option value='" . $wiersz_model_lista['id'] . "'"; if($wiersz_model_lista['id'] == $_POST['model']) echo " selected='selected' "; echo ">"; echo $wiersz_model_lista['model']; echo "</option>"; } echo "</select>"; echo "<br><br>"; //<!--========================Wypełnianie listy z modelami============================--> echo "<select name='typ' style='width: 300px'>"; echo "<option value='select'>"; echo "==<NAME>=="; echo "</option>"; $zapytanie_typ_lista="SELECT * from typ_funkcji"; //query $wykonaj_typ_lista=mysql_query($zapytanie_typ_lista); // result while ($wiersz_typ_lista = mysql_fetch_array($wykonaj_typ_lista)){ echo "<option value='" . $wiersz_typ_lista['id'] . "'"; if($wiersz_typ_lista['id'] == $_POST['typ']) echo " selected='selected' "; echo ">"; echo $wiersz_typ_lista['typ']; echo "</option>"; } echo '</select>'; echo "<br><br>"; //<!--========================Wypełnienie listy z typami=======================--> echo "<select name='programista' style='width: 300px'>"; echo "<option value='select'>"; echo "==WYBIERZ PROGRAMISTE=="; echo "</option>"; $zapytanie_programista_lista="SELECT * from programisci"; //query $wykonaj_programista_lista=mysql_query($zapytanie_programista_lista); // result while ($wiersz_programista_lista = mysql_fetch_array($wykonaj_programista_lista)){ echo "<option value='" . $wiersz_programista_lista['id'] . "'"; if($wiersz_programista_lista['id'] == $_POST['programista']) echo " selected='selected' "; echo ">"; echo $wiersz_programista_lista['nazwisko']; echo " "; echo $wiersz_programista_lista['imie']; echo "</option>"; } echo "</select>"; //<!--========================Wypełnienie listy z programistami=======================--> echo "<br><br>"; if ($_POST['wersja'] != ""){ echo "Wersja: <input type='text' name='wersja' value='" . $_POST['wersja'] . "' style='float: right; width: 220px;'>"; }else{ echo "Wersja: <input type='text' name='wersja' style='float: right; width: 220px;'>"; } echo "<br><br>"; echo "Opis: <br>"; if($_POST['opis'] != ""){ echo "<textarea name='opis' style='width: 300px; height: 200px;'>" . $_POST['opis'] . "</textarea>"; }else{ echo "<textarea name='opis' style='width: 300px; height: 200px;' onclick='this.focus();this.select()'>Tu dodaj opis programu</textarea>"; } echo "<br><br>"; echo "Program:"; echo "<input type='hidden' name='MAX_FILE_SIZE' value='512000' />"; echo "<input type='file' name='nazwa_pliku' />"; echo "<br><br>"; echo "Dokumentacja:"; echo "<input type='hidden' name='MAX_FILE_SIZE' value='512000' />"; echo "<input type='file' name='nazwa_pliku_2' />"; echo "<br><br>"; echo "<input type='submit' name='button1' value='DODAJ' style='width: 300px; height: 40px;'>"; echo "</form>"; echo "</center>"; echo "</div>"; $data = date("d.n.o - G:i"); if (isset($_POST['button1'])){ //echo "MARKA: " . $_POST['marka'] . "<br>"; //echo "MODEL: " . $_POST['model'] . "<br>"; //echo "TYP: " . $_POST['typ'] . "<br>"; //echo "PROGRAMISTA: " . $_POST['programista'] . "<br>"; //echo "Wersja: " . $_POST['wersja']. "<br>"; //echo "OPIS: " . $_POST['opis'] . "<br>"; //echo "Program: " . $_FILES['nazwa_pliku']['name']. "<br>"; //echo "Dokumentacja: " . $_FILES['nazwa_pliku_2']['name']. "<br>"; //echo "POPRAWNOSC PROGRAMU: " . sprawdz_bledy(); //jak zwraca true to jest ok; //echo "POPRAWNOSC DOKUMENTACJI: " . sprawdz_bledy_2(); if (($_POST['model']!="select") and ($_POST['typ']!="select") and ($_POST['programista']!="select") and ($_POST['wersja']!="") and ($_POST['opis']!="Tu dodaj opis programu") and ($_FILES['nazwa_pliku']['name']!="") and ($_FILES['nazwa_pliku_2']['name']!="") and (sprawdz_bledy() == 1) and (sprawdz_bledy_2() == 1)){ if(sprawdz_bledy() == 1){ zapisz_plik(); } if(sprawdz_bledy_2() == 1){ zapisz_plik_2(); } $zapytanie="INSERT INTO programy (id, id_sterownika, id_typu, id_programisty, wersja, data, opis, pobierz, dokumentacja) VALUES ('', '".$_POST['model']."', '".$_POST['typ']."', '".$_POST['programista']."', '".mysql_real_escape_string($_POST['wersja'])."', '" . $data . "' , '".mysql_real_escape_string($_POST['opis'])."', '" . $_FILES['nazwa_pliku']['name'] . "', '" . $_FILES['nazwa_pliku_2']['name'] . "')"; $wykonaj=mysql_query($zapytanie); //echo $zapytanie; echo "<script>"; echo "alert('Program dodano pomyślnie');"; echo "</script>"; }else{ echo "<script>"; echo "alert('Wystąpił błąd (Musisz wypełnić wszystkie pola i wybrać załącznik)');"; echo "</script>"; } } }else{ echo "Brak dostepu"; } ?> </body> </html><file_sep>/AUMATIC_BAZA/users.php <html> <head> <meta http-equiv="Content-Language" content="pl"> <META NAME="Keywords" CONTENT=""> <meta http-equiv="Content-Type" content="text/html; charset=windows-1250"> <title>Zarzadzaj użytkownikami</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <?php mysql_connect("localhost", "root", "123") or die("Nie można poł±czyć się z MySQL"); mysql_select_db("aumatic") or die("Nie można poł±czyć się z baza danych"); ?> <?php session_start(); //require_once('db.php'); ?> <?php if ($_SESSION['auth'] == TRUE) { $zapytanie="SELECT * from uzytkownicy where login = '" . $_SESSION['user'] . "'"; //query $wykonaj=mysql_query($zapytanie); // result while ($wiersz = mysql_fetch_array($wykonaj)){ if ($wiersz['prawa'] != ""){ $prawa = $wiersz['prawa']; } } } if ($prawa == "admin"){ //var_dump($_POST); if($_GET["block"]) { //echo "Blokuj " . $_GET['block']; $zapytanie_block="update uzytkownicy uzytkownicy set block='1' where id='" . $_GET['block'] . "';"; //query $wykonaj_block=mysql_query($zapytanie_block); // result echo "<script>"; echo "alert('Użytkownik został zablokowany');"; echo "</script>"; } if($_GET["unblock"]) { //echo "Odblokuj ". $_GET['unblock']; $zapytanie_unblock="update uzytkownicy uzytkownicy set block='0' where id='" . $_GET['unblock'] . "';"; //query $wykonaj_unblock=mysql_query($zapytanie_unblock); // result echo "<script>"; echo "alert('Użytkownik został odblokowany');"; echo "</script>"; } if($_GET["delete"]){ //echo "Usuń " . $_GET['delete']; $zapytanie_delete="delete from uzytkownicy where id='" . $_GET['delete'] . "';"; //query $wykonaj_delete=mysql_query($zapytanie_delete); // result echo "<script>"; echo "alert('Użytkownik został usunięty');"; echo "</script>"; } $zapytanie="SELECT * from uzytkownicy"; //query $wykonaj=mysql_query($zapytanie); // result $zapytanie_count="select * from uzytkownicy;"; //query $wykonaj_count=mysql_query($zapytanie_count); // result $policz_count = mysql_num_rows($wykonaj_count); $zapytanie_count_block="select * from uzytkownicy where block='1';"; //query $wykonaj_count_block=mysql_query($zapytanie_count_block); // result $policz_count_block = mysql_num_rows($wykonaj_count_block); echo "<center><font size='7'>Zarządzaj użytkownikami:</center><br></font>"; echo "<center><font size='5'>Uzytkowników w systemie: " . $policz_count . " (w tym zablokowanych: " . $policz_count_block . ")</center><br></font>"; echo "<div style='float: left'><font size='7'><a href='hide.php'><--Wróć</a></div></font>"; echo "<div style='margin: 0 auto; width: 600px;'>"; while ($wiersz = mysql_fetch_array($wykonaj)){ echo "<table border='1' align='center' width='600'>"; echo "<tr>"; echo "<td width='80'>"; echo "ID:"; echo "</td>"; echo "<td>"; echo $wiersz['id']; echo "</td>"; echo "</tr>"; echo "<tr>"; echo "<td width='80'>"; echo "Imie:"; echo "</td>"; echo "<td>"; $temp_imie = $wiersz['id']; $zapytanie_imie="SELECT * from uzytkownicy where id=$temp_imie"; //query $wykonaj_imie=mysql_query($zapytanie_imie); // result $wiersz_imie = mysql_fetch_array($wykonaj_imie); echo $wiersz_imie['imie']; echo "</td>"; echo "</tr>"; ////////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Nazwisko:"; echo "</td>"; echo "<td>"; $temp_nazwisko = $wiersz['id']; $zapytanie_nazwisko="SELECT * from uzytkownicy where id=$temp_nazwisko"; //query $wykonaj_nazwisko=mysql_query($zapytanie_nazwisko); // result $wiersz_nazwisko = mysql_fetch_array($wykonaj_nazwisko); echo $wiersz_nazwisko['nazwisko']; //setcookie("typ", $wiersz_typ['typ']); echo "</td>"; echo "</tr>"; //////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Login:"; echo "</td>"; echo "<td>"; $temp_login = $wiersz['id']; $zapytanie_login="SELECT * from uzytkownicy where id=$temp_login"; //query $wykonaj_login=mysql_query($zapytanie_login); // result $wiersz_login = mysql_fetch_array($wykonaj_login); echo $wiersz_login['login']; echo "</td>"; echo "</tr>"; //////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "E-mail:"; echo "</td>"; echo "<td>"; $temp_mail = $wiersz['id']; $zapytanie_mail="SELECT * from uzytkownicy where id=$temp_mail"; //query $wykonaj_mail=mysql_query($zapytanie_mail); // result $wiersz_mail = mysql_fetch_array($wykonaj_mail); echo $wiersz_mail['mail']; echo "</td>"; echo "</tr>"; ////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Prawa:"; echo "</td>"; echo "<td>"; $temp_prawa = $wiersz['id']; $zapytanie_prawa="SELECT * from uzytkownicy where id=$temp_prawa"; //query $wykonaj_prawa=mysql_query($zapytanie_prawa); // result $wiersz_prawa = mysql_fetch_array($wykonaj_prawa); echo $wiersz_prawa['prawa']; //echo "<a href='accept.php?usun=".$wiersz['id']."'>-->ODMÓW<--</a><br><br>"; //echo "<a href='accept.php?dodaj=".$wiersz['id']. "&prawa=" . $_POST['prawa'] . "'>-->NADAJ PRAWA I DODAJ<--</a>"; echo "</td>"; echo "</tr>"; /////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Status:"; echo "</td>"; echo "<td>"; $temp_status = $wiersz['id']; $zapytanie_status="SELECT * from uzytkownicy where id=$temp_status"; //query $wykonaj_status=mysql_query($zapytanie_status); // result $wiersz_status = mysql_fetch_array($wykonaj_status); if ($wiersz_status['block'] == '0'){ echo "<div style='color: #006600; font-weight: bold;'>Odblokowany</div>"; }else{ echo "<div style='color: #CC0000; font-weight: bold;'>ZABLOKOWANY !!!</div>"; } echo "</td>"; echo "</tr>"; /////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Zarządzaj"; echo "</td>"; echo "<td>"; $temp_status = $wiersz['id']; $zapytanie_status="SELECT * from uzytkownicy where id=$temp_status"; //query $wykonaj_status=mysql_query($zapytanie_status); // result $wiersz_status = mysql_fetch_array($wykonaj_status); if ($wiersz_status['block'] == '0'){ echo "<a href='users.php?block=".$wiersz['id']."'>-->Zablokuj<--</a><br><br>"; }else{ echo "<a href='users.php?unblock=".$wiersz['id']."'>-->Odblokuj<--</a><br><br>"; } echo "<a href='users.php?delete=".$wiersz['id']."'>-->Usuń<--</a><br>"; echo "</td>"; echo "</tr>"; echo "</table>"; echo "<br><br><br>"; } echo "</div>"; echo "</center>"; echo "</div>"; }else{ echo "brak dostepu"; } ?> </body> </html> <file_sep>/AUMATIC_BAZA/drop.php <html> <head> <meta http-equiv="Content-Language" content="pl"> <META NAME="Keywords" CONTENT=""> <meta http-equiv="Content-Type" content="text/html; charset=windows-1250"> <title>Usuwanie</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <?php mysql_connect("localhost", "root", "123") or die("Nie można połączyć się z MySQL"); mysql_select_db("aumatic") or die("Nie można połączyć się z baza danych"); ?> <?php session_start(); //require_once('db.php'); ?> <?php if ($_SESSION['auth'] == TRUE) { $zapytanie="SELECT * from uzytkownicy where login = '" . $_SESSION['user'] . "'"; //query $wykonaj=mysql_query($zapytanie); // result while ($wiersz = mysql_fetch_array($wykonaj)){ if ($wiersz['prawa'] != ""){ $prawa = $wiersz['prawa']; } } } if (($prawa == "vip") || ($prawa == "admin")){ if($_GET["usun"]) { //echo "Usuwanie id ".$_GET['usun']; echo "<script>"; echo "alert('Program zostal usuniety pomyslnie');"; echo "</script>"; $zapytanie="delete from programy where id='" . $_GET['usun'] . "'"; //query mysql_query($zapytanie); // result //$zapytanie_plik="select * from programy where id='" . $_GET['usun'] . "'"; //query //$wykonaj_plik = mysql_query($zapytanie_plik); // result //$wiersz_plik = mysql_fetch_array($wykonaj_plik); //echo $wiersz_plik['pobierz']; //echo "unlink('nazwa_pliku_2.rar')"; } $tablica_wyborow = array(); echo "<div style='background-color:#eeeeee;'>"; echo "<center>"; $i=0; $tab = array(); $tab[0][1] = "==WYBIERZ PRODUCENTA=="; $zapytanie_marka_lista="SELECT * from sterowniki order by marka asc"; //query $wykonaj_marka_lista=mysql_query($zapytanie_marka_lista); // result while ($wiersz_marka_lista = mysql_fetch_array($wykonaj_marka_lista)){ $tab[$i+1][1] = $wiersz_marka_lista['marka']; $tab[$i+1][0] = $wiersz_marka_lista['id']; $i++; } //<!--====================Wypełnianie tablicy z markami================================--> echo "<form action='drop.php' method='post'>"; echo "<select name='marka' id='marka' onchange='this.form.submit()'>"; $flag = true; for ($i=0; $i<count($tab); $i++){ for($j=0; $j<$i; $j++){ if($tab[$j][1] == $tab[$i][1]){ $flag = false; } } if($flag == true){ echo "<option value='" . $tab[$i][1] . "'"; if($tab[$i][1] == $_POST['marka']) echo " selected='selected' "; echo ">"; echo $tab[$i][1]; echo "</option>"; } $flag = true; } echo "</select>"; //<!--====================Wypełnianie listy z markami============================--> echo "<select name='model' >"; echo "<option value='select'>"; echo "==WYBIERZ MODEL=="; echo "</option>"; $zapytanie_model_lista="SELECT * from sterowniki where marka='" . $_POST['marka'] . "'"; //query echo $zapytanie_model_lista; $wykonaj_model_lista=mysql_query($zapytanie_model_lista); // result while ($wiersz_model_lista = mysql_fetch_array($wykonaj_model_lista)){ echo "<option value='" . $wiersz_model_lista['id'] . "'"; if($wiersz_model_lista['id'] == $_POST['model']) echo " selected='selected' "; echo ">"; echo $wiersz_model_lista['model']; echo "</option>"; } echo "</select>"; //<!--========================Wypełnianie listy z modelami============================--> echo "<select name='typ' >"; echo "<option value='select'>"; echo "==WYBIERZ KLASĘ FUNKCJI=="; echo "</option>"; $zapytanie_typ_lista="SELECT * from typ_funkcji"; //query $wykonaj_typ_lista=mysql_query($zapytanie_typ_lista); // result while ($wiersz_typ_lista = mysql_fetch_array($wykonaj_typ_lista)){ echo "<option value='" . $wiersz_typ_lista['id'] . "'"; if($wiersz_typ_lista['id'] == $_POST['typ']) echo " selected='selected' "; echo ">"; echo $wiersz_typ_lista['typ']; echo "</option>"; } echo '</select>'; //<!--========================Wypełnienie listy z typami=======================--> echo "<select name='programista' >"; echo "<option value='select'>"; echo "==WYBIERZ PROGRAMISTE=="; echo "</option>"; $zapytanie_programista_lista="SELECT * from programisci"; //query $wykonaj_programista_lista=mysql_query($zapytanie_programista_lista); // result while ($wiersz_programista_lista = mysql_fetch_array($wykonaj_programista_lista)){ echo "<option value='" . $wiersz_programista_lista['id'] . "'"; if($wiersz_programista_lista['id'] == $_POST['programista']) echo " selected='selected' "; echo ">"; echo $wiersz_programista_lista['nazwisko']; echo " "; echo $wiersz_programista_lista['imie']; echo "</option>"; } echo "</select>"; //<!--========================Wypełnienie listy z programistami=======================--> if($_POST['opis'] != ''){ echo "<input type='text' name='opis' value='" . $_POST['opis'] . "' />"; }else{ echo "<input type='text' name='opis' value='' />"; } echo "<input type='submit' name='button1' value='SZUKAJ'>"; echo "</form>"; echo "</center>"; echo "</div>"; echo "<div><font size='7'><a href='hide.php'><--Wróć</a></div></font>"; if (isset($_POST['button1'])) { //echo "MARKA: " . $_POST['marka'] . "<br>"; //echo "MODEL: " . $_POST['model'] . "<br>"; //echo "TYP: " . $_POST['typ'] . "<br>"; //echo "PROGRAMISTA: " . $_POST['programista'] . "<br>"; //echo "OPIS: " . $_POST['opis']; echo "<div class='div3'>"; echo "<center>"; $zapytanie="SELECT * from programy"; //query if ($_POST['model'] != "select"){ $zapytanie = $zapytanie . " where id_sterownika=" . $_POST['model']; } if ($_POST['typ'] != "select"){ if (strpos($zapytanie, 'where') !== FALSE){ $zapytanie = $zapytanie . " and id_typu =" . $_POST['typ']; }else{ $zapytanie = $zapytanie . " where id_typu =" . $_POST['typ']; } } if ($_POST['programista'] != "select"){ if (strpos($zapytanie, 'where') !== FALSE){ $zapytanie = $zapytanie . " and id_programisty =" . $_POST['programista']; }else{ $zapytanie = $zapytanie . " where id_programisty =" . $_POST['programista']; } } if ($_POST['opis'] != ""){ if (strpos($zapytanie, 'where') !== FALSE){ $zapytanie = $zapytanie . " and opis like '%" . mysql_real_escape_string($_POST['opis']) . "%'"; }else{ $zapytanie = $zapytanie . " where opis like '%" . mysql_real_escape_string($_POST['opis']) . "%'" ; } } //echo $zapytanie; if (strpos($zapytanie, 'where') !== FALSE){ $wykonaj=mysql_query($zapytanie); // result }else{ echo "<script>"; echo "alert('Musisz wybrać jakieœ kryteria')"; echo "</script>"; } if (mysql_num_rows($wykonaj) == 0){ echo "Nie znalaziono takiego programu.<br>Zmień kryteria i wyszukaj ponownie."; } while ($wiersz = mysql_fetch_array($wykonaj)){ echo "<table border='1' align='center' width='600'>"; echo "<tr>"; echo "<td width='80'>"; echo "ID:"; echo "</td>"; echo "<td>"; echo $wiersz['id']; echo "</td>"; echo "</tr>"; echo "<tr>"; echo "<td width='80'>"; echo "Sterownik:"; echo "</td>"; echo "<td>"; $temp_ster = $wiersz['id_sterownika']; $zapytanie_ster="SELECT * from sterowniki where id=$temp_ster"; //query $wykonaj_ster=mysql_query($zapytanie_ster); // result $wiersz_ster = mysql_fetch_array($wykonaj_ster); echo $wiersz_ster['marka']; echo " "; echo $wiersz_ster['model']; echo "</td>"; echo "</tr>"; ////////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Typ:"; echo "</td>"; echo "<td>"; $temp_typ = $wiersz['id_typu']; $zapytanie_typ="SELECT * from typ_funkcji where id=$temp_typ"; //query $wykonaj_typ=mysql_query($zapytanie_typ); // result $wiersz_typ = mysql_fetch_array($wykonaj_typ); echo $wiersz_typ['typ']; //setcookie("typ", $wiersz_typ['typ']); echo "</td>"; echo "</tr>"; //////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Programista:"; echo "</td>"; echo "<td>"; $temp_programista = $wiersz['id_programisty']; $zapytanie_programista="SELECT * from programisci where id=$temp_programista"; //query $wykonaj_programista=mysql_query($zapytanie_programista); // result $wiersz_programista = mysql_fetch_array($wykonaj_programista); echo $wiersz_programista['imie']; echo " "; echo $wiersz_programista['nazwisko']; echo "</td>"; echo "</tr>"; //////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Wersja:"; echo "</td>"; echo "<td>"; echo $wiersz['wersja']; echo "</td>"; echo "</tr>"; ////////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Data dodania:"; echo "</td>"; echo "<td>"; echo $wiersz['data']; echo "</td>"; echo "</tr>"; //////////////////////////////////////////////////////// echo "<tr>"; echo "<td width='80'>"; echo "Opis:"; echo "</td>"; echo "<td>"; echo $wiersz['opis']; echo "</td>"; echo "</tr>"; echo "<tr>"; echo "<td width='80'>"; echo "Pobierz:"; echo "</td>"; echo "<td>"; $nazwa = $wiersz['pobierz']; //echo $wiersz['pobierz']; echo "<a href='pliki/" . $nazwa . "'>" . $nazwa . "</a>"; echo "</td>"; echo "</tr>"; echo "<tr>"; echo "<td width='80'>"; echo "Usun:"; echo "</td>"; echo "<td>"; $nazwa = $wiersz['pobierz']; //echo $wiersz['pobierz']; echo "<a href='drop.php?usun=".$wiersz['id']."'>-->USUŃ TEN PROGRAM<--</a>"; echo "</td>"; echo "</tr>"; echo "</table>"; echo "<br><br><br>"; } echo "</center>"; echo "</div>"; } }else{ echo "brak dostepu"; } ?> </body> </html> <file_sep>/AUMATIC_BAZA/index.php <?php session_start(); require_once('db.php'); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="css/style.css" rel="stylesheet" type="text/css" /> <title>Witamy w Aumatic Database</title> <meta name="description" content="" /> <meta name="keywords" content="" /> </head> <body> <?php /* jeżeli nie wypełniono formularza - to znaczy nie istnieje zmienna login, hasło i sesja auth * to wyświetl formularz logowania */ if (!isset($_POST['login']) && !isset($_POST['haslo']) && $_SESSION['auth'] == FALSE) { ?> <center> <div style="font-size: 80px;">Witamy w Aumatic database</div> <div style="width: 300px; height:200px; background: #f0f0f0; text-align: left;"> <font size="7">ZALOGUJ SIĘ</font><br><br> <form name="form-logowanie" action="index.php" method="post" > Login: <input type="text" name="login" autocomplete="off" style="width: 250px; float: right;"/><br><br> Hasło: <input type="text" id="passfld" autocomplete="off" name="haslo" style="width: 250px; float: right;"/><br><br> <input type="submit" name="zaloguj" value="Zaloguj" style="width: 300px"/> </form> </div> <br><br> <a href='rejestracja.php'>-->REJESTRACJA<--</a> </center> <script type="text/javascript"> // or in pure javascript window.onload=function(){ setTimeout(function(){ document.getElementById('passfld').type = 'password'; },10); } </script> <?php } /* jeżeli istnieje zmienna login oraz haslo i sesja z autoryzacją użytkownika jest FALSE to wykonaj * skrypt logowania */ elseif (isset($_POST['login']) && isset($_POST['haslo']) && $_SESSION['auth'] == FALSE) { // jeżeli pole z loginem i hasłem nie jest puste if (!empty($_POST['login']) && !empty($_POST['haslo'])) { // dodaje znaki unikowe dla potrzeb poleceń SQL $login = mysql_real_escape_string($_POST['login']); $haslo = mysql_real_escape_string($_POST['haslo']); // szyfruję wpisane hasło za pomocą funkcji md5() $haslo = str_rot13(md5($haslo)); /* zapytanie do bazy danych * mysql_num_rows - sprawdzam ile wierszy odpowiada zapytaniu mysql_query * mysql_query - pobierz wszystkie dane z tabeli user gdzie login i hasło odpowiadają wpisanym danym */ $sql = mysql_num_rows(mysql_query("SELECT * FROM `uzytkownicy` WHERE `login` = '$login' AND `haslo` = '$haslo' AND `block` = '0'")); // jeżeli powyższe zapytanie zwraca 1, to znaczy, że dane zostały wpisane poprawnie i rejestruję sesję if ($sql == 1) { // zmienne sesysje user (z loginem zalogowanego użytkownika) oraz sesja autoryzacyjna ustawiona na TRUE $_SESSION['user'] = $login; $_SESSION['auth'] = TRUE; // przekierwuję użytkownika na stronę z ukrytymi informacjami echo '<meta http-equiv="refresh" content="1; URL=hide.php">'; echo '<p style="padding-top:10px";><strong>Proszę czekać...</strong><br />trwa logowanie i wczytywanie danych</p>'; } // jeżeli zapytanie nie zwróci 1, to wyświetlam komunikat o błędzie podczas logowania else { echo '<p style="padding-top:10px;color:red";>Błąd podczas logowania do systemu<br />'; echo '<a href="index.php">Wróć do formularza</a></p>'; } } // jeżeli pole login lub hasło nie zostało uzupełnione wyświetlam błąd else { echo '<p style="padding-top:10px;color:red";>Błąd podczas logowania do systemu<br />'; echo '<a href="index.php">Wróć do formularza</a></p>'; } } // jeżeli sesja auth jest TRUE to przekieruj na ukrytą podstronę elseif ($_SESSION['auth'] == TRUE && !isset($_GET['logout'])) { echo '<meta http-equiv="refresh" content="1; URL=hide.php">'; echo '<p style="padding-top:10px"><strong>Proszę czekać...</strong><br />trwa wczytywanie danych</p>'; } // wyloguj się elseif ($_SESSION['auth'] == TRUE && isset($_GET['logout'])) { $_SESSION['user'] = ''; $_SESSION['auth'] = FALSE; echo '<meta http-equiv="refresh" content="1; URL=index.php">'; echo '<p style="padding-top:10px"><strong>Proszę czekać...</strong><br />trwa wylogowywanie</p>'; } ?> </body> </html> <file_sep>/AUMATIC_BAZA/hide.php <?php session_start(); //require_once('db.php'); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="css/style.css" rel="stylesheet" type="text/css" /> <title>Panel uzytkownika</title> <meta name="description" content="" /> <meta name="keywords" content="" /> </head> <body> <?php mysql_connect("localhost", "root", "123") or die("Nie można poł±czyć się z MySQL"); mysql_select_db("aumatic") or die("Nie można poł±czyć się z baza danych"); $prawa; ?> <?php if ($_SESSION['auth'] == TRUE) { $zapytanie="SELECT * from uzytkownicy where login = '" . $_SESSION['user'] . "'"; //query $wykonaj=mysql_query($zapytanie); // result while ($wiersz = mysql_fetch_array($wykonaj)){ if ($wiersz['prawa'] != ""){ $prawa = $wiersz['prawa']; } } echo "<div style='background: #f0f0f0; width: 350px; height: 60px; float: right; font-size: 20px'>"; echo "Zalogowany jako: " . $_SESSION['user'] . "<br>Na prawach: " . $prawa . "<br>" ; echo "</div>"; echo "<div style='background: #f0f0f0; width: 250px; height: 60px; float: left; font-size: 40px;'>"; echo '<a href="index.php?logout">Wyloguj się</a>'; echo "</div>"; echo "<div style='font-size: 60px; margin-left:auto; margin-right:auto; width: 500px;'>Aumatic database</div>"; echo "<center> <font size='5'>"; if ($prawa == "junior"){ echo "<a href='read.php'>Przeglądaj baze</a>"; } if ($prawa == "senior"){ echo "<a href='read.php'>Przeglądaj baze</a><br>"; echo "<a href='add.php'>Dodaj program do bazy</a>"; } if ($prawa == "vip"){ echo "<a href='read.php'>Przeglądaj baze</a><br>"; echo "<a href='add.php'>Dodaj program do bazy</a><br>"; echo "<a href='drop.php'>Usuń program z bazy</a>"; } if ($prawa == "admin"){ $count = 0; $zapytanie_count="select * from kandydaci"; $wykonaj_count=mysql_query($zapytanie_count); // result while ($wiersz_count = mysql_fetch_array($wykonaj_count)){ $count++; } echo "<a href='read.php'>Przeglądaj baze</a><br>"; echo "<a href='add_premium.php'>Dodaj program do bazy</a><br>"; echo "<a href='drop.php'>Usuń program z bazy</a><br><br>"; echo "<a href='accept.php'>Zatwierdź nowego użytkownika(" . $count . ")</a><br>"; echo "<a href='users.php'>Usuń/zablokuj użytkownia</a><br>"; //echo "<a href='add_plc.php'>Dodaj nowy sterownik</a><br>"; echo "<a href='add_producent.php'>Dodaj nowego producenta</a><br>"; echo "<a href='add_model.php'>Dodaj model do istniejącego sterownika</a><br>"; echo "<a href='add_type.php'>Dodaj nową klasę funkcji</a><br>"; } echo "</font></center>"; } else { echo '<p style="padding-top:10px;color:white";><strong>Próba nieautoryzowanego dostępu...</strong><br />trwa przenoszenie do formularza logowania</p>'; echo '<meta http-equiv="refresh" content="1; URL=index.php">'; } ?> </body> </html> <file_sep>/AUMATIC_BAZA/add_producent.php <html> <head> <meta http-equiv="Content-Language" content="pl"> <META NAME="Keywords" CONTENT=""> <meta http-equiv="Content-Type" content="text/html; charset=windows-1250"> <title>Dodaj sterownik</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <?php mysql_connect("localhost", "root", "123") or die("Nie można poł±czyć się z MySQL"); mysql_select_db("aumatic") or die("Nie można poł±czyć się z baza danych"); ?> <?php session_start(); //require_once('db.php'); ?> <?php if ($_SESSION['auth'] == TRUE) { $zapytanie="SELECT * from uzytkownicy where login = '" . $_SESSION['user'] . "'"; //query $wykonaj=mysql_query($zapytanie); // result while ($wiersz = mysql_fetch_array($wykonaj)){ if ($wiersz['prawa'] != ""){ $prawa = $wiersz['prawa']; } } } if ($prawa == "admin"){ $tablica_wyborow = array(); echo "<center><font size='7'>Dodaj nowego producenta</center><br></font>"; echo "<div style='float: left'><font size='7'><a href='hide.php'><--Wróć</a></div></font>"; echo "<div style='width: 350px; height:200px; background: #f0f0f0; text-align: left; float: right'>"; echo "<center><font size='5'>Podglądnij istniejących producentów</center><br></font>"; $i=0; $tab = array(); $tab[0][1] = "==PRODUCENCI="; $zapytanie_marka_lista="SELECT * from sterowniki order by marka asc"; //query $wykonaj_marka_lista=mysql_query($zapytanie_marka_lista); // result while ($wiersz_marka_lista = mysql_fetch_array($wykonaj_marka_lista)){ $tab[$i+1][1] = $wiersz_marka_lista['marka']; $tab[$i+1][0] = $wiersz_marka_lista['id']; $i++; } //<!--====================Wypełnianie tablicy z markami================================--> echo "<form action='' method='post' enctype='multipart/form-data'>"; echo "<select name='marka' style='width: 350px' id='marka'>"; $flag = true; for ($i=0; $i<count($tab); $i++){ for($j=0; $j<$i; $j++){ if($tab[$j][1] == $tab[$i][1]){ $flag = false; } } if($flag == true){ echo "<option value='" . $tab[$i][1] . "'"; if($tab[$i][1] == $_POST['marka']) echo " selected='selected' "; echo ">"; echo $tab[$i][1]; echo "</option>"; } $flag = true; } echo "</select>"; echo "<br>"; echo "</form>"; echo "</div>"; echo "<center>"; echo "<div style='width: 350px; height:200px; background: #f0f0f0; text-align: left;'>"; echo "<form action='add_producent.php' method='post' enctype='multipart/form-data'>"; echo "<br>Podaj nazwę producenta: "; echo "<input type='text' name='marka2' style='width: 180px; float: right;'/><br>"; echo "<br>Podaj model (opcjonalne): "; echo "<input type='text' name='model2' style='width: 180px; float: right;'/><br><br>"; echo "<input type='submit' name='button2' value='DODAJ' style='width: 350px; height: 40px;'>"; echo "</form>"; echo "</div>"; echo "</center>"; //var_dump($_POST); if(isset($_POST['button2'])){ if ($_POST['marka2'] !=""){ $zapytanie_model_2="insert into sterowniki (id, marka, model) values ('', '" . mysql_real_escape_string($_POST['marka2']) . "', '" . mysql_real_escape_string($_POST['model2']) . "')"; //query $wykonaj_model_2=mysql_query($zapytanie_model_2); // result echo "<script>"; echo "alert('Sterownik został dodany poprawnie')"; echo "</script>"; }else{ echo "<script>"; echo "alert('Podaj nazwę sterownika')"; echo "</script>"; } } }else{ echo "brak dostepu"; } ?> </body> </html> <file_sep>/AUMATIC_BAZA/add_type.php <html> <head> <meta http-equiv="Content-Language" content="pl"> <META NAME="Keywords" CONTENT=""> <meta http-equiv="Content-Type" content="text/html; charset=windows-1250"> <title>Dodaj typ</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <?php mysql_connect("localhost", "root", "123") or die("Nie można połączyć się z MySQL"); mysql_select_db("aumatic") or die("Nie można połączyć się z baza danych"); ?> <?php session_start(); //require_once('db.php'); ?> <?php if ($_SESSION['auth'] == TRUE) { $zapytanie="SELECT * from uzytkownicy where login = '" . $_SESSION['user'] . "'"; //query $wykonaj=mysql_query($zapytanie); // result while ($wiersz = mysql_fetch_array($wykonaj)){ if ($wiersz['prawa'] != ""){ $prawa = $wiersz['prawa']; } } } if ($prawa == "admin"){ echo "<center><font size='7'>Dodaj klasę funkcji</center><br></font>"; echo "<div style='float: left'><font size='7'><a href='hide.php'><--Wróć</a></div></font>"; echo "<center>"; echo "<div style='width: 300px; height:150px; background: #f0f0f0; text-align: left;'>"; echo "<form action='add_type.php' method='post'>"; echo "<br>Podaj nazwę klasy: "; echo "<input type='text' name='typ' style='float: right'/><br><br>"; echo "<input type='submit' name='button1' value='DODAJ' style='width: 300px; height: 40px;'>"; echo "</form>"; echo "</div>"; echo "</center>"; //var_dump($_POST); if(isset($_POST['button1'])){ $zapytanie="insert into typ_funkcji (id, typ) values ('', '" . mysql_real_escape_string($_POST['typ']) . "')"; //query $wykonaj=mysql_query($zapytanie); // result echo "<script>"; echo "alert('Typ został dodany pomyœlnie')"; echo "</script>"; } }else{ echo "brak dostepu"; } ?> </body> </html> <file_sep>/AUMATIC_BAZA/rejestracja.php <?php session_start(); require_once('db.php'); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="css/style.css" rel="stylesheet" type="text/css" /> <title>Zarejestruj się</title> <meta name="description" content="" /> <meta name="keywords" content="" /> </head> <body> <script type="text/javascript"> // <![CDATA[ function usun_pl(formularz) { for (i = 0; i < formularz.length; i++) { var pole = formularz.elements[i]; if (pole.type != "text" && pole.type != "textarea") continue; var str = ""; for (j = 0; j < pole.value.length; j++) { switch (pole.value.charAt(j)) { case "ą": str += "a"; break; case "ć": str += "c"; break; case "ę": str += "e"; break; case "ł": str += "l"; break; case "ń": str += "n"; break; case "ó": str += "o"; break; case "ś": str += "s"; break; case "ź": str += "z"; break; case "ż": str += "z"; break; case "Ą": str += "A"; break; case "Ć": str += "C"; break; case "Ę": str += "E"; break; case "Ł": str += "L"; break; case "Ń": str += "N"; break; case "Ó": str += "O"; break; case "Ś": str += "S"; break; case "Ź": str += "Z"; break; case "Ż": str += "Z"; break; default: str += pole.value.charAt(j); break; } } pole.value = str; } } // ]]> </script> <center> <div style="font-size: 80px;">Zarejestruj się w Aumatic database</div> <div style="float: left;"><font size='7'><a href='index.php'><--Wróć</a></div></font> <br><br> <div style="width: 400px; height:350px; background: #f0f0f0; text-align: left;"> <font size="7">ZAREJESTRUJ SIĘ</font><br><br> <form name="form-rejestracja" action="rejestracja.php" method="post" onsubmit="usun_pl(this)"> Imie: <input type="text" name="imie" style="width: 300px; float: right;"/><br><br> Nazwisko: <input type="text" name="nazwisko" style="width: 300px; float: right";/><br><br> E-mail: <input type="text" name="mail" style="width: 300px; float: right;"/><br><br> Login: <input type="text" name="login_reje" style="width: 300px; float: right;"/><br><br> Hasło: <input type="password" name="haslo_reje" style="width: 300px; float: right;"/><br><br> <input type="submit" name="zarejestruj" value="Zarejestruj" style="width: 400px; height: 50px"/> </form> </div> </center> <?php if (isset($_POST['zarejestruj'])){ if(($_POST['imie']!="") and ($_POST['nazwisko']!="") and ($_POST['mail']!="") and ($_POST['login_reje']!="") and ($_POST['haslo_reje']!="")){ if (mysql_num_rows(mysql_query("SELECT * FROM `uzytkownicy` WHERE `login` = '" . $_POST['login_reje'] . "'")) == 0){ $zapytanie="INSERT INTO kandydaci (id, imie, nazwisko, mail, login, haslo) VALUES ('', '" . mysql_real_escape_string($_POST['imie'])."', '" . mysql_real_escape_string($_POST['nazwisko'])."', '" . mysql_real_escape_string($_POST['mail'])."', '" . mysql_real_escape_string($_POST['login_reje'])."', '" . str_rot13(md5($_POST['haslo_reje']))."')"; $wykonaj=mysql_query($zapytanie); echo "<script>"; echo "alert('Zgloszenie przyjete, czekaj na zatwierdzenie przez admina');"; echo "</script>"; }else{ echo "<script>"; echo "alert('Twój login już jest zajęty');"; echo "</script>"; } }else{ echo "<script>"; echo "alert('Nie podales wszystkiego');"; echo "</script>"; } } ?> </body> </html>
0fd71fb3b02c21ac6e815476aff12f11c1ff4de1
[ "PHP" ]
10
PHP
marwis95/Aumatic-Database
22e47eb88c8b98aa9d4918ccd6816c22d30d0d9f
abe9da1bcf0c869d9cd7539873b5e935547f2b94
refs/heads/master
<file_sep>class Player attr_accessor :name,:position, :age, :height, :weight @@all = [] def initialize(hash) hash.each{|key, value| self.send("#{key}=", value)} self.class.all << self end def self.all @@all end def self.reset self.all.clear end def self.count self.all.length end end <file_sep>class Scraper def get_page_player doc = Nokogiri::HTML (open("https://www.newyorkredbulls.com/players")) end def get_players self.get_page_player.css('li.row') end def make_player self.get_players.collect do |players| player = {} player[:name] = players.css('div.player_info div.name a').children.first.text player[:position] = players.css('div.player_info span.position').children.first.text player[:age] = players.css('div.birthdate span.stat.age').text player[:height] = players.css('div.stats_container span.stat.height').text player[:weight] = players.css('div.stats_container span.stat.weight').text Player.new(player) #binding.pry end end # def print_players # self.make_player # Player.all.each do |player| # puts "name: #{player.name}" # puts "position: #{player.position}" # puts "age: #{player.age}" # puts "height: #{player.height}" # puts "weight: #{player.weight}" # end end #Scraper.new.make_player <file_sep>class CLI def call welcome list_name puts "\nWich player would you like to know more about" ask_for_input until @input == "exit" more_info ask_for_input end end def welcome puts "Welcome to version 1 of the Redbull Team line up!" end def list_name Scraper.new.make_player Player.all.each_with_index{|player, i| puts "#{i+1}. #{player.name}"} #binding.pry end def ask_for_input puts "\nPlease select between 1 and #{Player.all.length}" puts "To quit, type 'exit'." @input = gets.downcase.strip @input == 'exit' ? goodbye : check_for_input end def goodbye puts "Thanks for visiting the NYC Redbull Soccer team" exit end def check_for_input until @input.match(/^(\d)+$/) && @input.to_i.between?(0, Player.all.length) && @input != 'exit' puts "\nThe input you have typed is not a number within range" ask_for_input end end def more_info player = Player.all[@input.to_i - 1] puts "Player info is as follows:\n Position: #{player.position}\n Age: #{player.age}\n Height: #{player.height}" end end <file_sep>require 'nokogiri' require 'open-uri' require_relative "./redbull_team/player.rb" require_relative "./redbull_team/scraper.rb" require_relative "./redbull_team/cli.rb" require_relative "./redbull_team/version.rb" module RedbullTeam class Error < StandardError; end # Your code goes here... end
8691f2d304269ea1b3619eb1d3796ae7dd262ad7
[ "Ruby" ]
4
Ruby
kjgmez/redbull_team_gem
e8f792772dc59b41d34339380127f220eb5d613f
43a473518e7b4b7d71a87298af7de0c18a66af68
refs/heads/master
<repo_name>bradchao/TCCA_Android_MyIO<file_sep>/app/src/main/java/tw/org/tcca/apps/myio/MainActivity.java package tw.org.tcca.apps.myio; import androidx.appcompat.app.AppCompatActivity; import android.content.ContentValues; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; public class MainActivity extends AppCompatActivity { private SharedPreferences sp; private SharedPreferences.Editor editor; private TextView tv; private String name; private int counter; private boolean sound; private MyDBHelper myDBHelper; private SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myDBHelper = new MyDBHelper(this, "tcca", null, 1); db = myDBHelper.getReadableDatabase(); tv = findViewById(R.id.tv); sp = getSharedPreferences("config", MODE_PRIVATE); editor = sp.edit(); name = sp.getString("name", "nobody"); counter = sp.getInt("counter", 1); sound = sp.getBoolean("sound", true); tv.setText(name +":" + counter + ":" + sound); counter++; editor.putInt("counter", counter); editor.commit(); } public void test1(View view) { name = "Brad"; editor.putString("name", name); editor.putBoolean("sound", false); editor.commit(); } public void test2(View view) { try { FileOutputStream fout = openFileOutput("brad.txt", MODE_PRIVATE); fout.write("Hello, World".getBytes()); fout.flush(); fout.close(); Toast.makeText(this, "Save OK", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } public void test3(View view){ try { FileInputStream fin = openFileInput("brad.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(fin)); String line = reader.readLine(); fin.close(); tv.setText(line); } catch (Exception e) { e.printStackTrace(); } } public void test4(View view){ // SELECT * FROM cust Cursor c = db.query("cust", null, null, null,null, null, null); while (c.moveToNext()){ String id = c.getString(c.getColumnIndex("id")); String cname = c.getString(c.getColumnIndex("cname")); String tel = c.getString(c.getColumnIndex("tel")); Log.v("bradlog", id +":" + cname + ":" + tel); } } public void test5(View view){ ContentValues values = new ContentValues(); values.put("cname", "brad"); values.put("tel", "1234567"); db.insert("cust", null, values); test4(null); } public void test6(View view) { // delete from cust where id = 2; db.delete("cust", "id = ?", new String[]{"2"}); test4(null); } public void test7(View view){ ContentValues values = new ContentValues(); values.put("cname", "peter"); values.put("tel", "7654321"); db.update("cust",values, "id = ?", new String[]{"3"}); } }
bc1b2ee0fde07272f9b17d5cbcdc26befd8dff04
[ "Java" ]
1
Java
bradchao/TCCA_Android_MyIO
b3a9a0029d02cdb251b9b2151e8f01e54557b9e0
8f842a6e13703edeb8367c83ab6e2fb6d4d3ad5a
refs/heads/master
<repo_name>MRomarali/hangMan<file_sep>/src/main/java/se/ecUTB/Omar/Ali/hangMan.java package se.ecUTB.Omar.Ali; import java.util.Random; /** * Hello world! * */ public class hangMan { private static StringBuilder sb = new StringBuilder(); private static String[] secretWord = {"apple","watermelon","orange","pear","cherry","strawberry","nectarine","grape","mango","blueberry", "pomegranate","plum","banana","raspberry","mandarin","papaya","kiwi","pineapple","lime","lemon", "apricot","grapefruit","melon","coconut","avocado","peach"}; public static void main(String[] args) { welcome(); Random random = new Random(); String randomWord = secretWord[random.nextInt(secretWord.length)]; hangManClass hang = new hangManClass(randomWord, 8,0); hang.guess(secretWord[(int) (Math.random() * hang.getHangManSecretWord().length())],hang.getPlayerGuesses(), hang.getGuessedTimes()); sb.append(secretWord); } private static void welcome() { System.out.println("Welcome to my hangman GUESS THE FRUIT Game,\n " + "==============================================\n" + "You have eight guesses total to win the game\n" + "Guess a word by entering space in between or guess using letters.\n" + "you can also complete the letters by writing the remaining words with spaces in between \n" + "if you type the same letter more than once you wont get a minus point.\n" + "\t\t\t\t Good Luck!!\n" + "======================================================================== \n"); } }
d701ba08f4b0dbcf255d6433f7a25d1a69b78a9e
[ "Java" ]
1
Java
MRomarali/hangMan
a101819f45895c6c4a5ee41d9a4a4a6d0cf4a9d1
63f4bd18c4dc36017adccaca41b71d4b5853b2a9
refs/heads/master
<file_sep>export class KairosVerifyRsTransaction { private _status: string; private _subjectId: string; private _quality: number; private _width: number; private _height: number; private _topLeftX: number; private _topLeftY: number; private _confidence: number; private _galleryName: string; private _liveness: number; private _enrollmentTimestamp: string; private _eyeDistance: number; private _faceId: string; private _pitch: number; private _roll: number; /** * Getter liveness * @return {number} */ public get liveness(): number { return this._liveness; } /** * Getter enrollmentTimestamp * @return {string} */ public get enrollmentTimestamp(): string { return this._enrollmentTimestamp; } /** * Getter eyeDistance * @return {number} */ public get eyeDistance(): number { return this._eyeDistance; } /** * Getter faceId * @return {string} */ public get faceId(): string { return this._faceId; } /** * Getter pitch * @return {number} */ public get pitch(): number { return this._pitch; } /** * Getter roll * @return {number} */ public get roll(): number { return this._roll; } /** * Getter yaw * @return {number} */ public get yaw(): number { return this._yaw; } /** * Setter liveness * @param {number} value */ public set liveness(value: number) { this._liveness = value; } /** * Setter enrollmentTimestamp * @param {string} value */ public set enrollmentTimestamp(value: string) { this._enrollmentTimestamp = value; } /** * Setter eyeDistance * @param {number} value */ public set eyeDistance(value: number) { this._eyeDistance = value; } /** * Setter faceId * @param {string} value */ public set faceId(value: string) { this._faceId = value; } /** * Setter pitch * @param {number} value */ public set pitch(value: number) { this._pitch = value; } /** * Setter roll * @param {number} value */ public set roll(value: number) { this._roll = value; } /** * Setter yaw * @param {number} value */ public set yaw(value: number) { this._yaw = value; } private _yaw: number; public get status(): string { return this._status; } public set status(_status: string) { this._status = _status; } public get subjectId(): string { return this._subjectId; } public set subjectId(_subjectId: string) { this._subjectId = _subjectId; } public get quality(): number { return this._quality; } public set quality(_quality: number) { this._quality = _quality; } public get width(): number { return this._width; } public set width(_width: number) { this._width = _width; } public get height(): number { return this._height; } public set height(_height: number) { this._height = _height; } public get topLeftX(): number { return this._topLeftX; } public set topLeftX(_topLeftX: number) { this._topLeftX = _topLeftX; } public get topLeftY(): number { return this._topLeftY; } public set topLeftY(_topLeftY: number) { this._topLeftY = _topLeftY; } public get confidence(): number { return this._confidence; } public set confidence(_confidence: number) { this._confidence = _confidence; } public get galleryName(): string { return this._galleryName; } public set galleryName(_galleryName: string) { this._galleryName = _galleryName; } public static parse(json: any): KairosVerifyRsTransaction { let transaction: KairosVerifyRsTransaction = new KairosVerifyRsTransaction(); transaction.status = json.status; transaction.subjectId = json.subject_id; transaction.quality = json.quality; transaction.width = json.width; transaction.height = json.heigth; transaction.topLeftX = json.topLeftX; transaction.topLeftY = json.topLeftY; transaction.confidence = json.confidence; transaction.galleryName = json.gallery_name; transaction.liveness = json.liveness; transaction.enrollmentTimestamp = json.enrollment_timestamp; transaction.eyeDistance = json.eyeDistance; transaction.faceId = json.face_id; transaction.pitch = json.pitch; transaction.roll = json.roll; transaction.yaw = json.yaw; return transaction; } }<file_sep>export const PAGES = { ImageCapture: "ImageCapturePage" , Home: "HomePage" , Login: "LoginPage" , Welcome: "WelcomePage" };<file_sep>import { KairosEnrollImage } from "./kairos-enroll-image"; export class KairosEnrollRs { private _faceId: string; private _images: KairosEnrollImage[]; /** * Getter faceId * @return {string} */ public get faceId(): string { return this._faceId; } /** * Getter images * @return {KairosEnrollImage[]} */ public get images(): KairosEnrollImage[] { return this._images; } /** * Setter faceId * @param {string} value */ public set faceId(value: string) { this._faceId = value; } /** * Setter images * @param {KairosEnrollImage[]} value */ public set images(value: KairosEnrollImage[]) { this._images = value; } public static parse(json: any): KairosEnrollRs { let kairosEnrollRs: KairosEnrollRs = new KairosEnrollRs(); kairosEnrollRs.faceId = json.face_id; kairosEnrollRs.images = json.images.map(image => KairosEnrollImage.parse(image)); return kairosEnrollRs; } }<file_sep>export class KairosVerifyRq { private _image: string; private _galleryName: string; private _subjectId: string; public get image(): string { return this._image; } public set image(image: string) { this._image = image; } public get galleryName(): string { return this._galleryName; } public set galleryName(galleryName: string) { this._galleryName = galleryName; } public get subjectId(): string { return this._subjectId; } public set subjectId(subjectId: string) { this._subjectId = subjectId; } public stringify(): string { return JSON.stringify( { gallery_name: this.galleryName , subject_id: this.subjectId , image: this.image } ) } }<file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { KairosVerifyRq } from '../../dtos/kairos-verify-rq'; import { KairosVerifyRs } from '../../dtos/kairos-verify-rs'; import { map } from 'rxjs/operators'; import { Props } from '../../shared/properties'; import { CommonProvider } from '../common/common'; import { KairosEnrollRs } from '../../dtos/kairos-enroll-rs'; @Injectable() export class KairosProvider { constructor(public http: HttpClient , private common: CommonProvider) { console.log('Hello KairosProvider Provider'); } enroll(kairosVerifyRq: KairosVerifyRq): Observable<KairosEnrollRs> { let url: string = "https://api.kairos.com/enroll"; let headers: HttpHeaders = new HttpHeaders() .append('Content-Type', 'application/json') .append('app_id', Props.appId) .append('app_key', Props.appKey); kairosVerifyRq.galleryName = Props.galleryName; return this.http.post(url, kairosVerifyRq.stringify(), { headers: headers }) .pipe( map(result => { let resultStr: string = JSON.stringify(result); if (resultStr.includes("Errors")) { let message: string = ''; if (resultStr.includes("5002")) message = 'La imagen capturada no contiene un rostro.'; else message = 'kairos verify with errors: ' + resultStr; this.common.presentAcceptAlert('Reconocimiento Facial Denegado', message); } return KairosEnrollRs.parse(result); }) ); } verify(kairosVerifyRq: KairosVerifyRq): Observable<KairosVerifyRs> { let url: string = "https://api.kairos.com/recognize"; let headers: HttpHeaders = new HttpHeaders() .append('Content-Type', 'application/json') .append('app_id', Props.appId) .append('app_key', Props.appKey); kairosVerifyRq.galleryName = Props.galleryName; return this.http.post(url, kairosVerifyRq.stringify(), { headers: headers }) .pipe( map(result => { let resultStr: string = JSON.stringify(result); let message: string = ''; if (resultStr.includes("Errors")) { if (resultStr.includes("5002")) message = 'La imagen capturada no contiene un rostro.'; else if (resultStr.includes("5004")) message = 'La imagen capturada no coincide con algún perfil facial registrado.'; else message = 'kairos verify with errors: ' + resultStr; this.common.presentAcceptAlert('Reconocimiento Facial Denegado', message); } else if (resultStr.includes("failure")) { message = 'La imagen capturada no coincide con algún perfil facial registrado.'; this.common.presentAcceptAlert('Reconocimiento Facial Denegado', message); } return KairosVerifyRs.parse(result); }) ); } } <file_sep>export class Gender { private _type: string; /** * Getter type * @return {string} */ public get type(): string { return this._type; } /** * Setter type * @param {string} value */ public set type(value: string) { this._type = value; } public static parse(json: any): Gender { let gender: Gender = new Gender(); gender.type = json.type; return gender; } }<file_sep>export const Props = { appId: "269fafa4" , appKey: "3770148d0a9897b6d6f289792ff6deee" , galleryName: "secure-identity-dev-2020-11-23" }<file_sep>import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { KairosVerifyRq } from '../../dtos/kairos-verify-rq'; import { KairosVerifyRs } from '../../dtos/kairos-verify-rs'; import { CommonProvider } from '../../providers/common/common'; import { KairosProvider } from '../../providers/kairos/kairos'; import { PAGES } from '../../shared/pages'; import { PATIENTS } from '../../shared/patients'; @IonicPage() @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { private readonly faceImageShadow: string = '../../assets/imgs/person-shadow.png'; private formGroup: FormGroup; private faceImage: string = this.faceImageShadow; constructor(public navCtrl: NavController , private navParams: NavParams , private kairosProvider: KairosProvider , private formBuilder: FormBuilder , private common: CommonProvider) { this.formGroup = this.formBuilder.group({ nombreFormCtrl: [ '' , Validators.compose([]) ], apellidoFormCtrl: [ '' , Validators.compose([]) ], documentoIdentidadFormCtrl: [ '' , Validators.compose([ ]) ], idFormulaFormCtrl: [ '' , Validators.compose([]) ] }); } ionViewWillEnter(): void { let image = this.navParams.get('image') || null; if (image) this.faceImage = image; } captureImage(): void { this.navCtrl.push(PAGES.ImageCapture); } captureFingerprint(): void { } validarIdentidad(): void { if (!this.formGroup.valid) return; let kairosVerifyRq: KairosVerifyRq = new KairosVerifyRq(); kairosVerifyRq.subjectId = this.formGroup.value.documentoIdentidadFormCtrl; kairosVerifyRq.image = this.faceImage; this.kairosProvider.verify(kairosVerifyRq).subscribe( (kairosVerifyRs: KairosVerifyRs): void => { console.log('Kairos response: ' + JSON.stringify(kairosVerifyRs)); let patient = PATIENTS.find((_patient) => _patient.id == kairosVerifyRs.images[0].transaction.subjectId); let message: string = 'El paciente ' + patient.name + ' ' + patient.surname + ' con cédula de ciudadanína número ' + patient.id + ' está autorizado para realizar la transacción requerida.'; this.common.presentAcceptAlert('Autenticación Exitosa!', message); this.formGroup.controls['nombreFormCtrl'].setValue(patient.name); this.formGroup.controls['apellidoFormCtrl'].setValue(patient.surname); this.formGroup.controls['documentoIdentidadFormCtrl'].setValue(patient.id); }, (error: any): void => { this.common.presentAcceptAlert('Alerta', "kairosProvider.verify error: " + error); } ); } reset(): void { this.faceImage = this.faceImageShadow; this.formGroup.reset(); } }<file_sep>export const PATIENTS = [ { "id": "1152449035" , "name": "Gersain" , "surname": "<NAME>" }, { "id": "8163442" , "name": "<NAME>" , "surname": "<NAME>" }, { "id": "1128470162" , "name": "Duván" , "surname": "Corrales" } ]<file_sep>import { Attributes } from "./attributes"; import { KairosVerifyRsTransaction } from "./kairos-verify-rs-transaction"; export class KairosEnrollImage { private _attributes: Attributes; private _transaction: KairosVerifyRsTransaction; /** * Getter attributes * @return {Attributes} */ public get attributes(): Attributes { return this._attributes; } /** * Setter attributes * @param {Attributes} value */ public set attributes(value: Attributes) { this._attributes = value; } public get transaction(): KairosVerifyRsTransaction { return this._transaction; } public set transaction(transaction: KairosVerifyRsTransaction) { this._transaction = transaction; } public static parse(json: any): KairosEnrollImage { let image: KairosEnrollImage = new KairosEnrollImage(); image.attributes = Attributes.parse(json.attributes); image.transaction = KairosVerifyRsTransaction.parse(json.transaction); return image; } }<file_sep>import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { KairosEnrollRs } from '../../dtos/kairos-enroll-rs'; import { KairosVerifyRq } from '../../dtos/kairos-verify-rq'; import { CommonProvider } from '../../providers/common/common'; import { KairosProvider } from '../../providers/kairos/kairos'; import { PAGES } from '../../shared/pages'; @IonicPage() @Component({ selector: 'page-enrollment', templateUrl: 'enrollment.html', }) export class EnrollmentPage { private readonly faceImageShadow: string = '../../assets/imgs/person-shadow.png'; private formGroup: FormGroup; private faceImage: string = this.faceImageShadow; constructor(public navCtrl: NavController , public navParams: NavParams , private kairosProvider: KairosProvider , private formBuilder: FormBuilder , private common: CommonProvider) { this.formGroup = this.formBuilder.group({ nombreFormCtrl: [ '' , Validators.compose([]) ], apellidoFormCtrl: [ '' , Validators.compose([]) ], documentoIdentidadFormCtrl: [ '' , Validators.compose([ Validators.required ]) ], idFormulaFormCtrl: [ '' , Validators.compose([]) ] }); } ionViewWillEnter(): void { let image = this.navParams.get('image') || null; if (image) this.faceImage = image; } captureImage(): void { this.navCtrl.push(PAGES.ImageCapture); } captureFingerprint(): void { } enroll(): void { if (!this.formGroup.valid) return; let kairosVerifyRq: KairosVerifyRq = new KairosVerifyRq(); kairosVerifyRq.subjectId = this.formGroup.value.documentoIdentidadFormCtrl; kairosVerifyRq.image = this.faceImage; this.kairosProvider.enroll(kairosVerifyRq).subscribe( (kairosEnrollRs: KairosEnrollRs): void => { console.log('Kairos response: ' + JSON.stringify(kairosEnrollRs)); let patient = { "id": this.formGroup.value.documentoIdentidadFormCtrl , "name": this.formGroup.value.nombreFormCtrl , "surname": this.formGroup.value.apellidoFormCtrl }; let message: string = 'El paciente ' + patient.name + ' ' + patient.surname + ' con cédula de ciudadanína número ' + patient.id + ' ha sido inscrito exitosamente a biometría facial.'; this.common.presentAcceptAlert('Inscripción Exitosa!', message); }, (error: any): void => { this.common.presentAcceptAlert('Alerta', "kairosProvider.verify error: " + error); } ); } reset(): void { this.faceImage = this.faceImageShadow; this.formGroup.reset(); } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { EnrollmentPage } from './enrollment'; @NgModule({ declarations: [ EnrollmentPage, ], imports: [ IonicPageModule.forChild(EnrollmentPage), ], }) export class EnrollmentPageModule {} <file_sep>import { KairosVerifyRsTransaction } from "./kairos-verify-rs-transaction"; export class KairosVerifyRsImage { private _transaction: KairosVerifyRsTransaction; public get transaction(): KairosVerifyRsTransaction { return this._transaction; } public set transaction(transaction: KairosVerifyRsTransaction) { this._transaction = transaction; } public static parse(json: any): KairosVerifyRsImage { let image: KairosVerifyRsImage = new KairosVerifyRsImage(); image.transaction = KairosVerifyRsTransaction.parse(json.transaction); return image; } }<file_sep>import { KairosVerifyRsImage } from "./kairos-verify-rs-image"; export class KairosVerifyRs { private _images: KairosVerifyRsImage[]; public get images(): KairosVerifyRsImage[] { return this._images; } public set images(images: KairosVerifyRsImage[]) { this._images = images; } public static parse(json: any): KairosVerifyRs { let kairosVerifyRs: KairosVerifyRs = new KairosVerifyRs(); kairosVerifyRs.images = json.images.map(image => KairosVerifyRsImage.parse(image)); return kairosVerifyRs; } }<file_sep>import { Gender } from "./gender"; export class Attributes { private _lips: string; private _asian: number; private _gender: Gender; private _age: number; private _hispanic: number; private _other: number; private _black: number; private _white: number; private _glasses: string; /** * Getter lips * @return {string} */ public get lips(): string { return this._lips; } /** * Getter asian * @return {number} */ public get asian(): number { return this._asian; } /** * Getter gender * @return {Gender} */ public get gender(): Gender { return this._gender; } /** * Getter age * @return {number} */ public get age(): number { return this._age; } /** * Getter hispanic * @return {number} */ public get hispanic(): number { return this._hispanic; } /** * Getter other * @return {number} */ public get other(): number { return this._other; } /** * Getter black * @return {number} */ public get black(): number { return this._black; } /** * Getter white * @return {number} */ public get white(): number { return this._white; } /** * Getter glasses * @return {string} */ public get glasses(): string { return this._glasses; } /** * Setter lips * @param {string} value */ public set lips(value: string) { this._lips = value; } /** * Setter asian * @param {number} value */ public set asian(value: number) { this._asian = value; } /** * Setter gender * @param {Gender} value */ public set gender(value: Gender) { this._gender = value; } /** * Setter age * @param {number} value */ public set age(value: number) { this._age = value; } /** * Setter hispanic * @param {number} value */ public set hispanic(value: number) { this._hispanic = value; } /** * Setter other * @param {number} value */ public set other(value: number) { this._other = value; } /** * Setter black * @param {number} value */ public set black(value: number) { this._black = value; } /** * Setter white * @param {number} value */ public set white(value: number) { this._white = value; } /** * Setter glasses * @param {string} value */ public set glasses(value: string) { this._glasses = value; } public static parse(json: any): Attributes { let attributes: Attributes = new Attributes(); attributes.age = json.age; attributes.asian = json.asian; attributes.black = json.black; attributes.gender = Gender.parse(json.gender); attributes.glasses = json.glasses; attributes.hispanic = json.hispanic; attributes.lips = json.lips; attributes.other = json.other; attributes.white = json.white; return attributes; } }<file_sep>import { Injectable, Injector } from '@angular/core'; import { AlertController, Alert, AlertOptions, Loading, LoadingController, ToastController, Platform, Events, ModalController, ModalOptions, Modal, NavOptions } from 'ionic-angular'; @Injectable() export class CommonProvider { private static injector: Injector; private loading: Loading; private alert: Alert; private modalStack: Modal[] = new Array<Modal>(); loader: any; static alert: any; //urlServidor:string = "http://192.168.3.11:8095"; // publica //urlServidor: string = "http://172.16.0.20:8095"; urlServidor: string = "http://172.16.0.20:9095"; submenu = { sHuellas: false, sAvistamientos: false, sEntorno: false, sOrdenamiento: false, sVigias: false, sMovilidad: false, sConcursoFotografia: false }; stackActiveLayersSubcapas: number[] = new Array(); /* menuPreferencias = { Huellas: false, Avistamientos: false, Entorno: false, Ordenamiento: false, Vigias: false, Movilidad: false }; */ capas = [] activeLayers = { ids: [], level: '' } constructor( private modalCtrl: ModalController , private loadingCtrl: LoadingController , private toastCtrl: ToastController , public alertCtrl: AlertController , public platform: Platform){ this.alertCtrl.create(); CommonProvider.alert = this.alertCtrl; } createModal(component: any, data?: any, opts?: ModalOptions): Modal { let modal: Modal = this.modalCtrl.create(component, data, opts); this.modalStack.push(modal); return modal; } dismissModal(data?: any, role?: string, navOptions?: NavOptions): Promise<any> { if (this.canDismissModal()) { // console.log('dismissing modal'); let modal: Modal = this.modalStack.pop(); return modal.dismiss(data, role, navOptions); } return null; } canDismissModal(): boolean { console.log('modalStack ' + this.modalStack.length); return this.modalStack.length > 0; } presentAcceptAlert(title: string, message: string, onAccept?: () => void): void { if (this.alert) return; let options: AlertOptions = { title: title, enableBackdropDismiss: true, message: message, buttons: [ { text: 'Aceptar', role: 'cancel', handler: onAccept } ] }; this.alert = this.alertCtrl.create(options); this.alert.onDidDismiss((data: any, role: string) => { this.alert = null; }); this.alert.present(); } dissmisAlert() { if (this.alert) this.alert.dismiss(); } presentAcceptCancelAlert(title: string, message: string, onAccept: () => void) { if (this.alert) return; let options: AlertOptions = { title: title, enableBackdropDismiss: true, message: message, buttons: [ { text: 'Aceptar', handler: onAccept }, { text: 'Regresar' }, { text: '', cssClass: 'closeBt', } ] }; this.alert = this.alertCtrl.create(options); this.alert.onDidDismiss((data: any, role: string) => { this.alert = null; }); this.alert.present(); } presentAlert(alertOptions: AlertOptions): void { if (this.alert) return; this.alert = this.alertCtrl.create(alertOptions); this.alert.onDidDismiss((data: any, role: string) => { this.alert = null; }); this.alert.present(); } presentLoading(): void { if (this.loading) return; this.loading = this.loadingCtrl.create({ content: "Un momento por favor...", }); this.loading.present(); } presentLoadingCancel(): void { if (this.loading) return; this.loading = this.loadingCtrl.create({ content: "Un momento por favor...", enableBackdropDismiss: true, }); this.loading.present(); } presentFullLoading(): void { if (this.loading) return; this.loading = this.loadingCtrl.create({ spinner: 'hide', content: '<img src="assets/logo3.png"/>', cssClass: 'custom-loading', }); this.loading.present(); } dismissLoading(): void { if (this.loading) { this.loading.dismissAll(); this.loading = null; } } appLoading(mensajeLoading, duration: any) { let loading = this.loadingCtrl.create({ spinner: 'hide', content: ` <div class="custom-spinner-container"> <ion-spinner name="bubbles"></ion-spinner> <!-- <div class="custom-spinner-box"></div>--> <h5>`+ mensajeLoading + `</h5> </div>`, duration: duration || 5000 }); loading.onDidDismiss(() => { console.log('Dismissed loading'); }); loading.present(); } appToast(objetoToast: any) { let toast = this.toastCtrl.create({ message: objetoToast.mensaje, duration: objetoToast.duration, position: objetoToast.posicion }); toast.onDidDismiss(() => { console.log('Dismissed toast'); }); toast.present(); } menuApp(opocion, valor) { this.submenu[opocion] = valor; } generalAlert(pTitle, pSubtitle) { let alert = this.alertCtrl.create({ title: '<ion-toolbar color="primary">' + pTitle + '</ion-toolbar>', subTitle: pSubtitle, enableBackdropDismiss: true, buttons: [ { text: 'Aceptar', handler: () => { //this.platform.exitApp(); } }, { text: '', cssClass: 'closeBt', handler: () => { // reject(false); } } ], cssClass: '{background-color: white; color: red; button{ color: red;}}' }); alert.present(); } basicAlert(titulo: string, mensaje: string, ) { let alert = CommonProvider.alert.create({ title: titulo, enableBackdropDismiss: true, subTitle: mensaje, cssClass: 'alertAv', buttons: [ { text: 'Aceptar', }, { text: '', cssClass: 'closeBt', } ] }); alert.present(); } confirmAlert(titulo: string, mensaje: string, ) { return new Promise((resolve, reject) => { let alert = CommonProvider.alert.create({ title: titulo, enableBackdropDismiss: true, subTitle: mensaje, cssClass: 'warning alertAv', buttons: [ { text: 'Cancelar', handler: () => { reject(false); } }, { text: 'Aceptar', handler: () => { resolve(true); } }, { text: '', cssClass: 'closeBt', handler: () => { reject(false); } } ] }); alert.present(); }); } confirmAlertCss(titulo: string, mensaje: string, cssClass: string) { return new Promise((resolve, reject) => { let alert = CommonProvider.alert.create({ title: titulo, enableBackdropDismiss: true, subTitle: mensaje, cssClass: 'warning alertAv sGenRep', buttons: [ { text: 'Regresar', handler: () => { reject(false); } }, { text: 'Aceptar', handler: () => { resolve(true); } }, { text: '', cssClass: 'closeBt', handler: () => { reject(false); } } ] }); alert.present(); }); } basicAlePrtCss(titulo: string, mensaje: string, css: string, boton: string) { return new Promise((resolve, reject) => { let alert = CommonProvider.alert.create({ title: titulo, enableBackdropDismiss: true, cssClass: css, subTitle: mensaje, buttons: [ { text: boton, handler: () => { resolve(true); } }, { text: '', cssClass: 'closeBt', handler: () => { reject(false); } } ] }); alert.present(); }); } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { ImageCapturePage } from './image-capture'; @NgModule({ declarations: [ ImageCapturePage, ], imports: [ IonicPageModule.forChild(ImageCapturePage), ], }) export class ImageCapturePageModule {}
f125b145ec4e862361df9f4a8e24e45582fb4b67
[ "TypeScript" ]
17
TypeScript
blackgersain/secure-identity
6688e0c471b1d78c268dab37bd4d32145d89148a
98bd233b5db16bc2c793f37df2d0502fb53f492e
refs/heads/master
<file_sep>import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.*; public class TSALine implements Comparator<Passenger> { public ArrayList<Passenger> passengers = new ArrayList<Passenger>(); public PriorityQueue<Passenger> priorityQueue = new PriorityQueue<Passenger>(); public Agent agent; public static final String [] traits = {"Female", "Male", "Transgendered", "Hermaphrodite", "Epicene", "USA", "Canada", "Central America", "South America", "Western Europe", "Eastern Europe", "Middle Eastern", "North African", "African", "South Asian", "South East Asian", "Asian", "Aussie", "Kiwi", "Polynesian", "Outer Space", "Antarctican", "Lowest levels of the deep sea", "human", "alien", "ancients", "monster", "mutants"}; public TSALine(Agent agent) { this.agent = agent; } public void buildQueue() { for (int i = 0; i < this.passengers.size(); i++) { Passenger passenger = this.passengers.get(i); this.priorityQueue.add(passenger); } } public int compare(Passenger a, Passenger b) { int dangerLevelA = a.dangerLevel; int dangerLevelB = b.dangerLevel; if (dangerLevelA < dangerLevelB) { return 1; } else if (dangerLevelA > dangerLevelB) { return -1; } else { return 0; } } public boolean shouldInterrogate(Passenger p) { String gender = getGenderForPassenger(p); int dangerLevel = p.dangerLevel; if (this.agent.dislikes.contains(gender)) { dangerLevel+= 2; } if (this.agent.dislikes.contains(p.origin)) { dangerLevel+= 2; } if (this.agent.dislikes.contains(p.species)) { dangerLevel+= 2; } if (this.agent.likes.contains(gender)) { dangerLevel-= 2; } if (this.agent.likes.contains(p.origin)) { dangerLevel-= 2; } if (this.agent.likes.contains(p.species)) { dangerLevel-= 2; } if (dangerLevel < 10 - this.agent.paranoiaLevel) { return false; } else { return true; } } public String getGenderForPassenger(Passenger p) { return this.traits[p.gender]; } public String toString() { return "{TSALine: # of passengers: " + this.passengers.size() + " \n PQsize: " + this.priorityQueue.size() + "\n pqPeak: " + this.priorityQueue.peek() + "\npriorityQueue: " + this.priorityQueue + "}"; } }<file_sep>import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.*; public class Reader { public static final String [] traits = {"Female", "Male", "Transgendered", "Hermaphrodite", "Epicene", "USA", "Canada", "Central America", "South America", "Western Europe", "Eastern Europe", "Middle Eastern", "North African", "African", "South Asian", "South East Asian", "Asian", "Aussie", "Kiwi", "Polynesian", "Outer Space", "Antarctican", "Lowest levels of the deep sea", "human", "alien", "ancients", "monster", "mutants"}; public ArrayList<Agent> agents = new ArrayList<Agent>(); public ArrayList<Passenger> passengers = new ArrayList<Passenger>(); public ArrayList<TSALine> lines = new ArrayList<TSALine>(); public ArrayList<String> arrayOfLinesForFileName(String fileName) throws IOException { DataInputStream input = new DataInputStream(new FileInputStream(fileName)); ArrayList<String> lines = new ArrayList<String>(); while (input.available() > 0) { String z = input.readLine(); lines.add(z); } input.close(); return lines; } public void buildAgents() throws IOException{ ArrayList<String> arrayOfLines = this.arrayOfLinesForFileName("data.dat"); String firstLine = arrayOfLines.get(0); String delims = "[ ]+"; String[] tokens = firstLine.split(delims); int numberOfAgents = Integer.parseInt(tokens[0]); int numberOfPassengers = Integer.parseInt(tokens[1]); for (int i = 1; i < 1 + numberOfAgents * 3; i+= 3) { String lineInfo = arrayOfLines.get(i); String lineLikes = arrayOfLines.get(i + 1); String lineDislikes = arrayOfLines.get(i + 2); tokens = lineInfo.split(delims); String firstName = tokens[0]; String lastName = tokens[1]; int age = Integer.parseInt(tokens[2]); int gender = Integer.parseInt(tokens[3]); int paranoia = Integer.parseInt(tokens[4]); tokens = lineLikes.split(delims); ArrayList<String> likes = new ArrayList<String>(); for (int j = 0; j < tokens.length; j++) { String like = traits[Integer.parseInt(tokens[j])]; likes.add(like); } tokens = lineDislikes.split(delims); ArrayList<String> dislikes = new ArrayList<String>(); for (int k = 0; k < tokens.length; k++) { String dislike = traits[Integer.parseInt(tokens[k])]; dislikes.add(dislike); } Agent agent = new Agent(firstName,lastName,age,gender,paranoia,likes,dislikes); this.agents.add(agent); } } public void buildPassengers() throws IOException { ArrayList<String> arrayOfLines = this.arrayOfLinesForFileName("data.dat"); String firstLine = arrayOfLines.get(0); String delims = "[ ]+"; String[] tokens = firstLine.split(delims); int numberOfAgents = Integer.parseInt(tokens[0]); int numberOfPassengers = Integer.parseInt(tokens[1]); for (int i = 1 + 3 * numberOfAgents; i <= 3 * numberOfAgents + numberOfPassengers; i++) { String lineInfo = arrayOfLines.get(i); tokens = lineInfo.split(delims); String firstName = tokens[0]; String lastName = tokens[1]; int age = Integer.parseInt(tokens[2]); int gender = Integer.parseInt(tokens[3]); String origin = traits[Integer.parseInt(tokens[4])]; String species = traits[Integer.parseInt(tokens[5])]; int dangerLevel = Integer.parseInt(tokens[6]); boolean isThreat = intToBool(Integer.parseInt(tokens[7])); Passenger passenger = new Passenger(firstName, lastName, age, gender, origin, species, dangerLevel, isThreat); this.passengers.add(passenger); } } public boolean intToBool(int intToBeConverted) { if (intToBeConverted == 1) { return true; } else { return false; }} public void sortAgents() { Collections.sort(this.agents); Collections.reverse(this.agents); } public void createLinesAndSetAgents() { for (int i = 0; i < this.agents.size(); i++) { TSALine line = new TSALine(this.agents.get(i)); this.lines.add(line); System.out.println(line.agent.firstName + " " + line.agent.lastName + "(" + line.agent.age + ") is being assigned to line " + i); } } public void addPassengersToLines() { for (int i = 0; i < passengers.size(); i++) { // index = (age - gender + origin + species) % t (where t is the number of lines, or TSA agents) Passenger passenger = this.passengers.get(i); int indexOfLineForPassenger = (passenger.age - passenger.gender + passenger.getOriginAsInt() + passenger.getSpeciesAsInt()) % this.agents.size(); TSALine line = this.lines.get(indexOfLineForPassenger); line.passengers.add(passenger); } for (int i = 0; i < this.lines.size(); i++) { this.lines.get(i).buildQueue(); } //you added all the passengers to their corresponding lines without testing it, you now have to build the passengerLines into a priority queue // } public static void main (String[] args) throws IOException{ System.out.println("\n\n Starting TSA Simulation.... w00t"); Reader reader = new Reader(); reader.buildAgents(); reader.buildPassengers(); reader.sortAgents(); reader.createLinesAndSetAgents(); reader.addPassengersToLines(); for (int i = 0; i < reader.lines.size(); i++) { TSALine line = reader.lines.get(i); for (int j = 0; j < line.passengers.size(); j++) { Passenger passenger = line.priorityQueue.poll(); boolean shouldInterrogate = line.shouldInterrogate(passenger); if (shouldInterrogate) { System.out.println(passenger.firstName + " " + passenger.lastName + " is being interrogated."); } else { System.out.println(passenger.firstName + " " + passenger.lastName + " is moving on without interrogation."); } } } System.out.println("\n Done with TSA Simulation.... w00t\n\n"); } }
8ca768a22de9644fd8c1f25d38039b265c8dd18c
[ "Java" ]
2
Java
shakked/facebook
2327883fbb6353e5d224531a1a2d4552fd3f0548
ba017c50e25d8cd87ebe105ad0e34f72d80fd1c3
refs/heads/master
<file_sep>// concurrency project main.go package main import ( "fmt" ) func main() { c := make(chan int) defer close(c) fmt.Println("Main - Welcome ") go func() { fmt.Println("Goroutine - 0") c <- 10 //Send (blocks) }() a := <-c //Receive from Goroutine 0 and unblocks go func() { fmt.Println("Goroutine - 1") c <- 20 //Send (blocks) }() b := <-c //Receive from Goroutine 1 and unblocks go func() { fmt.Println("Goroutine - 2") c <- 30 //Send (blocks) }() d := <-c //Receive from Goroutine 2 and unblocks go func() { fmt.Println("Goroutine - 3") c <- 40 //Send (blocks) }() e := <-c //Receive from Goroutine 3 and unblocks fmt.Printf("%d, %d , %d, %d \n", a, b, d, e) } /****** final output ******************* Main - Welcome Goroutine - 0 Goroutine - 1 Goroutine - 2 Goroutine - 3 10, 20 , 30, 40 *****************************************/ <file_sep>// concurrency project main.go package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup var m sync.Mutex defer wg.Wait() fmt.Println("Main - Welcome ") wg.Add(1) m.Lock() go func() { fmt.Println("Goroutine - 0") wg.Done() m.Unlock() }() wg.Add(1) m.Lock() go func() { fmt.Println("Goroutine - 1") m.Unlock() wg.Done() }() wg.Add(1) m.Lock() go func() { fmt.Println("Goroutine - 2") m.Unlock() wg.Done() }() wg.Add(1) m.Lock() go func() { fmt.Println("Goroutine - 3") m.Unlock() wg.Done() }() } /****** final output ******************* Main - Welcome Goroutine - 0 Goroutine - 1 Goroutine - 2 Goroutine - 3 *****************************************/ <file_sep># golang_concurrency_examples Golang Concurrency Examples
b3c7af96dc6124deedf29b9b778407d490ba27d1
[ "Markdown", "Go" ]
3
Go
asheikm/golang_concurrency_examples
208e8455f42a1879bff403e938f27fc27d8baa6f
4d0432e50223d360466baf942cc3fbb17988aa7a
refs/heads/main
<file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import Swal from 'sweetalert2' import { NewsService } from '../core/news.service'; @Component({ selector: 'app-register-news', templateUrl: './register-news.component.html', styleUrls: ['./register-news.component.scss'] }) export class RegisterNewsComponent implements OnInit { formRegister: FormGroup; categories: any = []; authors: any = []; constructor(private fb: FormBuilder, private newsService: NewsService) { } initializedForm() { this.formRegister = this.fb.group({ title: ['', Validators.required], shortContent: ['', Validators.required], content: ['', Validators.required], urlImage: ['', Validators.required], category: ['', Validators.required], author: ['', Validators.required] }); } ngOnInit(): void { this.initializedForm(); this.getCategories(); this.getAuthors(); } register() { if (!this.formRegister.valid) { Swal.fire({ icon: 'error', title: 'Campos Vacios', text: 'Debes completar todos los campos para poder Registrar la Noticia', }); } else { const dataRegister = this.formRegister.value; let data = { tittle: dataRegister.title, short_content: dataRegister.shortContent, content: dataRegister.content, image: dataRegister.urlImage, id_category: dataRegister.category, author: dataRegister.author, avatar_author: dataRegister.author } this.newsService.insertNews(data).subscribe( res => { Swal.fire({ title: '<strong>Registro Exitoso!</strong>', icon: 'success', html: 'Tu Registro ha sido completado con Exito, ', confirmButtonText: '<i class="fa fa-thumbs-up"></i> Entendido!', }); this.initializedForm(); }, error => { } ); } } getCategories() { this.newsService.getCategories().subscribe( (res) => { this.categories = res.map((obj) => { return { id: obj.id, nom: obj.nom }; }); }, (error) => { console.log(error); } ); } getAuthors() { this.newsService.getAuthors().subscribe( (res) => { this.authors = res.data.map((obj) => { return { id: obj.id, name: obj.name, nom: obj.avatar_author }; }); }, (error) => { console.log(error); } ); } } <file_sep>import { Injectable } from '@angular/core'; import { environment } from 'src/environments/environment'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class NewsService { constructor(private http : HttpClient) { } getCategories() { return this.http.get<any>(environment.apiUrl + 'categories'); } insertNews(data) { const headers = new HttpHeaders() .set('Content-Type', 'application/json'); return this.http.post<any>(environment.apiUrl + 'news-create', data, { headers }); } getAuthors() { return this.http.get<any>(environment.apiUrl + 'authors'); } } <file_sep>import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RegisterNewsRoutingModule } from './register-news-routing.module'; import { RegisterNewsComponent } from './register-news.component'; @NgModule({ declarations: [RegisterNewsComponent ], imports: [ RegisterNewsRoutingModule, CommonModule, ReactiveFormsModule, FormsModule ], providers: [], bootstrap: [RegisterNewsComponent], }) export class RegisterNewsModule { }
e84365ff24e57aa3f8ff4c7de993d8d05c1aa27d
[ "TypeScript" ]
3
TypeScript
kiuromero/admin-cerro-landig-front
cfaa2adfcebd5707724b95ce12321b0c8fdb7e5f
985412d07787ccc8ef6b1de6a73d1247cc85c855
refs/heads/master
<repo_name>9Harkonnen6/Yet_Another_isThisPrime<file_sep>/isThisPrime.py while True: try: liczba = int(input('Give me a number: ')) if liczba > 0: for i in range(2, liczba): if (liczba % i) == 0: print(liczba, 'That aint prime number!') break else: print(liczba, 'YEAH, IT IS A PRIME!') else: print('ERROR, input <0') except ValueError: print('Oops! That aint number at all!') <file_sep>/README.md # Yet-Another-isThisPrime Just me horsing around with some Python.
e58a4ee48993755c062fe37d08e0ef3823d47005
[ "Markdown", "Python" ]
2
Python
9Harkonnen6/Yet_Another_isThisPrime
075126481121859a95c73c1bfd338ca055c73278
41f21c1ef43c8a3d520599681929393b38357530
refs/heads/master
<file_sep>require('dotenv').config(); const express = require('express'); const cors = require('cors'); const app = express(); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); //const mySecret = process.env['MONGO_URI']; const mySecret = "mongodb+srv://jensoni:KvvTNJgUr0LQP0JC@cluster0.9gvk4.mongodb.net/db1?retryWrites=true&w=majority\n"; // Basic Configuration const port = process.env.PORT || 3000; app.use(bodyParser.urlencoded({ extended: false })) app.use(cors()); app.use('/public', express.static(`${process.cwd()}/public`)); mongoose.connect(mySecret, { useNewUrlParser: true, useUnifiedTopology: true }); let linkSchema = new mongoose.Schema({ age: Number, name: {type: String, required: true} }) let Linker = mongoose.model("Link", linkSchema); app.post("/api/shorturl", (req,res)=>{ let regex = /^http:\/\/|^https:\/\//g; let currNum = -1; let uri = req.body.url; if(regex.test(uri)){ Linker.findOne({}).sort({age:'desc'}).exec((err, data) =>{ if(!err){ if(data==null){currNum=1} else{currNum = data.age + 1;} Linker.findOneAndUpdate({name:uri}, {name:uri, age:currNum}, {new:true, upsert:true},(err,data)=>{ if(err){ res.send("error"); } else{ res.json({original_url : uri, short_url : currNum}) } }) } else{ res.send(err); } }) } else{ res.json({error: 'invalid url'}) } }) app.get("/api/shorturl/:short", (req,res)=>{ let short = req.params.short; let regex = /^\d+/g; if(regex.test(short)){ // res.send(short) Linker.findOne({age:short},(err,data)=>{ if(!err && data!=null){ console.log("here",data.name); res.redirect(data.name) } else{ res.send("Data not found") } }) } else{ res.send("Data not found") } }) app.get('/', function(req, res) { res.sendFile(process.cwd() + '/views/index.html'); }); // Your first API endpoint app.get('/api/hello', function(req, res) { res.json({ greeting: 'hello API' }); }); app.listen(port, function() { console.log(`Listening on port ${port}`); });
89c92eda72eb90e78d6219bc7b339357bb8ada93
[ "JavaScript" ]
1
JavaScript
XThePresenceX/url-shortener
594969e12640e3b71316bb96c585375a324bc7c9
acbdc690477497a7fc0d2f198731c423af849114
refs/heads/master
<file_sep>/** * AddingMachine.java - Second version * @author <NAME> * @data 10/05/2020 * @version 2.0 * @github https://github.com/wen7752/cse360assignment02 */ package cse360assignment02; public class AddingMachine { //initialize the variables private int total; private String result = "0"; public AddingMachine () { total = 0; result = "0"; } //return the total public int getTotal () { return total; } /** * adding the value to total and store the value * into the result string. */ public void add (int value) { total = total + value; //add to the result result = result + " + " + value; //add to the string } /** * subtracting the value to total and store the value * into the result string. */ public void subtract (int value) { total = total - value; result = result + " - " + value; } /** * return the stored string */ public String toString () { return result.toString(); } /** *Clear the memory */ public void clear() { total = 0; result = "0"; } public static void main(String[] args) { AddingMachine myCalculator = new AddingMachine(); myCalculator.add(4); myCalculator.subtract(2); myCalculator.add(5); //Print out the toString method System.out.println(myCalculator.toString()); //System.out.println(myCalculator.getTotal()); } }
77814953573b5ed946bc87a95d255ad748b3890e
[ "Java" ]
1
Java
wen7752/cse360assignment02
e3a2a0e34363897e555fbaa05be1e572b76272fa
1191bf15e026fe043969e68ce767bee2caeec9f5
refs/heads/master
<repo_name>reynoldjong/Kijiji-Rental-Data-Analyzer<file_sep>/frontend/src/components/Navbar/Navbar.js import React from "react"; import classes from "./Navbar.module.css"; /** * Component represents a navbar which appears at the top of the screen, * mostly used for style */ const navbar = () => { return ( <nav className={classes.Navbar + " navbar navbar-light shadow p-3 mb-5"}> <h2>Kijiji Rental Data Analyzer</h2> </nav> ); }; export default navbar; <file_sep>/src/main/java/team14/KijijiRentalDataAnalyzer/KijijiRentalDataAnalyzerApplication.java package team14.KijijiRentalDataAnalyzer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class KijijiRentalDataAnalyzerApplication { public static void main(String[] args) { SpringApplication.run(KijijiRentalDataAnalyzerApplication.class, args); } } <file_sep>/src/test/java/team14/KijijiRentalDataAnalyzer/Controller/ViewsControllerTest.java package team14.KijijiRentalDataAnalyzer.Controller; //import team14.KijijiRentalDataAnalyzer.KijijiRentalDataAnalyzerApplication; import team14.KijijiRentalDataAnalyzer.Model.RentalListing; import team14.KijijiRentalDataAnalyzer.Repository.RentalListingRepository; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.hasSize; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc public class ViewsControllerTest { @Autowired private MockMvc mvc; @Autowired private RentalListingRepository rentalListingRepository; @After public void resetDb() { rentalListingRepository.deleteAll(); } @Test public void whenGetChartView_thenReturnAllInformationNeededForChartView() throws Exception { RentalListing rentalListingOne = new RentalListing.RentalListingBuilder("title1", "www.test.com", "123 fake street", "$1000") .unitType("House") .bedrooms("3") .bathrooms("2") .parkingIncluded("1") .moveInDate("Apr 1, 2020") .petFriendly("Yes") .sizeSqft("1200") .furnished("Yes") .smokingPermitted("Outdoor Only") .hydroIncluded("Yes") .heatIncluded("Yes") .waterIncluded("Yes") .cableTvIncluded("Yes") .internetIncluded("Yes") .landlineIncluded("No") .yardIncluded("No") .balconyIncluded("No") .elevatorInBuildingIncluded("No") .build(); RentalListing rentalListingTwo = new RentalListing.RentalListingBuilder("title2", "www.fakehouse.com", "321 real road ave", "$9001") .unitType("Condo") .bedrooms("3") .bathrooms("2") .parkingIncluded("1") .moveInDate("May 1, 2020") .petFriendly("Yes") .sizeSqft("1200") .furnished("Yes") .smokingPermitted("Outdoor Only") .hydroIncluded("Yes") .heatIncluded("Yes") .waterIncluded("Yes") .cableTvIncluded("Yes") .internetIncluded("Yes") .landlineIncluded("No") .yardIncluded("No") .balconyIncluded("No") .elevatorInBuildingIncluded("No") .build(); rentalListingRepository.saveAndFlush(rentalListingOne); rentalListingRepository.saveAndFlush(rentalListingTwo); mvc.perform(get("/chartview") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.title1.url", is(rentalListingOne.getUrl()))) .andExpect(jsonPath("$.title1.address", is(rentalListingOne.getAddress()))) .andExpect(jsonPath("$.title1.price", is(rentalListingOne.getPrice()))) .andExpect(jsonPath("$.title1.unitType", is(rentalListingOne.getUnitType()))) .andExpect(jsonPath("$.title1.bedrooms", is(rentalListingOne.getBedrooms()))) .andExpect(jsonPath("$.title1.bathrooms", is(rentalListingOne.getBathrooms()))) .andExpect(jsonPath("$.title1.parkingIncluded", is(rentalListingOne.getParkingIncluded()))) .andExpect(jsonPath("$.title1.petFriendly", is(rentalListingOne.getPetFriendly()))) .andExpect(jsonPath("$.title1.sizeSqft", is(rentalListingOne.getSizeSqft()))) .andExpect(jsonPath("$.title1.furnished", is(rentalListingOne.getFurnished()))) .andExpect(jsonPath("$.title1.smokingPermitted", is(rentalListingOne.getSmokingPermitted()))) .andExpect(jsonPath("$.title1.hydroIncluded", is(rentalListingOne.getHydroIncluded()))) .andExpect(jsonPath("$.title1.heatIncluded", is(rentalListingOne.getHeatIncluded()))) .andExpect(jsonPath("$.title1.waterIncluded", is(rentalListingOne.getWaterIncluded()))) .andExpect(jsonPath("$.title1.cableTvIncluded", is(rentalListingOne.getCableTvIncluded()))) .andExpect(jsonPath("$.title1.internetIncluded", is(rentalListingOne.getInternetIncluded()))) .andExpect(jsonPath("$.title1.landlineIncluded", is(rentalListingOne.getLandlineIncluded()))) .andExpect(jsonPath("$.title1.yardIncluded", is(rentalListingOne.getYardIncluded()))) .andExpect(jsonPath("$.title1.balconyIncluded", is(rentalListingOne.getBalconyIncluded()))) .andExpect(jsonPath("$.title1.elevatorInBuildingIncluded", is(rentalListingOne.getElevatorInBuildingIncluded()))) .andExpect(jsonPath("$.title2.url", is(rentalListingTwo.getUrl()))) .andExpect(jsonPath("$.title2.address", is(rentalListingTwo.getAddress()))) .andExpect(jsonPath("$.title2.price", is(rentalListingTwo.getPrice()))) .andExpect(jsonPath("$.title2.unitType", is(rentalListingTwo.getUnitType()))) .andExpect(jsonPath("$.title2.bedrooms", is(rentalListingTwo.getBedrooms()))) .andExpect(jsonPath("$.title2.bathrooms", is(rentalListingTwo.getBathrooms()))) .andExpect(jsonPath("$.title2.parkingIncluded", is(rentalListingTwo.getParkingIncluded()))) .andExpect(jsonPath("$.title2.petFriendly", is(rentalListingTwo.getPetFriendly()))) .andExpect(jsonPath("$.title2.sizeSqft", is(rentalListingTwo.getSizeSqft()))) .andExpect(jsonPath("$.title2.furnished", is(rentalListingTwo.getFurnished()))) .andExpect(jsonPath("$.title2.smokingPermitted", is(rentalListingTwo.getSmokingPermitted()))) .andExpect(jsonPath("$.title2.hydroIncluded", is(rentalListingTwo.getHydroIncluded()))) .andExpect(jsonPath("$.title2.heatIncluded", is(rentalListingTwo.getHeatIncluded()))) .andExpect(jsonPath("$.title2.waterIncluded", is(rentalListingTwo.getWaterIncluded()))) .andExpect(jsonPath("$.title2.cableTvIncluded", is(rentalListingTwo.getCableTvIncluded()))) .andExpect(jsonPath("$.title2.internetIncluded", is(rentalListingTwo.getInternetIncluded()))) .andExpect(jsonPath("$.title2.landlineIncluded", is(rentalListingTwo.getLandlineIncluded()))) .andExpect(jsonPath("$.title2.yardIncluded", is(rentalListingTwo.getYardIncluded()))) .andExpect(jsonPath("$.title2.balconyIncluded", is(rentalListingTwo.getBalconyIncluded()))) .andExpect(jsonPath("$.title2.elevatorInBuildingIncluded", is(rentalListingTwo.getElevatorInBuildingIncluded()))); } @Test public void whenGetMapView_thenReturnAllInformationNeededForChartView() throws Exception { RentalListing rentalListingOne = new RentalListing.RentalListingBuilder("title1", "www.test.com", "40 St George St, Toronto, ON M5S 2E4", "$1000") .build(); RentalListing rentalListingTwo = new RentalListing.RentalListingBuilder("title2", "www.fakehouse.com", "1295 Military TrailScarborough, ON M1C 3A8", "$9001") .build(); rentalListingRepository.saveAndFlush(rentalListingOne); rentalListingRepository.saveAndFlush(rentalListingTwo); // From google String latitudeOfListingOne = "43.6596184"; String longitudeOfListingOne = "-79.39692079999999"; String latitudeOfListingTwo = "43.784841"; String longitudeOfListingTwo = "-79.18471559999999"; mvc.perform(get("/mapview") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$", hasSize(2))) .andExpect(jsonPath("$[0].address", is(rentalListingOne.getAddress()))) .andExpect(jsonPath("$[0].price", is(rentalListingOne.getPrice()))) .andExpect(jsonPath("$[0].lat", is(latitudeOfListingOne))) .andExpect(jsonPath("$[0].lng", is(longitudeOfListingOne))) .andExpect(jsonPath("$[1].address", is(rentalListingTwo.getAddress()))) .andExpect(jsonPath("$[1].price", is(rentalListingTwo.getPrice()))) .andExpect(jsonPath("$[1].lat", is(latitudeOfListingTwo))) .andExpect(jsonPath("$[1].lng", is(longitudeOfListingTwo))); } } <file_sep>/README.md # Kijiji-Rental-Data-Analyzer A Web Application displaying Kijiji's Long Term Rental Listing statistics. Chart View consists of scatter plots, pie charts and table using the details of rental listings. Map View displays the location of rental listings on Google Map. Data will be saved after each crawling. Server runs on localhost:8080. ## Overview ### frontend - Front-end application using React ### src - Back-end application using Java Spring Boot ### Design Pattern - Builder (Model) - Strategy (Crawler) - Singleton (Google GeoCoding) ### First Time Running - Get your Google API Key, enable GeoCoding and Google Map - ${your_api_key}: your Google API Key ```sh sed -i '' 's/api_key/${your_api_key}/g' frontend/src/config/secret.json mvn clean install ``` ### Crawl Data And Enable View - ${depth}: Depth of your own choice in numerical value ```sh mvn spring-boot:run -Dspring-boot.run.arguments="https://www.kijiji.ca/b-apartments-condos/canada/c37l0 ${depth}" ``` ### Development ```sh mvn spring-boot:run ``` <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>team14</groupId> <artifactId>KijijiRentalDataAnalyzer</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.6.RELEASE</version> <relativePath/> </parent> <name>team14.KijijiRentalDataAnalyzer Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>2.2.6.RELEASE</version> </dependency> <!-- in-memory database --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>2.2.6.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.6.2</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.mockito/mockito-core --> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.10.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>2.0.0-alpha1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>2.0.0-alpha1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.13.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.maps/google-maps-services --> <dependency> <groupId>com.google.maps</groupId> <artifactId>google-maps-services</artifactId> <version>0.9.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup --> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.13.1</version> </dependency> </dependencies> <build> <finalName>team14.KijijiRentalDataAnalyzer</finalName> <sourceDirectory>src/main/java</sourceDirectory> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.2.6.RELEASE</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M4</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>com.github.eirslett</groupId> <artifactId>frontend-maven-plugin</artifactId> <version>1.6</version> <configuration> <workingDirectory>frontend</workingDirectory> <installDirectory>target</installDirectory> </configuration> <executions> <execution> <id>install node and npm</id> <goals> <goal>install-node-and-npm</goal> </goals> <configuration> <nodeVersion>v12.16.2</nodeVersion> <npmVersion>6.14.4</npmVersion> </configuration> </execution> <execution> <id>npm install</id> <goals> <goal>npm</goal> </goals> <configuration> <arguments>install</arguments> </configuration> </execution> <execution> <id>npm run build</id> <goals> <goal>npm</goal> </goals> <configuration> <arguments>run build</arguments> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> <phase>generate-resources</phase> <configuration> <target> <copy todir="${project.build.directory}/classes/public"> <fileset dir="${project.basedir}/frontend/build"/> </copy> </target> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> <configuration> <filesets> <fileset> <directory>./frontend/build</directory> <includes> <include>**</include> </includes> <followSymlinks>false</followSymlinks> </fileset> <fileset> <directory>./target</directory> <includes> <include>**</include> </includes> <followSymlinks>false</followSymlinks> </fileset> </filesets> </configuration> </plugin> </plugins> </build> </project> <file_sep>/src/main/java/team14/KijijiRentalDataAnalyzer/GoogleGeoCodingEngine/GeoCoding.java package team14.KijijiRentalDataAnalyzer.GoogleGeoCodingEngine; import com.google.maps.GeoApiContext; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.FileReader; import java.io.IOException; /** * A singleton class that handles the Google GeoCoding API */ public class GeoCoding { private static GeoCoding geoCoding = null; // The context used in getting coordinates private GeoApiContext context; private String apiKey; private GeoCoding() { getApiKey(); context = new GeoApiContext.Builder() .apiKey(apiKey) .build(); } /** * Get he GeoApiContext field */ public GeoApiContext getContext() { return context; } /** * Get the instance of this class */ public static GeoCoding buildMapControl() { if (GeoCoding.geoCoding == null) { GeoCoding.geoCoding = new GeoCoding(); return GeoCoding.geoCoding; } else { return GeoCoding.geoCoding; } } private void getApiKey() { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader("frontend/src/config/secret.json")); JSONObject jsonObject = (JSONObject) obj; apiKey = (String) jsonObject.get("GeoAPI"); } catch (ParseException | IOException e) { e.printStackTrace(); } } } <file_sep>/frontend/src/components/MainScatterPlot/MainScatterPlot.js import React from 'react'; import Chart from "react-google-charts"; /** * Since price distribution is very important this componenet is only used to render that data. * @param {*} props */ const MainScatterPlot= (props) =>{ return( <React.Fragment> <Chart width='100%' height='100%' chartType="Scatter" loader={<div>Loading Chart</div>} data={props.plotPoints} options={{ title: props.title, chartArea: { width: "100%" }, hAxis: { title: props.hTitle, minValue: 0 }, vAxis: { title: props.vTitle, } }} legendToggle /> </React.Fragment> ); } export default MainScatterPlot<file_sep>/src/main/java/team14/KijijiRentalDataAnalyzer/Model/RentalListing.java package team14.KijijiRentalDataAnalyzer.Model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import org.apache.commons.lang3.builder.ToStringBuilder; import javax.persistence.*; @Data @Entity // This tells Hibernate to make a table out of this class public class RentalListing { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) @JsonIgnore private Long id; @JsonIgnore private String title; private String url; private String address; private String price; private String unitType; private String bedrooms; private String bathrooms; private String parkingIncluded; private String moveInDate; private String petFriendly; private String sizeSqft; private String furnished; private String smokingPermitted; private String hydroIncluded; private String heatIncluded; private String waterIncluded; private String cableTvIncluded; private String internetIncluded; private String landlineIncluded; private String yardIncluded; private String balconyIncluded; private String elevatorInBuildingIncluded; private RentalListing(RentalListingBuilder builder) { this.title = builder.title; this.url = builder.url; this.address = builder.address; this.price = builder.price; this.unitType = builder.unitType; this.bedrooms = builder.bedrooms; this.bathrooms = builder.bathrooms; this.parkingIncluded = builder.parkingIncluded; this.moveInDate = builder.moveInDate; this.petFriendly = builder.petFriendly; this.sizeSqft = builder.sizeSqft; this.furnished = builder.furnished; this.smokingPermitted = builder.smokingPermitted; this.hydroIncluded = builder.hydroIncluded; this.heatIncluded = builder.heatIncluded; this.waterIncluded = builder.waterIncluded; this.cableTvIncluded = builder.cableTvIncluded; this.internetIncluded = builder.internetIncluded; this.landlineIncluded = builder.landlineIncluded; this.yardIncluded = builder.yardIncluded; this.balconyIncluded = builder.balconyIncluded; this.elevatorInBuildingIncluded = builder.elevatorInBuildingIncluded; } public RentalListing() {} @Override public String toString() { return ToStringBuilder.reflectionToString(this); } public static class RentalListingBuilder { private String title; private String url; private String address; private String price; private String unitType; private String bedrooms; private String bathrooms; private String parkingIncluded; private String moveInDate; private String petFriendly; private String sizeSqft; private String furnished; private String smokingPermitted; private String hydroIncluded = "No"; private String heatIncluded = "No"; private String waterIncluded = "No"; private String cableTvIncluded = "No"; private String internetIncluded = "No"; private String landlineIncluded = "No"; private String yardIncluded = "No"; private String balconyIncluded = "No"; private String elevatorInBuildingIncluded = "No Information"; public RentalListingBuilder(String title, String url, String address, String price) { this.title = title; this.url = url; this.address = address; this.price = price; } public RentalListingBuilder unitType(String unitType) { this.unitType = unitType; return this; } public RentalListingBuilder bedrooms(String bedrooms) { this.bedrooms = bedrooms; return this; } public RentalListingBuilder bathrooms(String bathrooms) { this.bathrooms = bathrooms; return this; } public RentalListingBuilder parkingIncluded(String parkingIncluded) { this.parkingIncluded = parkingIncluded; return this; } public RentalListingBuilder moveInDate(String moveInDate) { this.moveInDate = moveInDate; return this; } public RentalListingBuilder petFriendly(String petFriendly) { this.petFriendly = petFriendly; return this; } public RentalListingBuilder sizeSqft(String sizeSqft) { this.sizeSqft = sizeSqft; return this; } public RentalListingBuilder furnished(String furnished) { this.furnished = furnished; return this; } public RentalListingBuilder smokingPermitted(String smokingPermitted) { this.smokingPermitted = smokingPermitted; return this; } public RentalListingBuilder hydroIncluded(String hydroIncluded) { this.hydroIncluded = hydroIncluded; return this; } public RentalListingBuilder heatIncluded(String heatIncluded) { this.heatIncluded = heatIncluded; return this; } public RentalListingBuilder waterIncluded(String waterIncluded) { this.waterIncluded = waterIncluded; return this; } public RentalListingBuilder cableTvIncluded(String cableTvIncluded) { this.cableTvIncluded = cableTvIncluded; return this; } public RentalListingBuilder internetIncluded(String internetIncluded) { this.internetIncluded = internetIncluded; return this; } public RentalListingBuilder landlineIncluded(String landlineIncluded) { this.landlineIncluded = landlineIncluded; return this; } public RentalListingBuilder yardIncluded(String yardIncluded) { this.yardIncluded = yardIncluded; return this; } public RentalListingBuilder balconyIncluded(String balconyIncluded) { this.balconyIncluded = balconyIncluded; return this; } public RentalListingBuilder elevatorInBuildingIncluded(String elevatorInBuildingIncluded) { this.elevatorInBuildingIncluded = elevatorInBuildingIncluded; return this; } public RentalListing build() { return new RentalListing(this); } } } <file_sep>/src/main/java/team14/KijijiRentalDataAnalyzer/CrawlerEngine/Crawler.java package team14.KijijiRentalDataAnalyzer.CrawlerEngine; import java.io.IOException; import java.util.ArrayList; import java.util.List; import team14.KijijiRentalDataAnalyzer.Model.RentalListing; import team14.KijijiRentalDataAnalyzer.Repository.RentalListingRepository; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class Crawler { @Autowired private RentalListingRepository rentalListingRepository; private CrawlerStrategy basicStrategy = new CrawlerBasicStrategy(); private CrawlerStrategy detailedOverviewStrategy = new CrawlerOverviewStrategy(); private List<String> listings = new ArrayList<>(); public void crawlFromSeed(String seed, int limit) throws IOException { if (!seed.contains("https://www.kijiji.ca")) { // not crawling anything other than kijiji System.out.println("Crawler only support Kijiji pages"); return; } String url = seed; // we may end up with list size >= limit after loop, but we can trim extras while (listings.size() < limit) { Document doc = Jsoup.connect(url + "?siteLocale=en_CA").get(); // build a list of url for each listing populateListings(doc); Elements nextElements = doc.select("div[class*=bottom-bar]").select("a[title=Next]"); if (nextElements.size() != 0) { Element next = nextElements.get(0); url = next.attr("abs:href"); // special case if there is no more "next" if (url.equals("")) break; } } int i = 0; // clear all entries in database rentalListingRepository.deleteAll(); while (i < limit && i < listings.size()) { crawlEachListing(listings.get(i++)); } } // helper that builds a list of URL for each listing private void populateListings(Document doc) throws IOException { Elements links = doc.select("div[data-vip-url]"); for (Element link : links) { String listingUrl = link.attr("abs:data-vip-url"); // avoid repeats if (!listings.contains(listingUrl)) { listings.add(listingUrl); } } } public void crawlEachListing(String url) throws IOException { Document doc = Jsoup.connect(url + "?siteLocale=en_CA").get(); String title = getTitle(doc); String addr = getAddress(doc); String price = getPrice(doc); RentalListing.RentalListingBuilder builder = new RentalListing.RentalListingBuilder(title, url, addr, price); // test to see if it is going to be a detailed list if (doc.select("li[class*=twoLinesAttribute]").size() == 0) rentalListingRepository.save(basicStrategy.execute(title, doc, builder)); else { rentalListingRepository.save(detailedOverviewStrategy.execute(title, doc, builder)); } } // get the title of the posting private String getTitle(Document doc) { String title = ""; Elements titleHeader = doc.select("h1[class*=title]"); for (Element s : titleHeader) { title = s.text(); } return title; } // get the address of the posting private String getAddress(Document doc) { String address = ""; Elements addrSpan = doc.select("span[itemprop=\"address\"]"); for (Element s : addrSpan) { address = s.text(); } return address; } // get the price of the posting (as a string) private String getPrice(Document doc) { String price = ""; Elements priceContainer = doc.select("span[content]"); for (Element e : priceContainer) { price = e.text(); } return price; } /* public static void main(String[] args) throws IOException { Crawler myCrawler = new Crawler(); myCrawler.crawlFromSeed("https://www.kijiji.ca/b-apartments-condos/canada/c37l0", 5); myCrawler.crawlEachListing("https://www.kijiji.ca/v-apartments-condos/st-johns/spacious-one-bedroom-apartment-available-for-may-1st/1497327681?undefined"); myCrawler.crawlEachListing("https://www.kijiji.ca/v-apartments-condos/mississauga-peel-region/2-bedroom-2-full-washroom-luxury-condo-near-sq-one-2500-month/1497524613"); System.out.println("1234567890".subSequence(0, 2)); } */ } <file_sep>/frontend/src/App.js import React, { Component } from "react"; import { Map, GoogleApiWrapper, Marker } from "google-maps-react"; import PieChart from "./components/PieChart/PieChart"; import MainScatterPlot from "./components/MainScatterPlot/MainScatterPlot"; import Navbar from "./components/Navbar/Navbar"; import axios from "axios"; import Table from "./components/Table/Table"; import ScatterPlot from "./components/ScatterPlot/ScatterPlot"; import RentalInfoWindow from "./components/Window/Window"; import * as data from "./config/secret.json"; const mapStyles = { width: "100%", height: "50%" }; export class MapContainer extends Component { /** * State holds variables on every crawlled element. * These varaibles get passed onto the charts. The benefit to this approach * is that only one get request needs to be made for the chartview and one * more for the graphs view. Data needs to be in list format for easier * maping of components * */ constructor(props) { super(props); this.state = { details: [], data: {}, Prices: [], Addresses: [], Bedrooms: [], Bathrooms: [], TV: [], Elevator: [], Furnished: [], SmokingPermitted: [], HydroIncluded: [], HeatIncluded: [], WaterIncluded: [], UnitType: [], Internet: [], Landline: [], Yard: [], Size: [], rows: [] }; } /** * When the component is created we should create retrieve the data * for the map section and charts section */ componentDidMount() { axios .get("/mapview") .then(response => { // If the get request is successful state (files) is updated this.updateDetails(response); }) .catch(function(error) { console.log(error); }); this.getData(); } updateDetails = response => { const data = response["data"]; this.setState({ ...this.state, details: data }); }; /** * Display the markers on the map correspond to the locations of the listing */ displayMarkers = () => { return this.state.details.map((details, index) => { return ( <Marker key={index} id={index} details={details} onClick={this.onMarkerClick} position={{ lat: details.lat, lng: details.lng }}/> ); }); }; /** * Pop up an info window when the marker is clicked */ onMarkerClick = (props, marker) => { this.setState({ activeMarker: marker, selectedAddress: props.details.address, selectedPrice: props.details.price, selectedUrl: props.details.url, selectedId: props, showingInfoWindow: true }); }; /** * Close the info window box when the cross button is clicked */ onInfoWindowClose = () => this.setState({ activeMarker: null, showingInfoWindow: false }); /** * Close the info window box when the map is clicked while info window box is on */ onMapClicked = () => { if (this.state.showingInfoWindow) this.setState({ activeMarker: null, showingInfoWindow: false }); }; handleClick = () => { this.setState({ open: true }); }; handleClose = (event, reason) => { if (reason === 'clickaway') { return; } this.setState({ open: false }); }; /** * Makes a get request to /chartview which adds crawler data to state */ getData = async () => { await axios .get("/chartview") .then(response => { // this.setData(data); this.getRows(response); this.setFields(response); }) .catch(error => { console.log(error); }); }; /** * Helper function for setting state */ setData = data => { this.setState({ ...this.state, data: data }); }; /** * Maps all the raw data to a rows state variable */ getRows = response => { let rows = []; const data = response["data"]; for (var key in data) { let row = null; row = data[key]; rows.push(row); } this.setState({ ...this.state, rows: rows }); }; /** * Maps all the fields in the crawler data to their appropriate state * counterpart. */ setFields = response => { const data = response["data"]; // Set up lists to hold data let Prices = []; let Bedrooms = []; let Bathrooms = []; let Addresses = []; let TV = []; let Elevator = []; let Furnished = []; let SmokingPermitted = []; let HydroIncluded = []; let HeatIncluded = []; let WaterIncluded = []; let UnitType = []; let Internet = []; let Landline = []; let Yard = []; let Size = []; // Loop through response maping variables for (var listing in data) { Prices.push(data[listing]["price"]); Bedrooms.push(data[listing]["bedrooms"]); Bathrooms.push(data[listing]["bathrooms"]); Addresses.push(data[listing]["address"]); TV.push(data[listing]["cableTvIncluded"]); Elevator.push(data[listing]["elevatorInBuildingIncluded"]); Furnished.push(data[listing]["furnished"]); SmokingPermitted.push(data[listing]["smokingPermitted"]); HydroIncluded.push(data[listing]["hydroIncluded"]); HeatIncluded.push(data[listing]["heatIncluded"]); WaterIncluded.push(data[listing]["waterIncluded"]); UnitType.push(data[listing]["unitType"]); Internet.push(data[listing]["internetIncluded"]); Landline.push(data[listing]["landlineIncluded"]); Yard.push(data[listing]["yardIncluded"]); Size.push(data[listing]["sizeSqft"]); } // update state this.setState({ ...this.state, Prices: Prices, Bedrooms: Bedrooms, Bathrooms: Bathrooms, Addresses: Addresses, TV: TV, Elevator: Elevator, Furnished: Furnished, SmokingPermitted: SmokingPermitted, HydroIncluded: HydroIncluded, HeatIncluded: HeatIncluded, WaterIncluded: WaterIncluded, UnitType: UnitType, Internet: Internet, Landline: Landline, Yard: Yard, Size: Size }); }; /** * Creates a plotPoints array for the prices category. Prices * however have "," and "$" for each home and need to be removed and * then converted to float. If the price is null it will be made * into a 0. */ getPricesPlotPoints = () => { const prices = this.state.Prices; let plotPoints = []; plotPoints.push(["Home", "Price"]); prices.forEach(function(price, homeNumber) { let alteredPrice = price; alteredPrice = alteredPrice.replace(",", ""); alteredPrice = alteredPrice.replace("$", ""); if (alteredPrice === "") { alteredPrice = 0; } alteredPrice = parseFloat(alteredPrice); plotPoints.push([homeNumber, alteredPrice]); }); return plotPoints; }; /** * Given a valid type name (the ones used in state), this function will * return the appropriate array of each point to be used in a scatter plot. * All the values need to be converted to float. * @param type: a variable name describe in state */ buildScatterPlotData = type => { let plotPoints = []; plotPoints.push(["Home", type]); this.state[type].forEach(function(item, index) { plotPoints.push([index, parseFloat(item)]); }); return plotPoints; }; /** * Given a valid type name (the ones used in state), this function * return the appropriate array of each point to be used in a pie chart. * @param type: a variable name describe in state */ buildPieChartData = type => { let plotPoints = []; let dict = {}; // Dummy header plotPoints.push(["X", type]); // Loop through each key and add 1 more if the key exists in dict // Otherwise make an entry for it this.state[type].forEach(function(item, index) { if (dict.hasOwnProperty(item)) { dict[item] += 1; } else { dict[item] = 1; } }); for (var key in dict) { plotPoints.push([key, dict[key]]); } return plotPoints; }; render() { return ( <React.Fragment> <div style={{ position: "relative", left: "auto", right: "auto" }}> <Navbar /> <div className="container-fluid" style={{ marginTop: "40px" }}> <center> <div className="row"> <div className="col"> <div className="card shadow p-3 mb-5 bg-white rounded"> <h3 style={{ textAlign: "left" }}>Price Distribution</h3> <div className="card-body "> <MainScatterPlot title="Price Distribution Across Homes" vTitle="Price in $CAD" hTitle="Home" plotPoints={this.getPricesPlotPoints()} /> </div> </div> </div> </div> </center> <center> <div className="row"> <PieChart vTitle="vTitle" hTitle="hTitle" buildDataHandler={this.buildPieChartData} initialPoints={this.buildPieChartData("Furnished")} /> <PieChart vTitle="vTitle" hTitle="hTitle" buildDataHandler={this.buildPieChartData} initialPoints={this.buildPieChartData("Furnished")} /> </div> <div className="row"> <ScatterPlot title="Chart" vTitle="vTitle" hTitle="hTitle" buildDataHandler={this.buildScatterPlotData} initialPoints={this.buildScatterPlotData("Bedrooms")} /> <ScatterPlot title="Chart" vTitle="vTitle" hTitle="hTitle" buildDataHandler={this.buildScatterPlotData} initialPoints={this.buildScatterPlotData("Bedrooms")} /> </div> </center> <center> <div className="row"> <div className="col"> <div className="card shadow p-3 mb-5 bg-white rounded"> <h3 style={{ textAlign: "left" }}>View all Data</h3> <div className="card-body "> <Table rows={this.state.rows} /> </div> </div> </div> </div> </center> </div> <Map google={this.props.google} onClick={this.onMapClicked} zoom={8} style={mapStyles} initialCenter={{ lat: 43.7645, lng: -79.411 }} > {this.displayMarkers()} <RentalInfoWindow marker={this.state.activeMarker} visible={this.state.showingInfoWindow} > <div> <h1>{this.state.selectedAddress}</h1> <p>{this.state.selectedPrice}</p> <span>{this.state.selectedUrl}</span> </div> </RentalInfoWindow> </Map> </div> </React.Fragment> ); } } export default GoogleApiWrapper({ apiKey: data.GeoAPI })(MapContainer); <file_sep>/src/main/java/team14/KijijiRentalDataAnalyzer/CrawlerEngine/CrawlerBasicStrategy.java package team14.KijijiRentalDataAnalyzer.CrawlerEngine; import team14.KijijiRentalDataAnalyzer.Model.RentalListing; import org.apache.commons.text.CaseUtils; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class CrawlerBasicStrategy implements CrawlerStrategy { public RentalListing execute(String title, Document doc, RentalListing.RentalListingBuilder builder) { Elements attr = doc.select("div[class*=attributeListWrapper]").select("dl[class*=itemAttribute]"); for (Element entry : attr) { String label = entry.select("dt[class*=attributeLabel]").text(); String value = entry.select("dd[class*=attributeValue]").text(); label = CaseUtils.toCamelCase(label, false, new char[] {' ', '-', '(', ')'}); try { Method m = RentalListing.RentalListingBuilder.class.getMethod(label, String.class); m.invoke(builder, value); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } //System.out.println(entry.select("dt[class*=attributeLabel]").text()); //System.out.println(entry.select("dd[class*=attributeValue]").text()); //System.out.println("======"); } return builder.build(); } } <file_sep>/frontend/src/components/PieChart/PieChart.js import React, { useState, useEffect } from "react"; import Chart from "react-google-charts"; /** * Component used to render a pie chart, data must be formated * as follows [["header1", "header2"], [data1, data2]....] * @props */ const PieChart = props => { /** * State for PieChart, only contains a title used for the pie chart and * the plot points for the pie chart */ const [data, setData] = useState({ data: props.initialPoints, title:"furnished", }); /** * Once the component is being rendered we need to populate the graph * with something, initial points is used to pre-populate the data */ useEffect(()=>{ setData({title:"Furnished", data:props.initialPoints}); },[props.initialPoints]); /** * Once a user selects a different type of data from the data * this function will change the data and title that is used in useState * @event */ const updateData = event => { event.preventDefault(); const plotPoints = props.buildDataHandler(event.target.value); setData({ title:event.target.value, data:plotPoints}); }; return ( <div className="col"> <div className="card shadow p-3 mb-5 bg-white rounded"> <h3 style={{ textAlign: "left" }}>{data.title}</h3> <div className="card-body"> <select onChange={updateData}> <option value="SmokingIncluded">Smoking Included</option> <option value="Bedrooms">Bedrooms</option> <option value="Bathrooms">Bathrooms</option> <option value="TV">TV</option> <option value="Elevator">Elevator</option> <option value="Furnished">Furnished</option> <option value="SmokingPermitted">Smoking Permitted</option> <option value="HydroIncluded">Hydro Included</option> <option value="HeatIncluded">Heat Included</option> <option value="WaterIncluded">Water Included</option> <option value="Internet">Internet</option> <option value="Landline">Landline Included</option> </select> <Chart width="100%" height="100%" chartType="PieChart" loader={<div>Loading Chart</div>} data={data.data} options={{ title: data.title }} /> </div> </div> </div> ); }; export default PieChart; <file_sep>/src/main/java/team14/KijijiRentalDataAnalyzer/Repository/RentalListingRepository.java package team14.KijijiRentalDataAnalyzer.Repository; import team14.KijijiRentalDataAnalyzer.Model.RentalListing; import org.springframework.data.jpa.repository.JpaRepository; public interface RentalListingRepository extends JpaRepository<RentalListing, Long> { }
2837d2802f9458ff6c4c144589cd8ab5c0f7b549
[ "JavaScript", "Java", "Maven POM", "Markdown" ]
13
JavaScript
reynoldjong/Kijiji-Rental-Data-Analyzer
40c1c02ff0b16ab55a97d68be199dea581ca9a37
2b09d3b6d7f00ab65bbd8d0239a6402654bbedbd
refs/heads/master
<repo_name>canjs/can-view-modifiers<file_sep>/src/test/helper.js steal('can/util', function() { var viewCheck = /(\.stache|extensionless)$/; can.test = { fixture: function (path) { if (typeof steal !== 'undefined') { if(steal.idToUri) { return steal.config('root').toString() + '/' + path; } else { return steal.joinURIs(System.baseURL, path); } } if (window.require && require.toUrl && !viewCheck.test(path)) { return require.toUrl(path); } return path; }, path: function (path, absolute) { //absolute prevents require.toURL from returning a relative path if (typeof steal !== 'undefined') { if(steal.idToUri) { return ""+steal.idToUri(steal.id("can/"+path).toString()); } else { return steal.joinURIs(System.baseURL, path); } } if (!absolute && window.require && require.toUrl && !viewCheck.test(path)) { return require.toUrl(path); } var pathIndex = window.location.href.indexOf('/test/'); if(pathIndex) { return window.location.href.substring(0, pathIndex + 1) + path; } return path; } }; }); <file_sep>/readme.md # can-view-modifiers (DEPRECATED) *The can-view-modifiers plugin is deprecated* [![Build Status](https://travis-ci.org/canjs/can-view-modifiers.png?branch=master)](https://travis-ci.org/canjs/can-view-modifiers) Use jQuery modifiers to render views ## Overview The can/view/modifiers plugin extends the jQuery view modifiers * jQuery.fn.after * jQuery.fn.append * jQuery.fn.before * jQuery.fn.html * jQuery.fn.prepend * jQuery.fn.replaceWith * jQuery.fn.text to render a [can.view](http://canjs.com/docs/can.view.html). When rendering a view you call the view modifier the same way as can.view with the view name or id as the first, the data as the second and the optional success callback (to load the view asynchronously) as the third parameter. For example, you can render a template from *todo/todos.ejs* looking like this: <% for(var i = 0; i < this.length; i++ ){ %> <li><%= this[i].name %></li> <% } %> By calling the [can.prototype.jQuery.fn.html html] modifier on the `#todos` element like this: can.$('#todos').html('todo/todos.ejs', [ { name : '<NAME>' }, { name : '<NAME>' } ]); __Note:__ You always have to provide the data (second) argument to render a view, otherwise the standard jQuery modifier will be used. If you have no data to render pass an empty object: $('#todos').html('todo/todos.ejs', {}); // Render todo/todos.ejs wit no data ### Deferreds Additionally it is also possible to pass a [can.Deferred] as a single parameter to any view modifier. Once the deferred resolves the result will be rendered using that modifier. This can be used to easily request and render static content. The following example inserts the content of _content/info.html_ after the `#todos` element: can.$('#todos').after(can.ajax({ url : 'content/info.html' })); ### API For API details, see `src/can-view-modifiers.js` ## Usage ### ES6 use With StealJS, you can import this module directly in a template that is autorendered: ```js import plugin from 'can-view-modifiers'; ``` ### CommonJS use Use `require` to load `can-view-modifiers` and everything else needed to create a template that uses `can-view-modifiers`: ```js var plugin = require("can-view-modifiers"); ``` ## AMD use Configure the `can` and `jquery` paths and the `can-view-modifiers` package: ```html <script src="require.js"></script> <script> require.config({ paths: { "jquery": "node_modules/jquery/dist/jquery", "can": "node_modules/canjs/dist/amd/can" }, packages: [{ name: 'can-view-modifiers', location: 'node_modules/can-view-modifiers/dist/amd', main: 'lib/can-view-modifiers' }] }); require(["main-amd"], function(){}); </script> ``` ### Standalone use Load the `global` version of the plugin: ```html <script src='./node_modules/can-view-modifiers/dist/global/can-view-modifiers.js'></script> ``` ## Contributing ### Making a Build To make a build of the distributables into `dist/` in the cloned repository run ``` npm install node build ``` ### Running the tests Tests can run in the browser by opening a webserver and visiting the `test.html` page. Automated tests that run the tests from the command line in Firefox can be run with ``` npm test ```
4a5d4ea28a9067a3bb252a4b62341cb3307dfa89
[ "JavaScript", "Markdown" ]
2
JavaScript
canjs/can-view-modifiers
50f2e80042b9a5c1cd3c33b018ee281830bf2a35
8e996ed8ab8c3a676253955a8347fc794e3654ae
refs/heads/master
<file_sep>#!/bin/bash docker rm -f mobile-light docker run --name="mobile-light" -v /home/couchbase/jenkinsdocker-ssh:/ssh \ --volume=/home/couchbase/latestbuilds:/latestbuilds \ --restart=unless-stopped \ -p 2300:22 -d ceejatec/ubuntu1404-mobile-android-docker:20160712 docker rm -f mobile-android docker run --name="mobile-android" -v /home/couchbase/jenkinsdocker-ssh:/ssh \ --restart=unless-stopped \ -p 2422:22 -d ceejatec/ubuntu1404-mobile-android-docker:20180502 docker rm -f mobile-java docker run --name="mobile-java" -v /home/couchbase/jenkinsdocker-ssh:/ssh \ --restart=unless-stopped \ -p 2424:22 -d ceejatec/ubuntu1404-mobile-android-docker:20160712 <file_sep>#!/bin/bash # Fetches a project by project name, path and Git ref # This script is normally used in conjunction with allcommits.py: # ./allcommits.py <change-id>|xargs -n 3 ./fetchproject.sh set -x set -e PROJECT=$1 PROJECT_PATH=$2 REFSPEC=$3 if [ -z "$GERRIT_HOST" ]; then echo "Error: Required environment variable 'GERRIT_HOST' not set." exit 1 fi if [ -z "$GERRIT_PORT" ]; then echo "Error: Required environment variable 'GERRIT_PORT' not set." exit 2 fi if [ -z "$GERRIT_SCHEME" ]; then echo "Error: Required environment variable 'GERRIT_SCHEME' not set." exit 3 fi if [ -z "$PROJECT" ]; then echo "Error: Required environment variable 'PROJECT' not set." exit 4 fi if [ -z "$PROJECT_PATH" ]; then echo "Error: Required environment variable 'PROJECT_PATH' not set." exit 5 fi if [ -z "$REFSPEC" ]; then echo "Error: Required environment variable 'REFSPEC' not set." exit 6 fi pushd $PROJECT_PATH > /dev/null git reset --hard HEAD git fetch $GERRIT_SCHEME://$GERRIT_HOST:$GERRIT_PORT/$PROJECT $REFSPEC git clean -d --force -x git checkout FETCH_HEAD popd > /dev/null <file_sep>#!/bin/sh # Bump this when rebuilding with changes #TAG=20160712 TAG=`date +%Y%m%d` mkdir -p build cp -a ../../util/couchbuilder_start.sh build docker build -t ceejatec/ubuntu1404-mobile-android-docker:$TAG . <file_sep>#!/bin/sh cd `dirname $0` # Spock SUSE container (currently hosted on 172.23.96.152) ./restart_jenkinsdocker.py localonly/suse-12-couchbase-build:20170418 spock-suse12 3125 server.jenkins.couchbase.com & ./restart_jenkinsdocker.py localonly/suse-12-couchbase-build:20180815 vulcan-suse12 3126 server.jenkins.couchbase.com & wait echo "All done!" <file_sep>#!/bin/sh cd `dirname $0` # Vulcan+ SUSE container (currently hosted on 172.23.96.156) ./restart_jenkinsdocker.py localonly/suse-12-couchbase-build:20170418 spock-suse12-02 3127 server.jenkins.couchbase.com & ./restart_jenkinsdocker.py localonly/suse-12-couchbase-build:20180815 vulcan-suse12-02 3128 server.jenkins.couchbase.com & wait echo "All done!" <file_sep>#!/bin/bash # # Common script run by various Jenkins builds to run CBNT testing on kv_engine if [ -z "$GERRIT_HOST" ]; then echo "Error: Required environment variable 'GERRIT_HOST' not set." exit 1 fi if [ -z "$GERRIT_PORT" ]; then echo "Error: Required environment variable 'GERRIT_PORT' not set." exit 2 fi if [ -z "$GERRIT_PROJECT" ]; then echo "Error: Required environment variable 'GERRIT_PROJECT' not set." exit 3 fi if [ -z "$GERRIT_PATCHSET_REVISION" ]; then echo "Error: Required environment variable 'GERRIT_PATCHSET_REVISION' not set." exit 4 fi if [ -z "$GERRIT_REFSPEC" ]; then echo "Error: Required environment variable 'GERRIT_REFSPEC' not set." exit 5 fi if [ -z "$GERRIT_CHANGE_ID" ]; then echo "Error: Required environment variable 'GERRIT_CHANGE_ID' not set." exit 6 fi if [ -z "$WORKSPACE" ]; then echo "Error: Required environment variable 'WORKSPACE' not set." exit 7 fi if [ -z "$LNT_IP" ]; then echo "Error: Required environment variable 'LNT_IP' not set." exit 8 fi if [ -z "$CBNT_TYPE" ]; then echo "Error: Required environment variable 'CBNT_TYPE' not set." exit 9 fi if [ -z "$CBNT_SUITE" ]; then echo "Error: Required environment variable 'CBNT_SUITE' not set." exit 10 fi if [ -z "$ITERATIONS" ]; then echo "Error: Required environment variable 'ITERATIONS' not set." exit 11 fi if [ "${GERRIT_PROJECT}" != "kv_engine" ]; then echo "Error: Project ${GERRIT_PROJECT} is not kv_engine." exit 12 fi BASEDIR=$(cd $(dirname $BASH_SOURCE) && pwd) function echo_cmd { echo \# "$@" "$@" } # We define two error handler functions - a fatal one used for the # manditory parts of the build (i.e. actually building Couchbase), and # a deferred one which 'remembers' error(s) have occured but lets the # rest of the script run. # This is to maximise the number of tests we run (even if earlier # tests fail), so developers see as many problems in a single run as # possible, but ensures that the script still exits with the correct # error code. last_error=0 error_count=0 function fatal_error_handler() { last_error=$? echo "Fatal error - aborting" exit $last_error } function deferred_error_handler() { last_error=$? (( error_count++ )) } # Initially install the fatal handler. trap fatal_error_handler ERR cat <<EOF ============================================ === environment === ============================================ EOF ulimit -a echo "" env | grep -iv password | grep -iv passwd | sort cat <<EOF ============================================ === clean === ============================================ EOF echo_cmd make clean-xfd-hard echo_cmd rm -fr install echo_cmd rm -f build/CMakeCache.txt # Zero ccache stats, so we can measure how much space this build is # consuming. echo_cmd ccache -z # Wipe out any core files left from a previous run. echo_cmd rm -f /tmp/core.* cat <<EOF ============================================ === update all projects with === === the same Change-Id === ============================================ EOF ${BASEDIR}/checkout_dependencies.py $GERRIT_PATCHSET_REVISION $GERRIT_CHANGE_ID $GERRIT_PROJECT $GERRIT_REFSPEC cat <<EOF ============================================ === Build === ============================================ EOF echo_cmd make -j${PARALLELISM} EXTRA_CMAKE_OPTIONS="${CMAKE_ARGS}" echo_cmd ccache -s # Manditory steps complete, install the deferred error handler. trap deferred_error_handler ERR cat <<EOF ============================================ === CBNT Tests === ============================================ EOF # We run the lnt command under numactl --interleave=all # this is due to the fact that before this, the tests were rather # unstable in their execution times and had a large std. deviaiton # even when running in the most determenistic way possible. After testing # we found this to be the most stable way of running the tests to get repeatable # results. numactl --interleave=all lnt runtest $CBNT_SUITE ${WORKSPACE}/kv_engine/tests/cbnt_tests/cbnt_test_list.yml\ ${CBNT_TYPE} --submit_url=http://${LNT_IP}/submitRun -v --commit=1 --iterations=${ITERATIONS} # Check for core files - if present then archive them and the # executable they are from (for post-mortem) and fail the build. shopt -s nullglob ${BASEDIR}/archive_core_files.sh archived_core_dumps /tmp/core.* rm -f /tmp/core.* exit $last_error <file_sep>#!/bin/bash # These are currently all hosted on mega echo @@@@@@@@@@@@@@@@@@@@@@ echo @ Recreating slaves echo @@@@@@@@@@@@@@@@@@@@@@ ../buildslaves/centos-65/sgw_jenkins/restart.sh ../buildslaves/centos-70/sgw_jenkins/restart.sh ../buildslaves/ubuntu-14.04/sgw_jenkins/restart.sh ../buildslaves/ubuntu-14.04/android/restart.sh ./restart_jenkinsdocker.py ceejatec/ubuntu-1604-couchbase-build:latest zz-mobile-lightweight 2423 mobile.jenkins.couchbase.com ./restart_jenkinsdocker.py ceejatec/centos-72-litecore-build:20170710 mobile-litecore-linux 6501 mobile.jenkins.couchbase.com ./restart_jenkinsdocker.py --no-workspace ceejatec/ubuntu1604-mobile-lite-android:20180604 mobile-lite-android 6502 mobile.jenkins.couchbase.com ./restart_jenkinsdocker.py --no-workspace ceejatec/ubuntu1604-mobile-lite-android:20180604 mobile-lite-android-02 6503 mobile.jenkins.couchbase.com <file_sep>#!/bin/sh TAG=$(date +%Y%m%d) mkdir -p build cp -a ../../util/couchbuilder_start.sh build docker build -t ceejatec/centos-70-sgw-build:$TAG . <file_sep>#!/bin/sh cd `dirname $0` # Watson docker containers (currently hosted on mega3) ./restart_jenkinsdocker.py ceejatec/centos-65-couchbase-build:20170522 watson-centos6-01 5222 server.jenkins.couchbase.com # Vulcan CentOS 6 builder ./restart_jenkinsdocker.py couchbasebuild/server-centos6-build:20180713 vulcan-centos6 5225 server.jenkins.couchbase.com ./restart_jenkinsdocker.py couchbasebuild/server-ubuntu16-build:20180905 zz-server-lightweight-backup 5322 server.jenkins.couchbase.com ./restart_jenkinsdocker.py ceejatec/ubuntu-1204-couchbase-build:20151223 watson-ubuntu12.04 5223 server.jenkins.couchbase.com ./restart_jenkinsdocker.py ceejatec/debian-7-couchbase-build:20170522 watson-debian7 5224 server.jenkins.couchbase.com ./restart_jenkinsdocker.py ceejatec/centos-70-couchbase-build:20170522 watson-centos7-01 5227 server.jenkins.couchbase.com # Vulcan CentOS 7 builder ./restart_jenkinsdocker.py couchbasebuild/server-centos7-build:20180829 vulcan-centos7 5228 server.jenkins.couchbase.com ./restart_jenkinsdocker.py ceejatec/debian-8-couchbase-build:20171106 watson-debian8 5229 server.jenkins.couchbase.com # Vulcan Debian 8.2 builder ./restart_jenkinsdocker.py couchbasebuild/server-debian8-build:20180829 vulcan-debian8 5230 server.jenkins.couchbase.com # Temporary cbdeps slave based on Ubuntu 12.04 CV image ./restart_jenkinsdocker.py ceejatec/ubuntu-1204-couchbase-cv:20160304 watson-ubuntu12.04-cv 5233 server.jenkins.couchbase.com wait echo "All done!" <file_sep>#!/bin/sh cd `dirname $0` # Watson docker containers (currently hosted on mega2) ./restart_jenkinsdocker.py ceejatec/ubuntu-1404-couchbase-build:20170522 watson-ubuntu14.04 5226 server.jenkins.couchbase.com # Vulcan Ubuntu 14.04 builder ./restart_jenkinsdocker.py couchbasebuild/server-ubuntu14-build:20180829 vulcan-ubuntu14.04 5232 server.jenkins.couchbase.com # Spock Ubuntu 16.04 builder - using CV image because that helps some # cbdeps builds, notably jemalloc needing valgrind headers ./restart_jenkinsdocker.py ceejatec/ubuntu-1604-couchbase-cv:20170522 spock-ubuntu16.04 5238 server.jenkins.couchbase.com # Spock Debian 9.1 builder ./restart_jenkinsdocker.py ceejatec/debian-9-couchbase-build:20170911 spock-debian9 5230 server.jenkins.couchbase.com # Vulcan Debian 9.1 builder ./restart_jenkinsdocker.py couchbasebuild/server-debian9-build:20180829 vulcan-debian9 5231 server.jenkins.couchbase.com # Vulcan Ubuntu 16.04 slave - probably should use CV image as well, # but don't want to rebuild that yet ./restart_jenkinsdocker.py couchbasebuild/server-ubuntu16-build:20180905 vulcan-ubuntu16.04 5239 server.jenkins.couchbase.com # Primary zz-server-lightweight running on mega2 (same port as backup on mega3) ./restart_jenkinsdocker.py couchbasebuild/server-ubuntu16-build:20180905 zz-server-lightweight 5322 server.jenkins.couchbase.com wait echo "All done!" <file_sep>#!/bin/bash echo "docker stop mobile-sgw-centos6" docker stop mobile-sgw-centos6 echo "docker rm mobile-sgw-centos6" docker rm mobile-sgw-centos6 docker run --name="mobile-sgw-centos6" -v /home/couchbase/jenkinsdocker-ssh:/ssh \ --volume=/home/couchbase/latestbuilds:/latestbuilds \ --restart=unless-stopped \ -p 2320:22 -d ceejatec/centos-65-sgw-build:20170627 <file_sep>#!/bin/bash container_name="mobile-sgw-ubuntu14" container=$(docker ps | grep $container_name | awk -F\" '{ print $1 }') echo "container: $container" if [[ $container ]] then echo "docker rm -f $container_name" docker rm -f $container_name fi # Port number 23xx used by SGW docker run --name=$container_name -v /home/couchbase/jenkinsdocker-ssh:/ssh \ --volume=/home/couchbase/latestbuilds:/latestbuilds \ --restart=unless-stopped \ -p 2321:22 -d ceejatec/ubuntu1404-sgw-build:20180214 <file_sep>#!/bin/bash container_name="mobile-sgw-centos70" container=$(docker ps | grep $container_name | awk -F\" '{ print $1 }') echo "container: $container" if [[ $container ]] then echo "docker rm -f $container_name" docker rm -f $container_name fi docker run --name=$container_name -v /home/couchbase/jenkinsdocker-ssh:/ssh \ --volume=/home/couchbase/latestbuilds:/latestbuilds \ --restart=unless-stopped \ -p 2322:22 -d ceejatec/centos-70-sgw-build:20180214 <file_sep># Docker container for Ubuntu 16.04 # See https://github.com/ceejatec/naked-docker/ for details about the # construction of the base image. FROM ubuntu:16.04 MAINTAINER <EMAIL> USER root # Install SSH server RUN apt-get update && \ apt-get install -y openssh-server sudo && \ apt-get clean && \ mkdir /var/run/sshd # Create couchbase user with password-less sudo privs, and give # ownership of /opt/couchbase RUN useradd couchbase -G sudo -m -s /bin/bash && \ mkdir -p /opt/couchbase && chown -R couchbase:couchbase /opt/couchbase && \ echo 'couchbase:couchbase' | chpasswd && \ sed -ri 's/ALL\) ALL/ALL) NOPASSWD:ALL/' /etc/sudoers # Install Couchbase Lite Android toolchain requirements RUN apt-get update && apt-get install -y git-core tar curl unzip gcc-multilib g++-multilib lib32z1 lib32stdc++6 openjdk-8-jdk gnupg2 zip && \ apt-get clean # Update locale RUN apt-get update && \ apt-get install -y locales && \ apt-get clean && \ locale-gen en_US.UTF-8 ENV LANG=en_US.UTF-8 # Expose SSH daemon and run our builder startup script EXPOSE 22 ADD .ssh /home/couchbase/.ssh COPY build/couchbuilder_start.sh /usr/sbin/ ENTRYPOINT [ "/usr/sbin/couchbuilder_start.sh" ] CMD [ "default" ] # Android SDK USER couchbase # Download and untar Android SDK tools RUN mkdir -p /home/couchbase/jenkins/tools && \ cd /home/couchbase/jenkins/tools && \ wget --no-check-certificate https://dl.google.com/android/repository/tools_r25.2.3-linux.zip -O android-sdk.zip && \ unzip android-sdk.zip -d android-sdk && \ rm android-sdk.zip && \ chown -R couchbase:couchbase android-sdk && \ chmod 755 android-sdk # Set environment variable ENV ANDROID_HOME /home/couchbase/jenkins/tools/android-sdk ENV PATH ${ANDROID_HOME}/tools:$ANDROID_HOME/platform-tools:$PATH # Android SDK License RUN mkdir $ANDROID_HOME/licenses && \ echo 8933bad161af4178b1185d1a37fbf41ea5269c55 > $ANDROID_HOME/licenses/android-sdk-license && \ echo d56f5187479451eabf01fb78af6dfcb131a6481e >> $ANDROID_HOME/licenses/android-sdk-license && \ echo 84831b9409646a918e30573bab4c9c91346d8abd > $ANDROID_HOME/licenses/android-sdk-preview-license # Update and install using sdkmanager ENV SDK_CMD $ANDROID_HOME/tools/bin/sdkmanager RUN $SDK_CMD "tools" "platform-tools" RUN $SDK_CMD "build-tools;27.0.3" "build-tools;27.0.0" "build-tools;26.0.2" "build-tools;25.0.3" RUN $SDK_CMD "platforms;android-27" "platforms;android-26" "platforms;android-25" "platforms;android-24" "platforms;android-16" RUN $SDK_CMD "system-images;android-16;default;armeabi-v7a" RUN $SDK_CMD "system-images;android-24;default;armeabi-v7a" RUN $SDK_CMD "system-images;android-25;google_apis;armeabi-v7a" RUN $SDK_CMD "extras;android;m2repository" "extras;google;m2repository" # Android NDK USER couchbase RUN cd /home/couchbase/jenkins/tools && \ curl -L https://dl.google.com/android/repository/android-ndk-r15c-linux-x86_64.zip -o android-ndk-r15c.zip && \ unzip -qq android-ndk-r15c.zip && \ chown -R couchbase:couchbase android-ndk-r15c && \ chmod 755 android-ndk-r15c && \ rm -rf android-ndk-r15c.zip # Revert so CMD will run as root. USER root # gpg maven COPY couchhook.sh /usr/sbin/
e17642bd8ee9b58ea1aaf5af609a39d3832d2721
[ "Dockerfile", "Shell" ]
14
Shell
jameseh96/build
3b8998ac0ce6c6fd2609b1bb5fddc793a9cbff67
b069c5d46129d6cada92df4e03e29b6ee7896809
refs/heads/master
<file_sep>package com.example.hoangnguyen.americanstem; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Space; import com.google.zxing.Result; import me.dm7.barcodescanner.zxing.ZXingScannerView; public class MainMenu extends AppCompatActivity implements ZXingScannerView.ResultHandler{ private ZXingScannerView mScannerView; private String treeID[] = {"0"}; //Not for use yet private String name[] = {"Test"}; private String person[] = {"Dr. Le"}; private String bdate[] = {"6/9/2017"}; private String extrainfo[] = {"bla bla"}; private int[] picID = {R.drawable.logo}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main_menu); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int h = dm.heightPixels; int w = dm.widthPixels; ImageView background = (ImageView)findViewById(R.id.background); ImageView showImg = (ImageView)findViewById(R.id.dialog_imageview); Space blank = (Space)findViewById(R.id.blank); Button but1 = (Button)findViewById(R.id.btn1); Button but2 = (Button)findViewById(R.id.btn2); Button but3 = (Button)findViewById(R.id.btn3); ImageButton but4 = (ImageButton)findViewById(R.id.btn4); background.getLayoutParams().height = (h/2); background.getLayoutParams().width = (w - (w/100)*5); background.setImageResource(R.drawable.logo); showImg.getLayoutParams().height = h/4*3; showImg.getLayoutParams().width = w/4*3; blank.getLayoutParams().height = (h/20); but1.getLayoutParams().height = (w/2 - w/4 + w/16); but1.getLayoutParams().width = (w/2 - w/4 + w/16); but2.getLayoutParams().height = (w/2 - w/4 + w/16); but2.getLayoutParams().width = (w/2 - w/4 + w/16); but3.getLayoutParams().height = (w/2 - w/4 + w/16); but3.getLayoutParams().width = (w/2 - w/4 + w/16); but4.getLayoutParams().width = (w/2 - w/4 + w/16); but4.getLayoutParams().height = (w/2 - w/4 + w/16); Animation fadeIn = new AlphaAnimation(0, 1.0f); fadeIn.setDuration(2222); background.setAnimation(fadeIn); but1.setAnimation(fadeIn); but2.setAnimation(fadeIn); but3.setAnimation(fadeIn); but4.setAnimation(fadeIn); } public void goScan (View v) { mScannerView = new ZXingScannerView(this); setContentView(mScannerView); mScannerView.setResultHandler(this); mScannerView.startCamera(); } @Override protected void onPause() { super.onPause(); mScannerView.stopCamera(); mScannerView.stopCameraPreview(); } @Override public void handleResult(Result rawResault) { Log.e("handler", rawResault.getText()); Log.e("handler", rawResault.getBarcodeFormat().toString()); String dialogMessage; int codeID; String rawResult = rawResault.getText().toString(); //String newLine = System.getProperty("line.separator"); String getID[] = rawResult.split("\\s+", 2); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Scan Result"); LayoutInflater factory = LayoutInflater.from(this); final View view = factory.inflate(R.layout.sample, null); try { codeID = Integer.parseInt(getID[0]); dialogMessage = ("Name: " + name[codeID] + "\nPlanted by(Tree only): " + person[codeID] + "\nDOB: " + bdate[codeID] + "\nExtra: " + extrainfo[codeID]); ImageView showImg = (ImageView)findViewById(R.id.dialog_imageview); showImg.setImageResource(picID[codeID]); } catch (NumberFormatException e) { dialogMessage = ("Invalid AmericanSTEM QR Code"); } //int QRres = Integer.parseInt(rawResault.getText()); builder.setMessage(dialogMessage); //Result goes here builder.setPositiveButton("Okay", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = getIntent(); finish(); startActivity(intent); } }); builder.setView(view); AlertDialog showRes = builder.create(); showRes.show(); } public void goAbout (View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://americanstem.vn")); startActivity(browserIntent); System.exit(0); } public void goQuit (View v) { ImageView bg = (ImageView)findViewById(R.id.background); Button but1 = (Button)findViewById(R.id.btn1); Button but2 = (Button)findViewById(R.id.btn2); Button but3 = (Button)findViewById(R.id.btn3); Animation fadeOut = new AlphaAnimation(1.0f, 0); fadeOut.setDuration(6666); bg.setAnimation(fadeOut); but1.setAnimation(fadeOut); but2.setAnimation(fadeOut); but3.setAnimation(fadeOut); try { System.exit(0); Thread.sleep(5000); } catch (InterruptedException ex) { } } public void goAme (View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://americanstem.vn")); startActivity(browserIntent); System.exit(0); } } <file_sep># AmericanSTEMandroid (unfinished) Company internal app for AmericanSTEM Last edit: 18:21 June 29th, 19 Writen (unfinished) by <NAME> BEFORE BUILDING THE PROJECT IN ANDROID STUDIO: - Remember to extract file "intermediates.zip" in folder app/build to the same location (AmericanSTEM/app/build) *More to be added later
6f21cce780436d2519c1f33e2efd80d9833e2043
[ "Markdown", "Java" ]
2
Java
koben98/AmericanSTEMandroid
4a521556dcd146f45f537cfcc2032d718683b444
d93701824f5b2d579304b92dfe1ab8d8f0da68d4
refs/heads/master
<repo_name>mutual-of-enumclaw/guard-rails<file_sep>/DeleteUserSQS/DeleteUserSQS.test.js /*! * Copyright 2017-2017 Mutual of Enumclaw. All Rights Reserved. * License: Public */ //Test function for DeleteUserSQS.js const config = require('./config.json'); //Environment variable values defined from the config.json file. Object.keys(config).forEach((key) => { process.env[key] = config[key]; }) const main = require(`./DeleteUserSQS`); const Master = require('./MasterClass').handler; let master = new Master(); let event = require("./__data__/event").event; //overriding the ses.sendEmail operation to just log the html snippet master.setSes((params) => { let html = params.Message.Body.Html.Data; html = html.replace('data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUTExIVFhUVFxYWFxUYFxUXFxgXFxcWFhcVFRgYHSggGBolHRUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKBQUFDgUFDisZExkrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrK//AABEIARMAtwMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAAEBQMGAAIHAQj/xABBEAABAwMBBQUGBAQFBAIDAAABAAIRAwQhMQUSQVFhBiJxgZETobHB0fAyQlLhBxRichUjM4LxU5KiwrLSFjRD/8QAFAEBAAAAAAAAAAAAAAAAAAAAAP/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AKLccXc/w9BzWlvYye99/fzTWtTbMAafYH1KMtrQwCepg8eUoBrehn0MaYGgRNetBAE70SMcYMfX0RZpRnz6k/lB95SupX3d/GS0AHUiZx<KEY>', 'annoying image link'); console.log(html); return {promise: () => {} } }) //*******remediationTest() parameter examples********** //event > the event that is passed to the main function. (Call getEvent()) //functionName > "detachRolePolicy" (no cap on first letter). The aws iam function you //want to override //_____________getEvent() parameters for reference_____________ //env, launch, eventName, requestParameters, responseElements describe(`Remediate a User`, () => { // test calls ************* CHANGE ************* test(`Testing CreateUser going through SQS event`, async() => { await remediationTest('deleteUser'); }); }); //test function async function remediationTest(functionName) { //overriding the iam function being called so it just checks for the correct params await main.setFunction(functionName, (params) => { return {promise: () => {} } }); await main.setFunction('deleteLoginProfile', (params) => { return {promise: () => {} } }); await main.setFunction('deleteMessage', (params) => { return {promise: () => {} } }); await main.setSQS((params) => { return {promise: () => {} }; }); await main.handler(event); console.log("-------------------------------------------------------"); }<file_sep>/Role/RemediateRoles.js /*! * Copyright 2017-2017 Mutual of Enumclaw. All Rights Reserved. * License: Public */ //Mutual of Enumclaw // //<NAME> and <NAME> - 2019 :) :) // //Main file that controls remediation and notifications of all IAM Role events. //Remediates actions when possible or necessary based on launch type and tagging. Then, notifies the user/security. const AWS = require('aws-sdk'); AWS.config.update({region: process.env.region}); let iam = new AWS.IAM(); const Master = require("./MasterClass").handler; let path = require("./MasterClass").path; let stopper = require("./MasterClass").stopper; let dbStopper = require("./MasterClass").dbStopper; let master = new Master(); let improperLaunch = false; //Variables that allow these functions to be overridden in Jest testing by making the variable = jest.fn() //instead of its corresponding function let callAutoTag = autoTag; let callCheckTagsAndAddToTable = checkTagsAndAddToTable; let callRemediate = remediate; let callRemediateDynamo = remediateDynamo; //********************************************************************************************** //remediates a specific action after receiving an event log async function handleEvent(event) { console.log(JSON.stringify(event)); path.n = 'Path: '; //Conditionals for a dynamo event if(await master.checkDynamoDB(event)){ path.n += 'DB'; let convertedEvent = await master.dbConverter(event); //Extra console.log statements for testing =================================== if (convertedEvent.ResourceName) { console.log(`"${convertedEvent.ResourceName}" is being inspected----------`); } else { console.log(`"${event.Records[0].dynamodb.Keys.ResourceName.S}" is being inspected----------`); } //================================================== //remediation process and checking tags for a Dynamodb event if (convertedEvent.ResourceType == "Role" && event.Records[0].eventName == 'REMOVE'){ path.n += '1'; try{ let tags = await iam.listRoleTags({RoleName: convertedEvent.ResourceName}).promise(); if (!(await master.tagVerification(tags.Tags))) { path.n += '2'; await callRemediateDynamo(event, convertedEvent); } } catch(e){ if (e.code == 'NoSuchEntity') { console.log(e); path.n += '!!'; console.log("**************NoSuchEntity error caught**************"); console.log(path.n); return e; } } } else { path.n += '6'; console.log('**************Event didn\'t meet standards, ending program**************') } console.log(path.n); return; } //Checks the event log for any previous errors. Stops the function if there is an error. if (master.errorInLog(event)) { path.n += 'Error in Log'; console.log(path.n); return; } console.log(`"${event.detail.requestParameters.roleName}" is being inspected----------`); console.log(`Event action is ${event.detail.eventName}---------- `); //Conditionals to stop the function from continuing if (await master.selfInvoked(event)) { path.n += 'Self Invoked'; console.log(path.n); return; } else if (!(await master.checkKeyUser(event, 'roleName'))) { path.n += 'Key Not Found'; console.log(path.n); return; } //Checks if the event is invalid. If it is invalid, then remediate. Else check for tags and add to the table with a TTL if (await master.invalid(event)) { path.n += '1'; improperLaunch = true; await callRemediate(event); if (event.detail.eventName == "CreateRole") { console.log(path.n); return; } } else if (event.detail.eventName.includes('Delete')) { path.n += '2'; if (master.isConsole(event)) { path.n += '3'; improperLaunch = true; console.log('Action was "Delete" and done through console---------------'); await callRemediate(event); } else { path.n += 'X'; } } await callCheckTagsAndAddToTable(event); console.log(path.n); }; //********************************************************************************************** //Checks for and auto adds tags and then adds resource to the table if it is missing any other tags async function checkTagsAndAddToTable(event) { let params = { RoleName: event.detail.requestParameters.roleName }; let tags = {}; path.checkTagsAndAddToTable += '1'; try { tags = await callAutoTag(event, params); path.checkTagsAndAddToTable += '2'; } catch(e) { if (e.code == 'NoSuchEntity') { console.log(e); path.checkTagsAndAddToTable += '!!'; console.log("**************NoSuchEntity error caught**************"); return e; } } if (!(await master.tagVerification(tags.Tags))) { path.checkTagsAndAddToTable += '3'; await master.putItemInTable(event, 'Role', params.RoleName); } else { path.checkTagsAndAddToTable += '4'; } } //********************************************************************************************** //Remediates the action performed and sends an email async function remediate(event) { path.remediate += '='; if (dbStopper.c) { console.log(`Stopper: ${JSON.stringify(dbStopper)}`); dbStopper.c -= 1; path.remediate += '-'; console.log(`Stopper in place for ${dbStopper.c} more invocations`); if (dbStopper.c == 0) { console.log('Stopper removed----------'); path.remediate += 'X'; delete dbStopper.c; } path.remediate += '!' console.log(`*******Remediation completed in previous invocation*******`) return; } //Sets up required parameters for remediation const erp = event.detail.requestParameters; let params = { RoleName: erp.roleName }; let results = await master.getResults(event, { RoleName: params.RoleName }); let id = erp.PolicyArn; if (results.Action == 'CreateRole' || results.Action == 'DeleteRole') { id = results.RoleName; } else if (results.Action == 'AttachRolePolicy' || results.Action == 'DetachRolePolicy') { id = erp.policyArn; } else { id = erp.policyName; } if (process.env.environment != 'snd' && stopper.id == id) { console.log(`*********Resource has already been remediated manually*********`); console.log(`Stopper removed-------`); stopper.id = ''; path.n = "!"; return; } //Decides, based on the incoming event name, which function to call to perform remediation try { switch(results.Action){ case "CreateRole": path.remediate += '1'; results.Response = 'DeleteRole'; results.Reason = 'Improper Launch'; await callRemediateDynamo(event, results); return; case "PutRolePolicy": path.remediate += '2'; params.PolicyName = erp.policyName; await iam.deleteRolePolicy(params).promise(); results.PolicyName = erp.policyName; results.Response = "DeleteRolePolicy"; break; case "AttachRolePolicy": path.remediate += '3'; params.PolicyArn = erp.policyArn; await iam.detachRolePolicy(params).promise(); results.PolicyArn = erp.policyArn; results.Response = "DetachRolePolicy"; break; case "DetachRolePolicy": path.remediate += '4'; params.PolicyArn = erp.policyArn; await iam.attachRolePolicy(params).promise(); results.PolicyArn = erp.policyArn; results.Response = "AttachRolePolicy"; break; case "DeleteRolePolicy": path.remediate += '5'; results.PolicyName = erp.policyName; results.Response = "Remediation could not be performed"; break; case "DeleteRole": path.remediate += '6'; results.Response = 'Remediation could not be performed'; break; }; } catch(e) { if (e.code == 'NoSuchEntity') { stopper.id = id; console.log(`Stopper set on ${id}-------------`); console.log(e); path.n += '!!'; console.log("**************NoSuchEntity error caught**************"); return e; } } console.log("Remediation completed-----------------"); results.Reason = 'Improper Tags'; if (improperLaunch) { results.Reason = 'Improper Launch'; } if (results.Response == 'Remediation could not be performed') { delete results.Reason; } path.n += '='; await master.notifyUser(event, results); } //********************************************************************************************** //Function to remediate the event coming from DynamoDB. Remediates all attachments before removing the role async function remediateDynamo(event, results){ let params = {}; if (results.KillTime) { params = { RoleName: results.ResourceName } } else { params = { RoleName: event.detail.requestParameters.roleName }; } let count = 0; //lists the attachments let inline = {}; let attached = {}; try { inline = await iam.listRolePolicies(params).promise(); attached = await iam.listAttachedRolePolicies(params).promise(); } catch(e) { if (e.code == 'NoSuchEntity') { console.log(e); path.n += '!!'; console.log("**************NoSuchEntity error caught**************"); return e; } } //checks if there is at least one attachment that needs remediation if (inline.PolicyNames[0] || attached.AttachedPolicies[0]) { let newEvent = event; if (results.KillTime) { path.n += '3'; let requestParameters = { roleName: params.RoleName, policyName: '', policyArn: '' } newEvent = await master.TranslateDynamoToCloudwatchEvent(event, requestParameters); } //Remediates all the inline policies if (inline.PolicyNames[0]) { path.n += '4'; for (let i = 0; i < inline.PolicyNames.length; i++) { count += 1; newEvent.detail.requestParameters.policyName = inline.PolicyNames[i]; newEvent.detail.eventName = 'PutRolePolicy'; console.log(`deleting "${newEvent.detail.requestParameters.policyName}"---------`); await callRemediate(newEvent); } } //Remediates all the attached policies if (attached.AttachedPolicies[0]) { path.n += '5'; for (let i = 0; i < attached.AttachedPolicies.length; i++) { count += 1; newEvent.detail.requestParameters.policyArn = attached.AttachedPolicies[i].PolicyArn; newEvent.detail.eventName = 'AttachRolePolicy'; console.log(`detaching "${newEvent.detail.requestParameters.policyArn}"---------`); await callRemediate(newEvent); } } } if (!results.KillTime && count != 0) { dbStopper.c = count; console.log(`Stopper placed for ${count} more invocations--------`) } path.n += '-'; console.log(`deleting "${params.RoleName}"----------`); let InstanceProfiles = await iam.listInstanceProfilesForRole(params).promise() //removes an instance profile, if it is attached, from the role in order to delete the role. if (InstanceProfiles.InstanceProfiles[0]) { params.InstanceProfileName = params.RoleName; path.n += '.'; iam.removeRoleFromInstanceProfile(params).promise(); delete params.InstanceProfileName; } //Deletes the role await iam.deleteRole(params).promise(); console.log('Remediation complete----------'); path.n += '-'; await master.notifyUser(event, results); } //********************************************************************************************** //Automatically adds missing tags, tag3 and Environment, if needed async function autoTag(event, params) { let tags = await iam.listRoleTags(params).promise(); //checks if env is sandbox AND checks for and adds tag3 tag if (await master.snd() && await master.needsTag(tags.Tags, `${process.env.tag3}`)){ //Adds the tag3 tag to the resource await iam.tagRole(await master.getParamsForAddingTags(event, params, `${process.env.tag3}`)).promise(); tags = await iam.listRoleTags(params).promise(); path.n += '5'; console.log(`${process.env.tag3} added---------`); } //checks if the resource has an environment tag and adds it if it doesn't if (await master.needsTag(tags.Tags, 'Environment')) { //Adds the Environment tag to the resource await iam.tagRole(await master.getParamsForAddingTags(event, params, 'Environment')).promise(); tags = await iam.listRoleTags(params).promise(); path.n += '6'; console.log('Environment Tag added---------'); } return tags; } exports.handler = handleEvent; exports.checkTagsAndAddToTable = checkTagsAndAddToTable; exports.remediateDynamo = remediateDynamo; exports.autoTag = autoTag; exports.remediate = remediate; //overrides the given function (only for jest testing) exports.setIamFunction = (value, funct) => { iam[value] = funct; } exports.setAutoTag = (funct) => { callAutoTag = funct; } exports.setRemediate = (funct) => { callRemediate = funct; } exports.setRemediateDynamo = (funct) => { callRemediateDynamo = funct; } exports.setCheckTagsAndAddToTable = (funct) => { callCheckTagsAndAddToTable = funct; } //Created by <NAME> and <NAME>. Ur fav 2019 interns!! :) :) <file_sep>/Policy/MasterClass.js /*! * Copyright 2017-2017 Mutual of Enumclaw. All Rights Reserved. * License: Public */ //Mutual of Enumclaw // //<NAME> and <NAME> - 2019 :) :) // //Class file containing many functions used throughout the main files to perform specific jobs. //All functions perform a specific task and none are built for an individual file. const AWS = require('aws-sdk'); AWS.config.update({region: process.env.region}); const sns = new AWS.SNS(); const ses = new AWS.SES(); const dynamodb = new AWS.DynamoDB(); let reason = { Reason: 'Reason not specified'}; let subject = { Subject: '¯\\_(ツ)_/¯' }; let path = { n: 'Path: ' }; let stopper = { id: '' }; let dbStopper = {}; class Master { //********************************************************************************************** //Checks the event log for previous errors /**/errorInLog(event) { if (event.detail.errorCode) { console.log(`************There was an error in the event log (code: "${event.detail.errorCode}")************`); return true; } return false; } //********************************************************************************************** //Checks to see if there is any specific properties of the resource before running the function (testing only) /**/checkKeyUser(event, resourceName){ //checking event.detail.responseElements.policy.policyName if(event.detail.userIdentity.principalId.includes(`${process.env.internEmail2}`) || event.detail.userIdentity.principalId.includes(`${process.env.internEmail1}`) || event.detail.userIdentity.arn.includes(`${process.env.serverlessInfo}`) || event.detail.requestParameters[resourceName].includes("@@@")) { console.log("Found the key!~~~~"); return true; } console.log("*************Did not find key, ending program*************"); return false; } //********************************************************************************************** //Checks to see if the event coming from DynamoDB. /**/checkDynamoDB(event){ if(event.Records){ console.log("Event is DynamoDB!~~~~~~~~~~~"); return true; } console.log("Event is NOT DynamoDB!~~~~~~~~~~~~"); return false; } //********************************************************************************************** //Converts the information coming from DynamoDB into an actual JSON file for js to read /**/dbConverter(event){ let info = event.Records[0].dynamodb.OldImage; var unmarshalled = AWS.DynamoDB.Converter.unmarshall(info); return unmarshalled; } //********************************************************************************************** //checks if the event was from the function itself /**/selfInvoked(event) { if (event.detail.userIdentity.arn.includes(process.env.name)) { console.log('****************************Self invoked****************************'); return true; } return false; } //********************************************************************************************** //Gets the entity that performed the action and returns it. /**/getEntity(event){ let id = event.detail.userIdentity.principalId; if (id.includes(':') && !id.includes('@')) { let index = id.indexOf(":") + 1; return `${id.substring(index)} --Likely a lambda function`; } else if (id.includes('@')) { let index = id.indexOf(":") + 1; return id.substring(index); } else { return `${event.detail.userIdentity.userName} --Launched through serverless/TFS`; } } //********************************************************************************************** //Validates the event log (determines whether it comes from console, console being invalid) /**/invalid(event){ //checks if self invoked if (this.snd()) { console.log('****************Performed in Sandbox so event is valid****************'); return false; } else if (this.isConsole(event)) { console.log('Performed through console and in dev/prd so event log is invalid-----------------------'); return true; } console.log('****************Performed through Serverless/TFS so event is valid****************'); return false; }; //********************************************************************************************** //Function used to check to see if the event is coming from console /**/isConsole(event){ if((event.detail.userIdentity.sessionContext.sessionIssuer) || (event.detail.userAgent != 'cloudformation.amazonaws.com')){ return true; } return false; } //********************************************************************************************** //Creates the HTML for the user that performed the action depending on the event type and returns it /**/getHtml(event, results) { let env = process.env.environment; let message = this.structureMessage(results); let resultsArray = Object.entries(results); subject.Subject = 'Your AWS stuff was deleted...¯\\_(ツ)_/¯'; let attachmentId = `attachment "${resultsArray[4][1]}" on` let resourceName = resultsArray[3][1]; let header = 'Your AWS stuff was remediated...</br>¯\\_(ツ)_/¯'; let description = ''; let howToFixMessage = `Please add the correct tags to "${resourceName}" to prevent deletion (${process.env.tag1} and ${process.env.tag2}).`; let img = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUTExIVFhUVFxYWFxUYFxUXFxgXFxcWFhcVFRgYHSggGBolHRUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKBQUFDgUFDisZExkrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrK//AABEIARMAtwMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAAEBQMGAAIHAQj/xABBEAABAwMBBQUGBAQFBAIDAAABAAIRAwQhMQUSQVFhBiJxgZETobHB0fAyQlLhBxRichUjM4LxU5KiwrLSFjRD/8QAFAEBAAAAAAAAAAAAAAAAAAAAAP/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AKLccXc/w9BzWlvYye99/fzTWtTbMAafYH1KMtrQwCepg8eUoBrehn0MaYGgRNetBAE70SMcYMf<KEY>'; let shruggs = '¯\\_(ツ)_/¯'; let color = ``; let colorHeader = ``; let spaces = '</br></br>'; //If the event is the result of a taggable resource being deleted if (results.KillTime) { path.n += 'A'; header = `Your ${results.ResourceType} has been deleted...</br>¯\\_(ツ)_/¯`; description = `Your ${results.ResourceType} "${results.ResourceName}" has been deleted and all its attachments have been remediated by AWS Automated Security.`; howToFixMessage = `Next time, please be sure to add the proper tags to your ${results.ResourceType} (${process.env.tag1} and ${process.env.tag2}).`; color = `style = 'color:red'`; //If the event is just the creation of a resource with incorrect tags } else if (!results.Response) { path.n += 'B'; subject.Subject = 'You forgot your tags...¯\\_(ツ)_/¯'; let days = this.undoEpoch(this.createTTL(event)); let s = 's'; if (days == 1) { s = ''; } header = 'Ahhhh Snap! You forgot your tags...</br>¯\\_(ツ)_/¯'; description = `Your ${results.ResourceType} "${resourceName}" has been archived for deletion in ${days} day${s} by AWS Automated Security.`; //If a resource was deleted and cannot be recreated } else if (results.Response == 'Remediation could not be performed'){ path.n += 'C'; let id = resultsArray[4][1]; img = ''; if (resultsArray[4][0] == 'Response') { attachmentId = `resource`; id = resourceName; } subject.Subject = `Improper Deletion`; colorHeader = `style="color:red"`; header = `${id} was deleted...`; description = `You have improperly deleted the ${attachmentId} "${resourceName}".`; howToFixMessage = `Next time, please remove through Serverless or TFS when deleting resources.`; spaces = `</br>`; shruggs = ''; //If the event was the remediation of a creation of a new policy version } else if (results['Reset Default Version']){ path.n += 'D'; subject.Subject = `A default policy version has been reset. ${shruggs}`; colorHeader = `style = 'color:red'`; header = `The policy version ${results["Old Default Version"]} has been reset... ${shruggs}`; description = `The policy "${resourceName}" has been set to ${results['Reset Default Version']} by AWS Automated Security.`; howToFixMessage = `Next time, please deploy through Serverless or TFS when creating new policy versions.`; //Default notification } else { path.n += 'E'; subject.Subject = 'Your AWS stuff was remediated...¯\\_(ツ)_/¯'; if (resultsArray[4][0] == 'Response') { attachmentId = 'resource'; } description = `The ${attachmentId} ${resourceName} has been remediated by AWS Automated Security.`; if (results.Reason == 'Improper Launch') { howToFixMessage = `Next time, please deploy through Serverless or TFS when working in ${env} to prevent remediation`; } color = `style="color:red"`; } return ` <html> <body style="width:100%"> <div style="width:100%"> <h1 ${colorHeader}>${header}</h1> <p ${color}>${description}</p> <p>${howToFixMessage}</p> <p>${spaces}${message}</p> <div style="text-align:center"> </br></br><a href = https://giphy.com/gifs/work-get-dad-2Zxe4ZB4i1yJW/fullscreen><img src=${img}></a> </div> <div style="text-align:center"> <font></br></br></br><b>Have a wonderful day!</b></font> </div> <div style="text-align:center"> <font>${shruggs}</font> </div> </div> </body> </html>`; } //********************************************************************************************** //Creates the HTML for an email to security depending on the event type and returns it /**/getHtmlSecurity(event, results){ let env = process.env.environment; let message = this.structureMessage(results); let resultsArray = Object.entries(results); subject.Subject = `Someone forgot their tags in ${env}.`; let attachmentId = `attachment "${resultsArray[4][1]}" on`; let resourceName = resultsArray[3][1]; let header = `AWS stuff was remediated in ${env}...</br>`; let description = ''; let color = ``; let colorHeader = ``; let spaces = `</br>`; //If the event is the result of a taggable resource being deleted if (results.KillTime) { path.n += 'F'; subject.Subject = `A ${results.ResourceType} was auto-deleted in ${env}` header = `A ${results.ResourceType} has been auto-deleted in ${env}...</br>`; description = `A ${results.ResourceType} "${results.ResourceName}" has been deleted and all its attachments have been remediated by AWS automated security.`; color = `style = 'color:red'`; //If the event is just the creation of a resource with incorrect tags } else if (!results.Response) { path.n += 'G'; header = `A resource was created in ${env} without the proper tags.</br>`; let days = this.undoEpoch(this.createTTL(event)); let s = 's'; if (days == 1) { s = ''; } description = `A ${results.ResourceType} "${resourceName}" has been archived for deletion in ${days} day${s} by AWS Automated Security. The correct tags need to be added to "${resourceName}" to prevent deletion (${process.env.tag1} and ${process.env.tag2}).`; spaces = '</br></br>'; //If a resource was deleted and cannot be recreated } else if (results.Response == 'Remediation could not be performed'){ path.n += 'H'; let id = resultsArray[4][1]; if (resultsArray[4][0] == 'Response') { attachmentId = `resource`; id = resourceName; } subject.Subject = `Improper Deletion in ${env}`; colorHeader = `style="color:red"`; header = `${id} was deleted through ${env} console...`; description = `The ${attachmentId} "${resourceName}" has been deleted by "${results['Entity Responsible']}" through ${env} console and could not be remediated by AWS Automated Security.`; //If the event was the remediation of a creation of a new policy version } else if(results['Reset Default Version']){ path.n += 'I'; subject.Subject = `A default policy version has been auto-reset in ${env}.`; colorHeader = `style = 'color:red'`; header = `The policy version ${results["Old Default Version"]} was improperly set to default through ${env} console...`; description = `The policy "${resourceName}" has been set to ${results['Reset Default Version']} by AWS Automated Security.`; //Default notification } else { path.n += 'J'; subject.Subject = `An AWS resource was remediated in ${env}.`; if (resultsArray[4][0] == 'Response') { attachmentId = 'resource'; } description = `The ${attachmentId} "${resourceName}" has been remediated by AWS Automated Security.`; color = `style="color:red"`; } //returns the html template with the defined variables inside return ` <html> <body style="width:100%"> <div style="width:100%"> <h1 ${colorHeader}>${header}</h1> <p ${color}>${description}</p> <p>${spaces}${message}${spaces}</p> <div style="text-align:center"> <a href = https://giphy.com/gifs/maury-maury-face-xT1XGWbE0XiBDX2T8Q/fullscreen>uuuhhh oooh....</a> <font></br></br></br><b>Have a wonderful day!</b></font> </div> </div> </body> </html>`; }; //********************************************************************************************** //Builds the results object /**/getResults(event, property) { return { Action: event.detail.eventName, Environment: process.env.environment, "Entity Responsible": this.getEntity(event), ...property }; } //********************************************************************************************** //Returns a cloudwatch event given a dynamo event with specified requestParameters /**/TranslateDynamoToCloudwatchEvent(event, requestParameters){ return { detail: { userIdentity: { principalId: `ASDFGHJAKKHGFG:${event.Records[0].dynamodb.OldImage['Entity Responsible'].S}` }, eventName: '', requestParameters: { ...requestParameters } } } } //********************************************************************************************** //Sends an email to the user //notifyUser async notifyUser(event, results){ const sender = `${process.env.sender}`; let recipient = ''; let body_html = ''; if (results['Entity Responsible'].includes('@') && event.Recusion == undefined) { recipient = results['Entity Responsible']; console.log("Sending to user! ~~~~~~~~~~~~~~~~~~"); body_html = await this.getHtml(event, results); path.n += 'U' if(results.Response == "Remediation could not be performed"){ event.Recusion = true; path.n += 'M'; await this.notifyUser(event, results); } } else { path.n += 'S'; console.log("Sending to security! ~~~~~~~~~~~~~~~~~~"); recipient = `${process.env.internEmail1}`; body_html = await this.getHtmlSecurity(event, results); } var params = { Source: sender, Destination: { ToAddresses: [ recipient ] }, Message: { Subject: { Data: subject.Subject }, Body: { Text: { Data: '' }, Html: { Data: body_html } } } } await ses.sendEmail(params).promise(); path.n += '^'; console.log(`**************Message sent to ${recipient}**************\n\n`); }; //********************************************************************************************** //Helper function that structures the email //structureMessage structureMessage(results) { //Reorders the results properties for the dynamo event to the baseline order so the email structures correctly. if(results.KillTime) { results = { Action: results.Action, "Entity Responsible": results['Entity Responsible'], Environment: process.env.environment, ResourceName: results.ResourceName, ResourceType: results.ResourceType, Reason: results.Reason } } results = Object.entries(results); //converts the given results information into an html display const rows = results.map((pair) => { return `<tr><td style="padding: 5px "><b>${pair[0]}:</b></td><td>${pair[1]}</td></tr>`; }).join(''); let message = ` <table style="width:100%"> ${rows} </table>`; return message; }; //********************************************************************************************** //functions that return whether or not the event is in the specific environment. /**/snd() { return process.env.environment == 'snd'; } /**/dev(event) { let num = this.getNumber(event); return num == `${process.env.devNum1}` || num == `${process.env.devNum2}`; } /**/prd(event) { let num = this.getNumber(event); return num == `${process.env.prdNum1}` || num == `${process.env.prdNum2}`; } //gets the number that corresponds the the environment for the given event. /**/getNumber(event) { return event.detail.userIdentity.accountId; } //********************************************************************************************** //Returns if the given resource is in the table or not. //checkTable async checkTable(ResourceName, ResourceType){ console.log("Checking table for item."); let params = { Key: { "ResourceName": { S: ResourceName }, "ResourceType":{ S: ResourceType } }, TableName: `remediation-db-table-${process.env.environment}-ShadowRealm` }; let pulledItem = await dynamodb.getItem(params).promise(); if(pulledItem.Item){ console.log(`**************Found ${ResourceName} in the table, ending program**************`); return true; } console.log(`Did not find ${ResourceName}-------`); return false; } //********************************************************************************************** //Returns the amount of time before the item is deleted from the table depending on it's environment /**/createTTL(event) { if(this.snd()) { return this.getTime(.002); //CHANGE TO 30 DAYS WHEN GUARD RAILS ARE OFF } else if(this.dev(event)) { return this.getTime(1); } return this.getTime(7); } //helper function that translates the current time into epoch based on days to wait /**/getTime(days) { let time = new Date().getTime() / 1000 + days * 86400; return time + ''; } //returns the number of days that the given epoch time represents /**/undoEpoch(time) { let days = (time - new Date().getTime() / 1000) / 86400; return Math.ceil(days); } //********************************************************************************************** //checks if the given service has all the right tags, returns true if it does. /**/tagVerification(tags){ //Stores only unique values for counting the tags let keySet = new Set(); //Checks for the two required tags.forEach((object) => { const key = object.Key.trim(); if (key == `${process.env.tag2}` || key == `${process.env.tag1}`) { keySet.add(key); } }); if (keySet.size == 2) { path.n += '*'; console.log('**************Tag verification succeeded, ending program**************'); return true; } reason.Reason = 'Improper Tags'; console.log('Required tags not found-----------------'); path.n += '7'; return false; } //********************************************************************************************** //Returns the required params for adding tags to the resource /**/getParamsForAddingTags(event, params, tagName) { let value = ''; if (tagName == 'Environment') { value = process.env.environment; } else { value = this.getEntity(event); } return { Tags: [ { Key: tagName, Value: value } ], ...params }; } //********************************************************************************************** //checks if the the specified tag needs to be added. Returns true if it does. /**/needsTag(tags, tagName) { if (tags.find((object) => { return object.Key.trim() == tagName; }) == undefined) { console.log(`no ${tagName} found-------------`); return true; } console.log(`${tagName} found-----------`) return false; } //********************************************************************************************** //Adds the given resource to the dynamodb table //putItemInTable async putItemInTable(event, ResourceType, ResourceName) { //Checks to see if the resource is already in the table to prevent restarting the TTL and sending multiple emails if(await this.checkTable(ResourceName, ResourceType)) { path.n += '_'; return; } //Builds the params to add to the dynamodb table var params = { TableName: `remediation-db-table-${process.env.environment}-ShadowRealm`, Item: { 'Action': { S: event.detail.eventName }, 'ResourceType': { S: ResourceType }, 'ResourceName': { S: ResourceName }, 'Entity Responsible': { S: await this.getEntity(event) }, 'KillTime': { N: await this.createTTL(event) }, 'Reason': {S: reason.Reason} } } //Adds to dynamodb table with TTL console.log('Adding to table--------'); await dynamodb.putItem(params).promise(); path.n += '+'; await this.notifyUser(event, await this.getResults(event, { ResourceName: ResourceName, ResourceType: ResourceType, Reason: reason.Reason})); } //********************************************************************************************** //overrides the publish property/function of sns (only for jest testing) /**/setSns(value) { sns.publish = value; } //overrides the sendEmail property/function of ses (only for jest testing) /**/setSes(value) { ses.sendEmail = value; } //overrides the putItem property/function of dynamodb (only for jest testing) /**/setDynamo(value) { dynamodb.putItem = value; } } module.exports.path = path; module.exports.stopper = stopper; module.exports.dbStopper = dbStopper; exports.handler = Master; //Created by <NAME> and <NAME>. Ur fav 2019 interns!! :) :) <file_sep>/README.md # guard-rails guard-rails is an automated aws resource management and remediation system. It monitors all IAM actions, deployment types, environments and resource tags. This data is then used to decide whether the action done to an IAM resource is valid or not and determine the best response. Responses to invalid actions may include: notifying security, notifying the user, remediating the action immediately, and archiving the resource created for some time and then notifying the user of potential deletion. # MasterClass.js Class file containing many functions used throughout the main files to perform specific jobs. All functions perform a specific task and none are built for an individual file. # RemediateGroups.js Main file that controls remediation and notifications of all IAM Group events. Remediates actions when possible or necessary based on launch type and tagging. Then, notifies the user/security. # RemediatePolicies.js Main file that controls remediation and notifications of all IAM Policy events. Remediates actions when possible or necessary based on launch type and tagging. Then, notifies the user/security. # RemediateRoles.js Main file that controls remediation and notifications of all IAM Role events. Remediates actions when possible or necessary based on launch type and tagging. Then, notifies the user/security. # RemediateUsers.js Main file that controls remediation and notifications of all IAM User events. Remediates actions when possible or necessary based on launch type and tagging. Then, notifies the user/security. # DeleteUserSQS.js Supporting function file that controls the remediation of creating a user. Invoked by SQS after some time, this function will delete the specified user. SQS waits to invoke this function so the user has enough time to be created. <file_sep>/Group/RemediateGroups.js /*! * Copyright 2017-2017 Mutual of Enumclaw. All Rights Reserved. * License: Public */ //Mutual of Enumclaw // //<NAME> and <NAME> - 2019 :) :) // //Main file that controls remediation and notifications of all IAM Group events. //Remediates actions when possible or necessary based on launch type and tagging. Then, notifies the user/security. const AWS = require('aws-sdk'); AWS.config.update({region: process.env.region}); let iam = new AWS.IAM(); const Master = require("./MasterClass").handler; let path = require("./MasterClass").path; let stopper = require("./MasterClass").stopper; let master = new Master(); //remediates a specific action after receiving an event log async function handleEvent(event) { console.log(JSON.stringify(event)); path.n = 'Path: '; //Checks the event log for any previous errors. Stops the function if there is an error. if (master.errorInLog(event)) { path.n += 'Error in Log'; console.log(path.n); return; } //Checks if the log came from this function, quits the program if it does. if (await master.selfInvoked(event)) { path.n += 'Self Invoked'; console.log(path.n); return; } console.log(`"${event.detail.requestParameters.groupName}" is being inspected----------`); console.log(`Event action is ${event.detail.eventName}---------- `); //Checks to see who is doing the action, if it's one of the two interns. RUN IT! if(master.checkKeyUser(event, "groupName")){ //checks if the log is invalid if (await master.invalid(event)) { try { path.n += '1'; await remediate(event); } catch(e) { if (e.code == 'NoSuchEntity') { console.log(e); path.n += '!!'; console.log("**************NoSuchEntity error caught**************"); console.log(path.n); return e; } } } else { path.n += 'Valid Launch'; } } else { path.n += 'Key Not Found'; } console.log(path.n); } async function remediate(event){ //Sets up required parameters const erp = event.detail.requestParameters; let params = { GroupName: erp.groupName }; let results = master.getResults(event, params); path.n += '='; let id = erp.PolicyArn; if (results.Action == 'CreateGroup' || results.Action == 'DeleteGroup') { id = results.GroupName; } else if (results.Action == 'AttachGroupPolicy' || results.Action == 'DetachGroupPolicy') { id = erp.policyArn; } else { id = erp.policyName; } if (process.env.environment != 'snd' && stopper.id == id) { console.log(`*********Resource has already been remediated manually*********`); stopper.id = ''; return; } //Decides, based on the incoming event, which function to call to perform remediation try { switch(results.Action){ case "PutGroupPolicy": params.PolicyName = erp.policyName; await iam.deleteGroupPolicy(params).promise(); results.PolicyName = erp.policyName; results.Response = "DeleteGroupPolicy"; break; case "AttachGroupPolicy": params.PolicyArn = erp.policyArn; await iam.detachGroupPolicy(params).promise(); results.PolicyArn = erp.policyArn; results.Response = "DetachGroupPolicy"; break; case "DetachGroupPolicy": params.PolicyArn = erp.policyArn; await iam.attachGroupPolicy(params).promise(); results.PolicyArn = erp.policyArn; results.Response = "AttachGroupPolicy"; break; case "DeleteGroupPolicy": results.PolicyName = erp.policyName; results.Response = "Remediation could not be performed"; break; case "CreateGroup": await iam.deleteGroup(params).promise(); results.Response = 'DeleteGroup'; break; case "DeleteGroup": results.Response = 'Remediation could not be performed'; break; }; } catch(e) { if (e.code == 'NoSuchEntity') { stopper.id = id; console.log(e); path.n += '!!'; console.log("**************NoSuchEntity error caught**************"); return e; } } console.log("Remediation completed-----------------"); results.Reason = 'Improper Launch'; if (results.Response == 'Remediation could not be performed') { delete results.Reason; } path.n += '='; await master.notifyUser(event, results); } exports.handler = handleEvent; exports.setFunction = (value, funct) => { iam[value] = funct; } <file_sep>/Policy/RemediatePolicies.js /*! * Copyright 2017-2017 Mutual of Enumclaw. All Rights Reserved. * License: Public */ //Mutual of Enumclaw // //<NAME> and <NAME> - 2019 :) :) // //Main file that controls remediation and notifications of all IAM Policy events. //Remediates actions when possible or necessary based on launch type and tagging. Then, notifies the user/security. const AWS = require('aws-sdk'); AWS.config.update({region: process.env.region}); let iam = new AWS.IAM(); const Master = require("./MasterClass").handler; let path = require("./MasterClass").path; let stopper = require("./MasterClass").stopper; let master = new Master(); //remediates a specific action after receiving an event log async function handleEvent(event) { let resourceName = 'policyArn' console.log(JSON.stringify(event)); path.n = 'Path: '; //Checks the event log for any previous errors. Stops the function if there is an error. if (master.errorInLog(event)) { path.n += 'Error In Log'; console.log(path.n); return; } //Checks if the log came from this function, quits the program if it does. if (await master.selfInvoked(event)) { path.n += 'Error in Log'; console.log('Self Invoked'); return; } if (event.detail.eventName == "CreatePolicy") { console.log(`${event.detail.requestParameters.policyName} is being inspected----------`); } else { console.log(`${event.detail.requestParameters.policyArn} is being inspected----------`); } console.log(`Event action is ${event.detail.eventName}---------- `); //Checks to see who is doing the action, if it's one of the two interns. RUN IT! if(event.detail.eventName == "CreatePolicy"){ resourceName = "policyName"; } if(master.checkKeyUser(event, resourceName)){ //checks if the log is invalid if (await master.invalid(event)) { try { path.n += '1' await remediate(event); } catch(e) { if (e.code == 'NoSuchEntity') { console.log(e); path.n += '!!'; console.log("**************NoSuchEntity error caught**************"); console.log(path.n); return e; } } } else { path.n += '~'; } } else { path.n += 'Key Not Found'; } console.log(path.n); } async function remediate(event){ //Sets up required parameters const erp = event.detail.requestParameters; const ere = event.detail.responseElements; let params = {}; let results = master.getResults(event, {}); path.n += '='; let id = erp.PolicyArn; if (results.Action == 'CreatePolicy') { id = erp.policyName; } if (process.env.environment != 'snd' && stopper.id == id) { console.log(`*********Resource has already been remediated manually*********`); stopper.id = ''; return; } //Decides, based on the incoming event, which function to call to perform remediation try { switch(results.Action){ case "CreatePolicy": params.PolicyArn = ere.policy.arn; await iam.deletePolicy(params).promise(); results.PolicyArn = ere.policy.arn; results.Response = "DeletePolicy"; break; case "DeletePolicy": let arnIndex = erp.policyArn.indexOf("/" ) + 1; results.PolicyName = erp.policyArn.substring(arnIndex); results.Response = "Remediation could not be performed"; break; case "CreatePolicyVersion": params.PolicyArn = erp.policyArn; let versionArray = await iam.listPolicyVersions(params).promise(); console.log(versionArray); let oldVersionNum = versionArray.Versions[0].VersionId; let newVersionNum = versionArray.Versions[1].VersionId; params.VersionId = newVersionNum; await iam.setDefaultPolicyVersion(params).promise(); params.VersionId = oldVersionNum; await iam.deletePolicyVersion(params).promise(); results.PolicyArn = erp.policyArn; results.VersionId = oldVersionNum; results.Response = "DeletePolicyVersion"; break; case "SetDefaultPolicyVersion": //setting the default back to 0 in the list array params.PolicyArn = erp.policyArn; let versionArray2 = await iam.listPolicyVersions(params).promise(); params.VersionId = versionArray2.Versions[0].VersionId; await iam.setDefaultPolicyVersion(params).promise(); results.PolicyArn = erp.policyArn; results["Old Default Version"] = erp.versionId; results["Reset Default Version"] = versionArray2.Versions[0].VersionId; results.Response = "ResetDefaultPolicyVersion"; break; case "DeletePolicyVersion": results.PolicyArn = erp.policyArn; results["Deleted Version"] = erp.versionId; results.Response = "Remediation could not be performed"; break; } } catch(e) { if (e.code == 'NoSuchEntity') { stopper.id = id; console.log(e); path.n += '!!'; console.log("**************NoSuchEntity error caught**************"); return e; } } console.log("Remediation completed-----------------"); results.Reason = 'Improper Launch'; if(results.Response == "Remediation could not be performed") { delete results.Reason; } path.n += '='; await master.notifyUser(event, results); } exports.handler = handleEvent; exports.setFunction = (value, funct) => { iam[value] = funct; }
292e204e7cddcc2e2ce64f64de10b0773a0acbc0
[ "JavaScript", "Markdown" ]
6
JavaScript
mutual-of-enumclaw/guard-rails
d13541e7d444ae7ffc4ff253305a65c4f3cc5734
dae23bf2a6de8a54b9b0d54f953479ee7c138003
refs/heads/main
<repo_name>csjy309450/debug-memo<file_sep>/bug_case/bugcase-memory_access_violation/bugcase-memory_access_violation.cpp // bugcase-memory_access_violation.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> void bugcase_stack_arr_access_violation() { char buf[5] = { 0xf, 0xf, 0xf, 0xf, 0xf }; buf[4] = 0; buf[5] = 0; } void bugcase_stack_pointer_access_violation_0() { char buf[5] = { 0xf, 0xf, 0xf, 0xf, 0xf }; *(buf + 4) = 0; *(buf + 5) = 0; } void bugcase_stack_pointer_access_violation_1() { char buf[5] = { 0xf, 0xf, 0xf, 0xf, 0xf }; //*(buf + 17) = 0; for (int i = 0; i < 17; ++i) { if (i == 16) { *(buf + i) = 0x00; } } } void bugcase_heap_arr_access_violation_0() { int * pbuf = new int[5]; pbuf[4] = 0xf; *(pbuf + 4) = 0xe; pbuf[5] = 0xe; delete pbuf; } void bugcase_heap_arr_access_violation_1_release() { char * pbuf = new char[2]; memset(pbuf, 0, 2); *(pbuf + 2 + 8) = 0xf; *(pbuf - 9) = 0xf; delete pbuf; char* pbuf3 = new char[3]; memset(pbuf3, 0, 3); *(pbuf3 - 8) = 0xf; delete pbuf3; char* pbuf2 = new char[5]; memset(pbuf2, 0, 5); *(pbuf2 + 5 + 7) = 0xf; delete pbuf2; } void bugcase_heap_arr_access_violation_1_debug() { char * pbuf = new char[2]; memset(pbuf, 0, 2); *(pbuf + 2 + 12) = 0xf;//越界访问了有效内存往后12字节之后的内存 *(pbuf - 17) = 0xf;//越界访问了有效内存往前16字节之前的内存 delete pbuf; char* pbuf3 = new char[3]; memset(pbuf3, 0, 3); *(pbuf3 - 16) = 0xf;//越界访问了有效内存往前16字节之内的内存 delete pbuf3; char* pbuf2 = new char[5]; memset(pbuf2, 0, 5); *(pbuf2 + 5 + 11) = 0xf;//越界访问了有效内存往后12字节之前的内存 delete pbuf2; } int _tmain(int argc, _TCHAR* argv[]) { //bugcase_stack_arr_access_violation(); //bugcase_stack_pointer_access_violation_0(); //bugcase_stack_pointer_access_violation_1(); //bugcase_heap_arr_access_violation_0(); bugcase_heap_arr_access_violation_1_release(); return 0; }
3abb7e05b37fb4aae6e656da821570cabd78f2bc
[ "C++" ]
1
C++
csjy309450/debug-memo
b92fac749a06727022813be55e34087c1b2afaed
2f6fb667186d6f5ce5a97a28996926ee0e9dc7b1
refs/heads/master
<file_sep> Build Scalatra docs on [Travis CI](https://travis-ci.org/dozed/travis-test) | Docs | Repo | Branch | URL | Built with | | :---------- | :-------------------------------------------- | :------------- | :------------------------------------------------------------- | :---------------------------------------------- | | Site | https://github.com/scalatra/scalatra-website | `feature/hugo` | https://dozed.github.io/travis-test/ | [Hugo](https://gohugo.io/) | | API v2.5.x | https://github.com/scalatra/scalatra | `2.5.x` | https://dozed.github.io/travis-test/apidocs/2.5/org/scalatra/ | [sbt-unidoc](https://github.com/sbt/sbt-unidoc) | | API v2.4.x | https://github.com/scalatra/scalatra | `2.5.x` | https://dozed.github.io/travis-test/apidocs/2.5/org/scalatra/ | [sbt-unidoc](https://github.com/sbt/sbt-unidoc) | TODO - trigger build for push to branch `2.4.x` on repo `scalatra` - trigger build for push to branch `2.5.x` on repo `scalatra` - trigger build for push to branch `master` on repo `scalatra-website` <file_sep>#!/bin/bash set -ev # Check dependencies # rsync -v echo "Config" # Get the deploy key by using Travis's stored variables to decrypt deploy_key.enc # https://gist.github.com/domenic/ec8b0fc8ab45f39403dd ENCRYPTED_KEY_VAR="encrypted_${ENCRYPTION_LABEL}_key" ENCRYPTED_IV_VAR="encrypted_${ENCRYPTION_LABEL}_iv" ENCRYPTED_KEY=${!ENCRYPTED_KEY_VAR} ENCRYPTED_IV=${!ENCRYPTED_IV_VAR} openssl aes-256-cbc -K $ENCRYPTED_KEY -iv $ENCRYPTED_IV -in deploy_key.enc -out deploy_key -d chmod 600 deploy_key eval `ssh-agent -s` ssh-add deploy_key git config --global user.name "<NAME>" git config --global user.email "<EMAIL>" git clone <EMAIL>:dozed/travis-test.git ls -al # total 5424 # drwxrwxr-x 6 travis travis 4096 Mar 26 11:57 . # drwxrwxr-x 3 travis travis 4096 Mar 26 11:57 .. # -rw------- 1 travis travis 1675 Mar 26 11:57 deploy_key # -rw-rw-r-- 1 travis travis 1680 Mar 26 11:57 deploy_key.enc # drwxrwxr-x 8 travis travis 4096 Mar 26 11:57 .git # -rwxrwxr-x 1 travis travis 1899 Mar 26 11:57 hello.sh # -rw-rw-r-- 1 travis travis 5511722 Feb 27 12:53 hugo_0.19-64bit.deb # drwxrwxr-x 25 travis travis 4096 Mar 26 11:57 scalatra # drwxrwxr-x 11 travis travis 4096 Mar 26 11:57 scalatra-website # drwxrwxr-x 3 travis travis 4096 Mar 26 11:57 travis-test # -rw-rw-r-- 1 travis travis 435 Mar 26 11:57 .travis.yml # pwd # /home/travis/build/dozed/travis-test echo "Build" # Final site is in travis-test/gh-pages cd travis-test git checkout gh-pages # always build full site rm -rf * cd .. # Build scalatra site cd scalatra-website git checkout origin/feature/hugo ls -al # TODO remove hugo -b https://takezoe.github.io/scalatra-website/ -d gh-pages || true ls -al ls -al gh-pages rsync -av gh-pages/* ../travis-test cd .. # Build scalatra apidocs v2.5.x cd scalatra git checkout origin/2.5.x sbt unidoc mkdir -p ../travis-test/apidocs/2.5 rsync -av target/scala-2.12/unidoc/* ../travis-test/apidocs/2.5 cd .. # Build scalatra apidocs v2.4.x cd scalatra git checkout origin/2.4.x sbt unidoc mkdir -p ../travis-test/apidocs/2.4 rsync -av target/scala-2.12/unidoc/* ../travis-test/apidocs/2.4 cd .. # Commit and push changes cd travis-test ls -al ls -al apidocs git rm --cached -r . git add --all . git commit -m "Built gh-pages" git push origin gh-pages echo "Done"
464146c4628e1b092c7f33b95d598aa6f2de3cea
[ "Markdown", "Shell" ]
2
Markdown
dozed/travis-test
d6f065ee8ff8b435b4a64186af2feca66a82b4ff
6885618e7532e6db6d9ac4ab041b736b62e2b209
refs/heads/master
<file_sep># If not running interactively, don't do anything [[ $- != *i* ]] && return # Stop Ctl+S stty -ixon [ -r /usr/share/bash-completion/bash_completion ] && . /usr/share/bash-completion/bash_completion PKGFILE_PROMPT_INSTALL_MISSING=y source /usr/share/doc/pkgfile/command-not-found.bash source /usr/share/git/completion/git-prompt.sh #source /home/owg1/.pythonvenv/bin/activate WHITE="\[\e[1;37m\]" BLUE="\[\e[1;34m\]" RED="\[\e[1;31m\]" PS1="$WHITE\W\$(__git_ps1 ' (%s)') $BLUEλ $WHITE" PS2='> ' PS3='> ' PS4='+ ' prompt_cmd () { LAST_STATUS=$? history -a; history -c; history -r; } export PROMPT_COMMAND=prompt_cmd alias pins="yay -Slq | fzf -m --preview 'cat <(yay -Si {1}) <(yay -Fl {1} | awk \"{print \$2}\")' | xargs -ro yay -S" alias spr="curl -F 'sprunge=<-' http://sprunge.us | xclip" alias vi=nvim alias pamcan="pacman" alias paste="xsel --clipboard | spr" alias ls="ls -lah --color --group-directories-first" alias entr="find . -not -path './node_modules/*' -not -name '*.swp' | entr sh -c" alias where="bfs ./ -exclude -name Music/ -name" alias rg="rg -p" alias less="less -R" alias orphans="pacman -Qdt" alias cleanorphans="pacman -Rns $(pacman -Qtdq)" alias explicit="pacman -Qet" alias mirrors="sudo pacman-mirrors --fasttrack && sudo pacman -Syy" alias json="python -m json.tool" alias build="npm --silent run build" alias test="npm --silent run test" alias start="npm --silent run start" alias nuke="rm -rf build node_modules/ && npm i && npm run build" alias psql="pgcli" alias diff="git difftool -- ':!package-lock.json'" alias show="git showtool" alias stat="git status" alias add="git add" alias commit="git commit -v" alias push='git push -u origin $(git rev-parse --abbrev-ref HEAD)' alias check="git checkout" alias stash="git stash -u" alias pop="git stash pop" alias pull="git pull" alias clone="git clone" alias merge="git merge" alias cherry="git cherry-pick" alias last="git difftool HEAD^ HEAD" alias fetch="git fetch" alias revert="git revert" alias bisect="git bisect" alias reflog="git reflog" alias apply="git apply" alias reset="git reset" alias rebase="git rebase -i master" alias clean="git clean -f" alias log="fzf_log" alias squash="git reset --soft HEAD~2 && git commit" alias theirs="git merge --strategy-option theirs" alias removelocal="git reset --hard @{u}" alias amend="git commit --amend -C @" export EDITOR=nvim export TERM=xterm-256color export PYTHON=python3.9.1 export PATH=~/.npm-global/bin:/home/owg1/.gem/ruby/2.5.0/bin:~/.poetry/bin:$PATH export DOCKER_BUILDKIT=1 export COMPOSE_DOCKER_CLI_BUILD=1 export HISTCONTROL=ignoredups:erasedups export HISTSIZE=-1 export HISTFILESIZE=-1 shopt -s histappend [ -f ~/.fzf.bash ] && source ~/.fzf.bash export FZF_DEFAULT_COMMAND='rg --files --no-ignore --hidden --follow -g "!{.git,output,node_modules,*.swp,dist,*.coffee}/*" 2> /dev/null' export FZF_ALT_C_COMMAND='bfs -type d -nohidden -exclude -name "Music" -exclude -name "Drive"' export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND" export FZF_DEFAULT_OPTS='--bind J:down,K:up --reverse --ansi --multi --preview "bat --style=numbers --color=always --line-range :500 {}"' bind -x '"\C-p": fvim' bind -m vi-insert '"\C-x\C-e": edit-and-execute-command' sf() { if [ "$#" -lt 1 ]; then echo "Supply string to search for!"; return 1; fi printf -v search "%q" "$*" include="tsx,vim,ts,yml,yaml,js,json,php,md,styl,pug,jade,html,config,py,cpp,c,go,hs,rb,conf,fa,lst,graphql,tf,proto" exclude="output,.config,.git,node_modules,vendor,build/,yarn.lock,*.sty,*.bst,*.coffee,dist" rg_command='rg --column --line-number --no-heading --fixed-strings --ignore-case --no-ignore --hidden --follow --color "always" -g "*.{'$include'}" -g "!{'$exclude'}/*"' files=`eval $rg_command $search | fzf --ansi --multi --reverse | awk -F ':' '{print $1":"$2":"$3}'` [[ -n "$files" ]] && ${EDITOR:-nvim} $files } sfu() { if [ "$#" -lt 1 ]; then echo "Supply string to search for!"; return 1; fi printf -v search "%q" "$*" include="ts,yml,yaml,js,json,php,md,styl,pug,jade,html,config,py,cpp,c,go,hs,rb,conf,fa,lst,tf" exclude="output,.config,.git,node_modules,vendor,build,yarn.lock,*.sty,*.bst,*.coffee,dist" rg_command='rg -m1 --column --line-number --no-heading --fixed-strings --ignore-case --no-ignore --hidden --follow --color "always" -g "*.{'$include'}" -g "!{'$exclude'}/*"' files=`eval $rg_command $search | fzf --ansi --multi --reverse | awk -F ':' '{print $1":"$2":"$3}'` [[ -n "$files" ]] && ${EDITOR:-nvim} $files } fc() { hash=$(git log --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr" "$@" | fzf | awk '{print $1}') git checkout $hash } gc() { hash=$(git log --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr" "$@" | fzf | awk '{print $1}') gopen $hash } fzf_log() { hash=$(git log --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr" "$@" | fzf | awk '{print $1}') echo $hash | xclip git showtool $hash } tm() { [[ -n "$TMUX" ]] && change="switch-client" || change="attach-session" if [ $1 ]; then tmux $change -t "$1" 2>/dev/null || (tmux new-session -d -s $1 && tmux $change -t "$1"); return fi session=$(tmux list-sessions -F "#{session_name}" 2>/dev/null | fzf --exit-0) && tmux $change -t "$session" || echo "No sessions found." } vee() { nvim $(npm run build | grep error | awk -F " " '{print $1}' | sed s/\(/:/g | sed s/\,/:/g | sed s/\).*//) } branch() { local branches branch branches=$(git for-each-ref --count=30 --sort=-committerdate refs/heads/ --format="%(refname:short)") && branch=$(echo "$branches" | fzf-tmux -d $(( 2 + $(wc -l <<< "$branches") )) +m) && git checkout $(echo "$branch" | sed "s/.* //" | sed "s#remotes/[^/]*/##") } fvim() { local IFS=$'\n' local files=($(fzf-tmux --query="$1" --multi --select-1 --exit-0)) [[ -n "$files" ]] && ${EDITOR:-nvim} "${files[@]}" } c() { local cols sep google_history open cols=$(( COLUMNS / 3 )) sep='{::}' google_history="$HOME/.config/BraveSoftware/Brave-Browser/Default/History" open=xdg-open cp -f "$google_history" /tmp/h sqlite3 -separator $sep /tmp/h \ "select substr(title, 1, $cols), url from urls order by last_visit_time desc" | awk -F $sep '{printf "%-'$cols's \x1b[36m%s\x1b[m\n", $1, $2}' | fzf --ansi --multi | sed 's#.*\(https*://\)#\1#' | xargs $open > /dev/null 2> /dev/null } gopen() { project=$(git config --local remote.origin.url | sed s/git@github.com\:// | sed s/\.git//) url="http://github.com/$project/commit/$1" xdg-open $url } #source /usr/share/nvm/init-nvm.sh <file_sep>This is for my Manjaro systems. Install manjaro with the architect, and use cinammon as the DE, and ensure to have yay installed. This gives you a nice platform to bootstrap the rest of the setup from. All of the files except for the vim specific stuff (lucius, coc, vimspector) needs to just be moved to the home directory and prepended with a `.` so `xmonad/ -> ~/.xmonad/`, `bashrc -> .bashrc`. The only exception is the ssh-agent.service file which has commented instructions in. Vim will auto install fzf and rg and everything else. It takes two launches to get it all mind. Packages used: ``` bfs-git brave copyq docker-compose gvim htop icdiff libinput-gestures nitrogen openssh pamac-gtk pass pass-clip pkgfile rofi scrot trayer ttf-anonymous-pro wifi-menu xf86-input-synaptics xkb-switch xmobar xmonad xmonad-contrib yay ```
d4331211e44547c78ff442d2f5bd05c8e9005194
[ "Markdown", "Shell" ]
2
Shell
bag-man/dotfiles
69901377525da4c9a467be2b53c00cce384674fc
ae5c4acda0656c3888c937868b71914e7657deef
refs/heads/master
<file_sep>package com.sperekrestova.visitCount.controllers; import lombok.AllArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; /** * Created by Svetlana * Date: 02.01.2021 */ @Controller @AllArgsConstructor public class MainController { @GetMapping("/") public String home(Model model) { return "home"; } @GetMapping("/timetable") public String timetable(Model model) { return "timetable"; } @GetMapping("/marks") public String marks(Model model) { return "marks"; } @GetMapping("/admin") public String admin(Model model) { return "admin"; } @GetMapping("/login") public String login(Model model, String error, String logout) { if (error != null) model.addAttribute("errorMsg", "Your username and password are invalid."); if (logout != null) model.addAttribute("msg", "You have been logged out successfully."); return "login"; } } <file_sep>package com.sperekrestova.visitCount.configuration; import com.sperekrestova.visitCount.model.User; import com.sperekrestova.visitCount.repository.RoleRepository; import com.sperekrestova.visitCount.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; /** * Created by Svetlana * Date: 06.01.2021 */ public class CustomUserDetailsService implements UserDetailsService { @Autowired UserRepository userRepository; @Autowired RoleRepository roleRepository; @Autowired private UserRepository userRepo; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepo.findByEmail(username); if (user == null) { throw new UsernameNotFoundException("User not found"); } return user; } }<file_sep>package com.sperekrestova.visitCount.repository; import com.sperekrestova.visitCount.model.Student; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by Svetlana * Date: 09.01.2021 */ public interface StudentRepository extends JpaRepository <Student, Long> { } <file_sep>package com.sperekrestova.visitCount.controllers; import com.sperekrestova.visitCount.model.Role; import com.sperekrestova.visitCount.model.User; import com.sperekrestova.visitCount.repository.UserRepository; import lombok.AllArgsConstructor; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.util.Collections; /** * Created by Svetlana * Date: 09.01.2021 */ @Controller @AllArgsConstructor @RequestMapping("/register") public class RegisterController { private final UserRepository userRepo; @GetMapping() public String showRegistrationForm(Model model) { model.addAttribute("user", new User()); return "register/signup_form"; } @PostMapping() public String processRegister(User user) { BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String encodedPassword = passwordEncoder.encode(user.getPassword()); user.setPassword(encodedPassword); user.setRoles(Collections.singleton(new Role(1L, "ROLE_USER"))); userRepo.save(user); return "register/register_success"; } } <file_sep>package com.sperekrestova.visitCount.controllers; import com.sperekrestova.visitCount.model.User; import com.sperekrestova.visitCount.repository.GroupRepository; import lombok.AllArgsConstructor; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; /** * Created by Svetlana * Date: 16.01.2021 */ @Controller @RequestMapping("/groups") @AllArgsConstructor public class GroupController { private final GroupRepository groupRepository; @GetMapping() public String groups(@AuthenticationPrincipal User user, Model model) { model.addAttribute("lectureGroups", user.getLectureGroups()); return "groups/groups"; } @GetMapping("/{id}") public String getExactGroup(@PathVariable("id") int id, Model model) { model.addAttribute("group", groupRepository.findById((long) id)); return "groups/show-group"; } } <file_sep>spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/visit_count_db?serverTimezone=Europe/Moscow spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.jpa.properties.hibernate.format_sql=true
5bdabd66066e8fcf042fb58dae1098c7a2d61726
[ "Java", "INI" ]
6
Java
SPerekrestova/VisitCountPro
d4fc173ccd464e366b9249e8ec33b659263a4f16
48f63691610ee64fcb13f54c0f8ebfcebadf74de
refs/heads/master
<repo_name>shossa3/DSPExamples<file_sep>/Source/Assets/PlotComponent.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "PlotComponent.h" #include "StringFunctions.h" //============================================================================== /* This structure gives a few functions interesting for visualization of data. */ struct PlotComponentHelpers { static const double getPixelXPositionForValue (double valueX, int width, double minimum, double maximum) { return 0.5 + (width - 1.0) * (valueX - minimum) / (maximum - minimum); } static const double getPixelXPositionForValueLog (double valueX, int width, double minimum, double maximum) { return 0.5 + (width - 1.0) * (std::log10 (valueX) - std::log10 (minimum)) / (std::log10 (maximum) - std::log10 (minimum)); } static const double getPixelYPositionForValue (double valueY, int height, double minimum, double maximum) { return 0.5 + (height - 1.0) * (1.0 - (valueY - minimum) / (maximum - minimum)); } static const double getIntegerPixelXPositionForValue (double valueX, int width, double minimum, double maximum) { return roundToInt (getPixelXPositionForValue (valueX, width, minimum, maximum) - 0.5) + 0.5; } static const double getIntegerPixelXPositionForValueLog (double valueX, int width, double minimum, double maximum) { return roundToInt (getPixelXPositionForValueLog (valueX, width, minimum, maximum) - 0.5) + 0.5; } static const double getIntegerPixelYPositionForValue (double valueY, int height, double minimum, double maximum) { return roundToInt (getPixelYPositionForValue (valueY, height, minimum, maximum) - 0.5) + 0.5; } }; //============================================================================== PlotComponent::PlotComponent() { } PlotComponent::~PlotComponent() { } void PlotComponent::resized() { } //============================================================================== void PlotComponent::setInformation (const Information &newInfo) { jassert (newInfo.gridXSize >= 0); jassert (newInfo.gridYSize >= 0); jassert (newInfo.minimumXValue < newInfo.maximumXValue); jassert (newInfo.minimumYValue < newInfo.maximumYValue); jassert (!(newInfo.isXAxisLogarithmic && newInfo.minimumXValue == 0)); const ScopedLock myScopedLock (processLock); information = newInfo; triggerAsyncUpdate(); } const PlotComponent::Information PlotComponent::getInformation() const { const ScopedLock myScopedLock (processLock); return information; } void PlotComponent::setColourIDs (const PlotComponent::ColourIDs &newInfo) { const ScopedLock myScopedLock (processLock); colourIDs = newInfo; triggerAsyncUpdate(); } const PlotComponent::ColourIDs PlotComponent::getColourIDs() const { const ScopedLock myScopedLock (processLock); return colourIDs; } void PlotComponent::setPlotLayout (const PlotComponent::PlotLayout &newInfo) { jassert (newInfo.marginX >= 0.f); jassert (newInfo.marginRight >= 0.f); jassert (newInfo.marginY >= 0.f); jassert (newInfo.marginBottom >= 0.f); jassert (newInfo.markerSize >= 0.f); jassert (newInfo.titleFontSize > 0.f); jassert (newInfo.titleSize >= 0.f); jassert (newInfo.titleNoSize >= 0.f); jassert (newInfo.labelFontSize > 0.f); jassert (newInfo.labelXSize >= 0.f); jassert (newInfo.labelYSize >= 0.f); jassert (newInfo.valuesFontSize > 0.f); jassert (newInfo.valuesXSize >= 0.f); jassert (newInfo.valuesYSize >= 0.f); jassert (newInfo.valuesLength >= 0.f); jassert (newInfo.valuesYMargin >= 0.f); const ScopedLock myScopedLock (processLock); plotLayout = newInfo; triggerAsyncUpdate(); } const PlotComponent::PlotLayout PlotComponent::getPlotLayout() const { const ScopedLock myScopedLock (processLock); return plotLayout; } void PlotComponent::pushData (const AudioBuffer<float> &dataXY, int numPoints, int numEntries) { jassert (numPoints > 0); jassert (numEntries >= 1); jassert (dataXY.getNumSamples() >= numPoints); jassert (dataXY.getNumChannels() >= numEntries + 1); const ScopedLock myScopedLock (dataLock); dataStructure.dataX.clear(); dataStructure.dataX.addArray (dataXY.getReadPointer (0), numPoints); dataStructure.dataY.clear(); for (auto i = 0; i < numEntries; i++) dataStructure.dataY.add (Array<float> (dataXY.getReadPointer (1 + i), numPoints)); dataStructure.numPoints.store (numPoints); dataStructure.numEntries.store (numEntries); } //============================================================================== void PlotComponent::handleAsyncUpdate() { repaint(); } void PlotComponent::paint (Graphics& g) { // ------------------------------------------------------------------------------------------------------------- auto currentInformation = getInformation(); auto currentColourIDs = getColourIDs(); auto currentLayout = getPlotLayout(); auto canDisplayData = true; auto canDisplayGrid = true; // ------------------------------------------------------------------------------------------------------------- if (currentInformation.isXAxisLogarithmic && currentInformation.minimumXValue <= 0) { // Logarithmic means minimum should be higher than zero ! canDisplayData = false; canDisplayGrid = false; } else if (currentInformation.minimumXValue == currentInformation.maximumXValue) { canDisplayData = false; canDisplayGrid = false; } else if (currentInformation.minimumYValue == currentInformation.maximumYValue) { canDisplayData = false; canDisplayGrid = false; } if (dataStructure.numPoints == 0) canDisplayData = false; // ------------------------------------------------------------------------------------------------------------- Rectangle<int> rect = getLocalBounds(); rect.removeFromLeft (roundToInt (currentLayout.marginX)); rect.removeFromRight (roundToInt (currentLayout.marginRight)); rect.removeFromTop (roundToInt (currentLayout.marginY)); rect.removeFromBottom (roundToInt (currentLayout.marginBottom)); // Title if (information.strTitle.isNotEmpty()) { Rectangle<int> rectTitle = rect.removeFromTop (roundToInt (currentLayout.titleSize)); if (information.strLabelY.isNotEmpty()) rectTitle.removeFromLeft (roundToInt (currentLayout.labelYSize)); if (information.displayGridYValues) rectTitle.removeFromLeft (roundToInt (currentLayout.valuesYSize)); paintTitle (g, rectTitle); } else rect.removeFromTop (roundToInt (currentLayout.titleNoSize)); // Label X if (information.strLabelX.isNotEmpty()) { Rectangle<int> rectLabel = rect.removeFromBottom (roundToInt (currentLayout.labelXSize)); if (information.strLabelY.isNotEmpty()) rectLabel.removeFromLeft (roundToInt (currentLayout.labelYSize)); if (information.displayGridYValues) rectLabel.removeFromLeft (roundToInt (currentLayout.valuesYSize)); paintLabelsX (g, rectLabel); } // Values X if (information.displayGridXValues) { Rectangle<int> rectValues = rect.removeFromBottom (roundToInt (currentLayout.valuesXSize)); if (information.strLabelY.isNotEmpty()) rectValues.removeFromLeft (roundToInt (currentLayout.labelYSize)); if (information.displayGridYValues) rectValues.removeFromLeft (roundToInt (currentLayout.valuesYSize)); if (canDisplayGrid) { if (information.isXAxisLogarithmic) paintValuesXLog (g, rectValues); else paintValuesX (g, rectValues); } } // Label Y if (information.strLabelY.isNotEmpty()) { Rectangle<int> rectLabel = rect.removeFromLeft (roundToInt (currentLayout.labelYSize)); paintLabelsY (g, rectLabel); } // Label Y if (information.displayGridYValues) { Rectangle<int> rectValues = rect.removeFromLeft (roundToInt (currentLayout.valuesYSize)); if (canDisplayGrid) paintValuesY (g, rectValues); } // Background g.setColour (currentColourIDs.backgroundColour); g.fillRect (rect); // Grid X if (information.displayGrid && canDisplayGrid) { if (information.isXAxisLogarithmic) paintGridXLog (g, rect); else if (information.gridXSize > 0) paintGridX (g, rect); } // Grid Y if (information.gridYSize > 0 && information.displayGrid && canDisplayGrid) paintGridY (g, rect); // Data if (canDisplayData) paintData (g, rect); // Outline g.setColour (currentColourIDs.outlineColour); g.drawRect (rect); } //============================================================================== void PlotComponent::paintTitle (Graphics& g, Rectangle<int> rect) { auto currentInformation = getInformation(); auto currentColourIDs = getColourIDs(); auto currentLayout = getPlotLayout(); g.setColour (currentColourIDs.textColour); g.setFont (currentLayout.fontPlotComponent.withHeight (currentLayout.titleFontSize)); g.drawFittedText (currentInformation.strTitle, rect, Justification::centred, 2); } void PlotComponent::paintValuesX (Graphics& g, Rectangle<int> rect) { auto currentInformation = getInformation(); auto currentColourIDs = getColourIDs(); auto currentLayout = getPlotLayout(); g.saveState(); g.addTransform (AffineTransform::translation (rect.getX() + 0.0f, rect.getY() + 0.0f)); rect.translate (-rect.getX(), -rect.getY()); g.setColour (currentColourIDs.textColour); g.setFont (currentLayout.fontPlotComponent.withHeight (currentLayout.valuesFontSize)); double valueX; auto reference = currentInformation.maximumXValue - currentInformation.minimumXValue; if (currentInformation.gridXSize > 0 && currentInformation.displayGrid) { if (currentInformation.gridXMustStartAtZero && currentInformation.minimumXValue <= 0 && currentInformation.maximumXValue >= 0) { valueX = 0.0; while (valueX <= currentInformation.maximumXValue) { auto pixelX = roundToInt (PlotComponentHelpers::getPixelXPositionForValue (valueX, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue)); Rectangle<int> newRect = Rectangle<int> (pixelX - roundToInt (currentLayout.valuesLength * 0.5), 0, roundToInt (currentLayout.valuesLength), rect.getHeight()); String strValue = StringFunctions::getIdealRepresentationForNumber (valueX, reference); g.drawFittedText (strValue, newRect, Justification::centred, 1); valueX += currentInformation.gridXSize; } valueX = 0.0 - currentInformation.gridXSize; while (valueX >= currentInformation.minimumXValue - 0.02 * (currentInformation.maximumXValue - currentInformation.minimumXValue)) { auto pixelX = roundToInt (PlotComponentHelpers::getPixelXPositionForValue (valueX, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue)); Rectangle<int> newRect = Rectangle<int> (pixelX - roundToInt (currentLayout.valuesLength * 0.5), 0, roundToInt (currentLayout.valuesLength), rect.getHeight()); String strValue = StringFunctions::getIdealRepresentationForNumber (valueX, reference); g.drawFittedText (strValue, newRect, Justification::centred, 1); valueX -= currentInformation.gridXSize; } } else { valueX = currentInformation.minimumXValue; while (valueX <= currentInformation.maximumXValue) { auto pixelX = roundToInt (PlotComponentHelpers::getPixelXPositionForValue (valueX, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue)); Rectangle<int> newRect = Rectangle<int> (pixelX - roundToInt (currentLayout.valuesLength * 0.5f), 0, roundToInt (currentLayout.valuesLength), rect.getHeight()); String strValue = StringFunctions::getIdealRepresentationForNumber (valueX, reference); g.drawFittedText (strValue, newRect, Justification::centred, 1); valueX += currentInformation.gridXSize; } } } else { valueX = currentInformation.minimumXValue; while (valueX <= currentInformation.maximumXValue) { auto pixelX = roundToInt (PlotComponentHelpers::getPixelXPositionForValue (valueX, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue)); Rectangle<int> newRect = Rectangle<int> (pixelX - roundToInt (currentLayout.valuesLength * 0.5f), 0, roundToInt (currentLayout.valuesLength), rect.getHeight()); String strValue = StringFunctions::getIdealRepresentationForNumber (valueX, reference); g.drawFittedText (strValue, newRect, Justification::centred, 1); valueX += currentInformation.maximumXValue - currentInformation.minimumXValue; } } g.restoreState(); } void PlotComponent::paintValuesXLog (Graphics& g, Rectangle<int> rect) { auto currentInformation = getInformation(); auto currentColourIDs = getColourIDs(); auto currentLayout = getPlotLayout(); g.saveState(); g.addTransform (AffineTransform::translation (rect.getX() + 0.f, rect.getY() + 0.f)); rect.translate (-rect.getX(), -rect.getY()); g.setColour (currentColourIDs.textColour); g.setFont (currentLayout.fontPlotComponent.withHeight (currentLayout.valuesFontSize)); double valueX; double reference = currentInformation.maximumXValue - currentInformation.minimumXValue; if (currentInformation.displayGrid) { valueX = std::pow (10.0, std::ceil (std::log10 (currentInformation.minimumXValue))); while (valueX <= currentInformation.maximumXValue) { auto pixelX = roundToInt (PlotComponentHelpers::getPixelXPositionForValueLog (valueX, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue)); Rectangle<int> newRect = Rectangle<int> (pixelX - roundToInt (currentLayout.valuesLength * 0.5f), 0, roundToInt (currentLayout.valuesLength), rect.getHeight()); String strValue = StringFunctions::getIdealRepresentationForNumber (valueX, reference); g.drawFittedText (strValue, newRect, Justification::centred, 1); valueX *= 10.0; } } else { valueX = currentInformation.minimumXValue; while (valueX <= currentInformation.maximumXValue) { auto pixelX = roundToInt (PlotComponentHelpers::getPixelXPositionForValue (valueX, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue)); Rectangle<int> newRect = Rectangle<int> (pixelX - roundToInt (currentLayout.valuesLength * 0.5f), 0, roundToInt (currentLayout.valuesLength), rect.getHeight()); String strValue = StringFunctions::getIdealRepresentationForNumber (valueX, reference); g.drawFittedText (strValue, newRect, Justification::centred, 1); valueX += currentInformation.maximumXValue - currentInformation.minimumXValue; } } g.restoreState(); } void PlotComponent::paintValuesY (Graphics& g, Rectangle<int> rect) { auto currentInformation = getInformation(); auto currentColourIDs = getColourIDs(); auto currentLayout = getPlotLayout(); g.setColour (currentColourIDs.textColour); g.setFont (currentLayout.fontPlotComponent.withHeight (currentLayout.valuesFontSize)); double valueY; auto reference = currentInformation.maximumYValue - currentInformation.minimumYValue; g.saveState(); if (currentInformation.displayGridYValuesReverted) { g.setOrigin (rect.getRight(), rect.getY()); rect.translate (-rect.getX(), -rect.getY()); g.addTransform (AffineTransform::rotation (-float_Pi * 0.5f)); Rectangle<int> newRect (rect.getY(), rect.getX(), rect.getHeight(), rect.getWidth()); newRect.translate (-newRect.getWidth(), -newRect.getHeight()); g.setOrigin (newRect.getX(), newRect.getY()); if (currentInformation.gridYSize > 0 && currentInformation.displayGrid) { if (currentInformation.gridYMustStartAtZero && currentInformation.minimumYValue <= 0 && currentInformation.maximumYValue >= 0) { valueY = 0.f; while (valueY <= currentInformation.maximumYValue) { auto pixelY = roundToInt (PlotComponentHelpers::getPixelYPositionForValue (valueY, newRect.getWidth(), currentInformation.minimumYValue, currentInformation.maximumYValue)); pixelY = newRect.getWidth() - pixelY; Rectangle<int> newRect2 = Rectangle<int> (pixelY - roundToInt (currentLayout.valuesLength * 0.5f), 0, roundToInt (currentLayout.valuesLength), newRect.getHeight()); String strValue = StringFunctions::getIdealRepresentationForNumber (valueY, reference); g.drawFittedText (strValue, newRect2, Justification::centred, 1); valueY += currentInformation.gridYSize; } valueY = 0.f - currentInformation.gridYSize; while (valueY >= currentInformation.minimumYValue) { auto pixelY = roundToInt (PlotComponentHelpers::getPixelYPositionForValue (valueY, newRect.getWidth(), currentInformation.minimumYValue, currentInformation.maximumYValue)); pixelY = newRect.getWidth() - pixelY; Rectangle<int> newRect2 = Rectangle<int> (pixelY - roundToInt (currentLayout.valuesLength * 0.5f), 0, roundToInt (currentLayout.valuesLength), newRect.getHeight()); String strValue = StringFunctions::getIdealRepresentationForNumber (valueY, reference); g.drawFittedText (strValue, newRect2, Justification::centred, 1); valueY -= currentInformation.gridYSize; } } else { valueY = currentInformation.minimumYValue; while (valueY <= currentInformation.maximumYValue) { auto pixelY = roundToInt (PlotComponentHelpers::getPixelYPositionForValue (valueY, newRect.getWidth(), currentInformation.minimumYValue, currentInformation.maximumYValue)); pixelY = newRect.getWidth() - pixelY; Rectangle<int> newRect2 = Rectangle<int> (pixelY - roundToInt (currentLayout.valuesLength * 0.5f), 0, roundToInt (currentLayout.valuesLength), newRect.getHeight()); String strValue = StringFunctions::getIdealRepresentationForNumber (valueY, reference); g.drawFittedText (strValue, newRect2, Justification::centred, 1); valueY += currentInformation.gridYSize; } } } else { valueY = currentInformation.minimumYValue; while (valueY <= currentInformation.maximumYValue) { auto pixelY = roundToInt (PlotComponentHelpers::getPixelYPositionForValue (valueY, newRect.getWidth(), currentInformation.minimumYValue, currentInformation.maximumYValue)); pixelY = newRect.getWidth() - pixelY; Rectangle<int> newRect2 = Rectangle<int> (pixelY - roundToInt (currentLayout.valuesLength * 0.5f), 0, roundToInt (currentLayout.valuesLength), newRect.getHeight()); String strValue = StringFunctions::getIdealRepresentationForNumber (valueY, reference); g.drawFittedText (strValue, newRect2, Justification::centred, 1); valueY += currentInformation.maximumYValue - currentInformation.minimumYValue; } } } else { g.addTransform (AffineTransform::translation (rect.getX() + 0.f, rect.getY() + 0.f)); rect.translate (-rect.getX(), -rect.getY()); if (currentInformation.gridYSize > 0 && currentInformation.displayGrid) { if (currentInformation.gridYMustStartAtZero && currentInformation.minimumYValue <= 0 && currentInformation.maximumYValue >= 0) { valueY = 0.f; while (valueY <= currentInformation.maximumYValue) { auto pixelY = roundToInt (PlotComponentHelpers::getPixelYPositionForValue (valueY, rect.getHeight(), currentInformation.minimumYValue, currentInformation.maximumYValue)); Rectangle<int> newRect = Rectangle<int> (0, pixelY - 12, rect.getWidth(), 24); newRect.removeFromRight (roundToInt (currentLayout.valuesYMargin)); String strValue = StringFunctions::getIdealRepresentationForNumber (valueY, reference); g.drawFittedText (strValue, newRect, Justification::centredRight, 1); valueY += currentInformation.gridYSize; } valueY = 0.f - currentInformation.gridYSize; while (valueY >= currentInformation.minimumYValue) { auto pixelY = roundToInt (PlotComponentHelpers::getPixelYPositionForValue (valueY, rect.getHeight(), currentInformation.minimumYValue, currentInformation.maximumYValue)); Rectangle<int> newRect = Rectangle<int> (0, pixelY - 12, rect.getWidth(), 24); newRect.removeFromRight (roundToInt (currentLayout.valuesYMargin)); String strValue = StringFunctions::getIdealRepresentationForNumber (valueY, reference); g.drawFittedText (strValue, newRect, Justification::centredRight, 1); valueY -= currentInformation.gridYSize; } } else { valueY = currentInformation.minimumYValue; while (valueY <= currentInformation.maximumYValue) { auto pixelY = roundToInt (PlotComponentHelpers::getPixelYPositionForValue (valueY, rect.getHeight(), currentInformation.minimumYValue, currentInformation.maximumYValue)); Rectangle<int> newRect = Rectangle<int> (0, pixelY - 12, rect.getWidth(), 24); newRect.removeFromRight (roundToInt (currentLayout.valuesYMargin)); String strValue = StringFunctions::getIdealRepresentationForNumber (valueY, reference); g.drawFittedText (strValue, newRect, Justification::centredRight, 1); valueY += currentInformation.gridYSize; } } } else { valueY = currentInformation.minimumXValue; while (valueY <= currentInformation.maximumYValue) { auto pixelY = roundToInt (PlotComponentHelpers::getPixelYPositionForValue (valueY, rect.getHeight(), currentInformation.minimumYValue, currentInformation.maximumYValue)); Rectangle<int> newRect = Rectangle<int> (0, pixelY - 12, rect.getWidth(), 24); newRect.removeFromRight (roundToInt (currentLayout.valuesYMargin)); String strValue = StringFunctions::getIdealRepresentationForNumber (valueY, reference); g.drawFittedText (strValue, newRect, Justification::centredRight, 1); valueY += currentInformation.maximumYValue - currentInformation.minimumYValue; } } } g.restoreState(); } void PlotComponent::paintLabelsX (Graphics& g, Rectangle<int> rect) { auto currentInformation = getInformation(); auto currentColourIDs = getColourIDs(); auto currentLayout = getPlotLayout(); g.setColour (currentColourIDs.textColour); g.setFont (currentLayout.fontPlotComponent.withHeight (currentLayout.labelFontSize)); g.drawFittedText (currentInformation.strLabelX, rect, Justification::centred, 2); } void PlotComponent::paintLabelsY (Graphics& g, Rectangle<int> rect) { auto currentInformation = getInformation(); auto currentColourIDs = getColourIDs(); auto currentLayout = getPlotLayout(); g.saveState(); g.setOrigin (rect.getRight(), rect.getY()); rect.translate (-rect.getX(), -rect.getY()); g.addTransform (AffineTransform::rotation (-float_Pi * 0.5f)); Rectangle<int> newRect (rect.getY(), rect.getX(), rect.getHeight(), rect.getWidth()); newRect.translate (-newRect.getWidth(), -newRect.getHeight()); g.setColour (currentColourIDs.textColour); g.setFont (currentLayout.fontPlotComponent.withHeight (currentLayout.labelFontSize)); g.drawFittedText (currentInformation.strLabelY, newRect, Justification::centred, 2); g.restoreState(); } void PlotComponent::paintGridX (Graphics& g, Rectangle<int> rect) { auto currentInformation = getInformation(); auto currentColourIDs = getColourIDs(); auto currentLayout = getPlotLayout(); g.saveState(); g.addTransform (AffineTransform::translation (rect.getX() + 0.f, rect.getY() + 0.f)); rect.translate (-rect.getX(), -rect.getY()); double valueX, pixelX; if (currentInformation.gridXMustStartAtZero && currentInformation.minimumXValue <= 0 && currentInformation.maximumXValue >= 0) { valueX = 0.0; while (valueX <= currentInformation.maximumXValue) { pixelX = PlotComponentHelpers::getIntegerPixelXPositionForValue (valueX, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue); g.setColour (Colours::lightgrey); g.drawLine ((float)pixelX, 0.f, (float)pixelX, rect.getHeight() + 0.f); g.setColour (currentColourIDs.markerColour); g.drawLine ((float)pixelX, 0.f, (float)pixelX, currentLayout.markerSize); g.drawLine ((float)pixelX, rect.getHeight() - currentLayout.markerSize, (float)pixelX, rect.getHeight() + 0.f); valueX += currentInformation.gridXSize; } valueX = 0.0 - currentInformation.gridXSize; while (valueX >= currentInformation.minimumXValue) { pixelX = PlotComponentHelpers::getIntegerPixelXPositionForValue (valueX, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue); g.setColour (Colours::lightgrey); g.drawLine ((float)pixelX, 0.f, (float)pixelX, rect.getHeight() + 0.f); g.setColour (currentColourIDs.markerColour); g.drawLine ((float)pixelX, 0.f, (float)pixelX, currentLayout.markerSize); g.drawLine ((float)pixelX, rect.getHeight() - currentLayout.markerSize, (float)pixelX, rect.getHeight() + 0.f); valueX -= currentInformation.gridXSize; } } else { valueX = currentInformation.minimumXValue; while (valueX <= currentInformation.maximumXValue) { pixelX = PlotComponentHelpers::getIntegerPixelXPositionForValue (valueX, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue); g.setColour (currentColourIDs.gridColour); g.drawLine ((float)pixelX, 0.f, (float)pixelX, rect.getHeight() + 0.f); g.setColour (currentColourIDs.markerColour); g.drawLine ((float)pixelX, 0.f, (float)pixelX, currentLayout.markerSize); g.drawLine ((float)pixelX, rect.getHeight() - currentLayout.markerSize, (float)pixelX, rect.getHeight() + 0.f); valueX += currentInformation.gridXSize; } } g.restoreState(); } void PlotComponent::paintGridXLog (Graphics& g, Rectangle<int> rect) { auto currentInformation = getInformation(); auto currentColourIDs = getColourIDs(); auto currentLayout = getPlotLayout(); g.saveState(); g.addTransform (AffineTransform::translation (rect.getX() + 0.f, rect.getY() + 0.f)); rect.translate (-rect.getX(), -rect.getY()); auto numOctaves = std::log10 (currentInformation.maximumXValue) - std::log10 (currentInformation.minimumXValue); auto valueX = std::pow (10.0, std::floor (std::log10 (currentInformation.minimumXValue))); if (numOctaves <= currentInformation.numOctavesMaxFullGridLog) { while (valueX <= currentInformation.maximumXValue) { for (auto i = 1; i <= 9; i++) { if (valueX * i >= currentInformation.minimumXValue && valueX * i <= currentInformation.maximumXValue) { auto pixelX = PlotComponentHelpers::getIntegerPixelXPositionForValueLog (valueX * i, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue); g.setColour (currentColourIDs.gridColour); g.drawLine ((float)pixelX, 0.f, (float)pixelX, rect.getHeight() + 0.f); g.setColour (currentColourIDs.markerColour); g.drawLine ((float)pixelX, 0.f, (float)pixelX, currentLayout.markerSize); g.drawLine ((float)pixelX, rect.getHeight() - currentLayout.markerSize, (float)pixelX, rect.getHeight() + 0.f); } } valueX *= 10.f; } } else { while (valueX <= currentInformation.maximumXValue) { auto pixelX = PlotComponentHelpers::getIntegerPixelXPositionForValueLog (valueX, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue); g.setColour (currentColourIDs.gridColour); g.drawLine ((float)pixelX, 0.f, (float)pixelX, rect.getHeight() + 0.f); g.setColour (currentColourIDs.markerColour); g.drawLine ((float)pixelX, 0.f, (float)pixelX, currentLayout.markerSize); g.drawLine ((float)pixelX, rect.getHeight() - currentLayout.markerSize, (float)pixelX, rect.getHeight() + 0.f); valueX *= 10.f; } } g.restoreState(); } void PlotComponent::paintGridY (Graphics& g, Rectangle<int> rect) { auto currentInformation = getInformation(); auto currentColourIDs = getColourIDs(); auto currentLayout = getPlotLayout(); g.saveState(); g.addTransform (AffineTransform::translation (rect.getX() + 0.f, rect.getY() + 0.f)); rect.translate (-rect.getX(), -rect.getY()); double valueY, pixelY; if (currentInformation.gridYMustStartAtZero && currentInformation.minimumYValue <= 0 && currentInformation.maximumYValue >= 0) { valueY = 0.0; while (valueY <= currentInformation.maximumYValue) { pixelY = PlotComponentHelpers::getIntegerPixelYPositionForValue (valueY, rect.getHeight(), currentInformation.minimumYValue, currentInformation.maximumYValue); g.setColour (currentColourIDs.gridColour); g.drawLine (0.f, (float)pixelY, rect.getWidth() + 0.f, (float)pixelY); g.setColour (currentColourIDs.markerColour); g.drawLine (0.f, (float)pixelY, currentLayout.markerSize, (float)pixelY); g.drawLine (rect.getWidth() + 0.f, (float)pixelY, rect.getWidth() - currentLayout.markerSize, (float)pixelY); valueY += currentInformation.gridYSize; } valueY = 0.0 - currentInformation.gridYSize; while (valueY >= currentInformation.minimumYValue) { pixelY = PlotComponentHelpers::getIntegerPixelYPositionForValue (valueY, rect.getHeight(), currentInformation.minimumYValue, currentInformation.maximumYValue); g.setColour (currentColourIDs.gridColour); g.drawLine (0.f, (float)pixelY, rect.getWidth() + 0.f, (float)pixelY); g.setColour (currentColourIDs.markerColour); g.drawLine (0.f, (float)pixelY, currentLayout.markerSize, (float)pixelY); g.drawLine (rect.getWidth() + 0.f, (float)pixelY, rect.getWidth() - currentLayout.markerSize, (float)pixelY); valueY -= currentInformation.gridYSize; } } else { valueY = currentInformation.minimumYValue; while (valueY <= currentInformation.maximumYValue) { pixelY = PlotComponentHelpers::getIntegerPixelYPositionForValue (valueY, rect.getHeight(), currentInformation.minimumYValue, currentInformation.maximumYValue); g.setColour (currentColourIDs.gridColour); g.drawLine (0.f, (float)pixelY, rect.getWidth() + 0.f, (float)pixelY); g.setColour (currentColourIDs.markerColour); g.drawLine (0.f, (float)pixelY, currentLayout.markerSize, (float)pixelY); g.drawLine (rect.getWidth() + 0.f, (float)pixelY, rect.getWidth() - currentLayout.markerSize, (float)pixelY); valueY += currentInformation.gridYSize; } } g.restoreState(); } void PlotComponent::paintData (Graphics& g, Rectangle<int> rect) { auto currentInformation = getInformation(); auto currentColourIDs = getColourIDs(); auto currentLayout = getPlotLayout(); g.saveState(); g.excludeClipRegion (Rectangle<int> (0, 0, getWidth(), rect.getY())); g.excludeClipRegion (Rectangle<int> (0, rect.getBottom(), getWidth(), getHeight() - rect.getBottom())); g.excludeClipRegion (Rectangle<int> (0, 0, rect.getX(), getHeight())); g.excludeClipRegion (Rectangle<int> (rect.getRight(), 0, getWidth() - rect.getRight(), getHeight())); g.addTransform (AffineTransform::translation (rect.getX() + 0.f, rect.getY() + 0.f)); rect.translate (-rect.getX(), -rect.getY()); auto numPoints = dataStructure.numPoints.load(); auto numEntries = dataStructure.numEntries.load(); const ScopedLock myScopedLock (dataLock); for (auto n = 0; n < numEntries; n++) { auto indexColour = n % currentColourIDs.dataColours.size(); g.setColour (currentColourIDs.dataColours[indexColour]); Path thePath; bool mustStartNewPath = true; for (auto i = 0; i < numPoints; i++) { auto valueX = dataStructure.dataX[i]; auto valueY = dataStructure.dataY[n][i]; if (isnan (valueY)) { mustStartNewPath = true; } else { if (isinf (valueY)) { if (valueY == -std::numeric_limits<double>::infinity()) valueY = (float) (currentInformation.minimumYValue - 10 * (currentInformation.maximumYValue - currentInformation.minimumYValue)); else valueY = (float) (currentInformation.maximumYValue + 10 * (currentInformation.maximumYValue - currentInformation.minimumYValue)); } double pixelX; if (currentInformation.isXAxisLogarithmic) pixelX = PlotComponentHelpers::getPixelXPositionForValueLog (valueX, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue); else pixelX = PlotComponentHelpers::getPixelXPositionForValue (valueX, rect.getWidth(), currentInformation.minimumXValue, currentInformation.maximumXValue); auto pixelY = PlotComponentHelpers::getPixelYPositionForValue (valueY, rect.getHeight(), currentInformation.minimumYValue, currentInformation.maximumYValue); if (mustStartNewPath) { thePath.startNewSubPath ((float)pixelX, (float)pixelY); mustStartNewPath = false; } else thePath.lineTo ((float)pixelX, (float)pixelY); } } PathStrokeType theStrokeType = PathStrokeType (1.f, PathStrokeType::JointStyle::curved, PathStrokeType::EndCapStyle::rounded); g.strokePath (thePath, theStrokeType); } g.restoreState(); } <file_sep>/Source/Assets/LowFrequencyOscillator.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" class LowFrequencyOscillator { public: // ============================================================================= /** The different types of LFOs allowed in this class. */ enum TypeLFO { lfoSine = 0, lfoTriangle, lfoSawtooth, lfoSquare, lfoNoise }; // ============================================================================= /** Constructor. */ LowFrequencyOscillator(); /** Destructor. */ ~LowFrequencyOscillator(); // ============================================================================= /** Sets the frequency of the LFO. */ void setFrequency (double newFrequency); /** Sets the output volume of the LFO, which is bounded between -1 and +1 when this volume is at 0 dB (the parameter is a linear gain value). */ void setVolume (float newVolume); /** Sets the type of LFO. */ void setType (TypeLFO newType); // ============================================================================= /** Initialization of the process. */ void initProcessing (double newSampleRate); /** Resets the LFO and sets the phase to a given value */ void reset (double initialPhase = 0.0); // ============================================================================= /** Returns next sample. */ const float getNextSample(); // ============================================================================= /** Sets the phase to a given value, for offsetting or synchronizing two LFOs. */ void copyPhase (double newPhase); /** Returns the current phase of the LFO. */ const double getPhase(); private: // ============================================================================= double sampleRate, frequency; int type; // ============================================================================= double factor, phase; Random theRandom; // ============================================================================= LinearSmoothedValue<float> outputVolume; // ============================================================================= JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowFrequencyOscillator) }; <file_sep>/Source/Sessions/Session4/SessionFourDSP.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "SessionFourDSP.h" //============================================================================== BallisticsFilter::BallisticsFilter() { prmAttack.store (1.f); prmRelease.store (100.f); isActive = false; } BallisticsFilter::~BallisticsFilter() { } void BallisticsFilter::setAttackTime (float attackTimeMs) { prmAttack.store (jlimit (0.001f, 10000.f, attackTimeMs)); mustUpdateProcessing = true; } void BallisticsFilter::setReleaseTime (float releaseTimeMs) { prmRelease.store (jlimit (10.f, 500000.f, releaseTimeMs)); mustUpdateProcessing = true; } void BallisticsFilter::initProcessing (double sR) { sampleRate = sR; updateProcessing(); reset(); isActive = true; } void BallisticsFilter::reset (float zeroValue) { yold = zeroValue; } float BallisticsFilter::processSingleSample (float &sample) { if (mustUpdateProcessing) updateProcessing(); auto timeCte = (sample > yold ? cteAT : cteRL); auto result = sample + timeCte * (yold - sample); yold = result; return result; } void BallisticsFilter::updateProcessing() { mustUpdateProcessing = false; auto Ts = 1.f / (float)sampleRate; cteAT = std::exp (-2.f * float_Pi * Ts * 1000.f / prmAttack.load()); cteRL = std::exp (-2.f * float_Pi * Ts * 1000.f / prmRelease.load()); } <file_sep>/Source/Sessions/Session5/SessionFiveDSP.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "SessionFiveDSP.h" //============================================================================== LinearSlewLimiter::LinearSlewLimiter() { reset(); setSlew (44100.0, 10000.0, 10000.0); } LinearSlewLimiter::~LinearSlewLimiter() { } void LinearSlewLimiter::reset (float resetValue) { lastOutput = resetValue; justReset = true; } void LinearSlewLimiter::setSlew (double sampleRate, double slewRiseMaximumSlopeInVpS, double slewFallMaximumSlopeInVpS) { slewRiseMax = (float)(slewRiseMaximumSlopeInVpS / sampleRate); slewFallMax = (float)(slewFallMaximumSlopeInVpS / sampleRate); } float LinearSlewLimiter::getSample (float &input) { if (justReset) { justReset = false; lastOutput = input; } else { // Rise limiting if (input > lastOutput) lastOutput = jmin (input, lastOutput + slewRiseMax); // Fall limiting else lastOutput = jmax (input, lastOutput - slewFallMax); } return lastOutput; } // =================================================================================================== TPTFilter1stOrder::TPTFilter1stOrder() { sampleRate = 44100; type = TypeLowPass; frequency = 200; isActive = false; } TPTFilter1stOrder::~TPTFilter1stOrder() { } void TPTFilter1stOrder::initProcessing (double newSampleRate) { jassert (newSampleRate > 0); sampleRate = newSampleRate; updateProcessing(); reset(); isActive = true; } void TPTFilter1stOrder::setType (TPTFilterType newType) { type.store (newType); mustUpdateProcessing = true; } void TPTFilter1stOrder::setCutoffFrequency (float newFrequency) { jassert (newFrequency > 0); newFrequency = jlimit (10.f, static_cast <float> (sampleRate) * 0.5f, newFrequency); frequency.store (newFrequency); mustUpdateProcessing = true; } void TPTFilter1stOrder::reset (const float s1eq) { s1 = s1eq; } float TPTFilter1stOrder::processSingleSampleRaw (const float &sample) { if (!(isActive)) return 0.f; if (mustUpdateProcessing) updateProcessing(); auto v = g * (sample - s1); auto y = v + s1; s1 = y + v; if (currentType == TypeLowPass) return y; else return sample - y; } void TPTFilter1stOrder::updateProcessing() { mustUpdateProcessing = false; g = std::tan (float_Pi * frequency.load() / (float)sampleRate); g = g / (1 + g); currentType = type.load(); } <file_sep>/Source/MainComponent.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "FileSystem.h" #include "SessionComponents.h" #include "./Assets/AudioThumbnailComponent.h" //============================================================================== /** LookandFeel class of our application */ class MainComponentLookAndFeel : public LookAndFeel_V4 { public: //============================================================================== MainComponentLookAndFeel() { setColour (TextButton::ColourIds::buttonColourId, findColour (TextButton::ColourIds::buttonColourId).brighter (0.2f)); setColour (TextButton::ColourIds::buttonOnColourId, findColour (TextButton::ColourIds::buttonOnColourId).brighter (0.2f)); setColour (ComboBox::ColourIds::backgroundColourId, findColour (ComboBox::ColourIds::backgroundColourId).brighter()); } private: //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainComponentLookAndFeel) }; //============================================================================== /** This component lives inside our window, and this is where you should put all your controls and content. */ class MainComponent : public Component, public ListBoxModel, public AudioSource, public Button::Listener, public ComboBox::Listener { public: //============================================================================== MainComponent(); ~MainComponent(); //============================================================================== void prepareToPlay (int samplesPerBlockExpected, double sampleRate) override; void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override; void releaseResources() override; //============================================================================== void paint (Graphics& g) override; void resized() override; //============================================================================== int getNumRows() override; void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected) override; void selectedRowsChanged (int lastRowSelected) override; void buttonClicked (Button *button) override; void comboBoxChanged (ComboBox *combo) override; private: //============================================================================== void loadAudioFile (File fileAudio); void setAudioChannels (int numInputChannels, int numOutputChannels, const XmlElement* const xml = nullptr); void shutdownAudio(); //============================================================================== AudioDeviceManager deviceManager; AudioSourcePlayer audioSourcePlayer; AudioFormatManager formatManager; AudioTransportSource transportSource; TimeSliceThread thread; ScopedPointer<AudioFormatReaderSource> currentAudioFileSource; //============================================================================== ScopedPointer<ListBox> listDemos; OwnedArray<SessionComponent> theSessionComponents; //============================================================================== ScopedPointer<TextButton> buttonPlay, buttonStop; ScopedPointer<ComboBox> comboAudioFiles; Array<File> fileListAudio; ScopedPointer<AudioThumbnailComponent> theThumbComponent; //============================================================================== MainComponentLookAndFeel theLF; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainComponent) }; <file_sep>/Source/Sessions/Session7/SessionSevenDSP.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" //============================================================================== /** State Variable Filter (low-pass output) with TPT Structure and naive tanh nonlinearity */ class SVFLowpassFilterNL { public: //============================================================================== SVFLowpassFilterNL(); ~SVFLowpassFilterNL(); //============================================================================== /** Initialization of the filter */ void initProcessing (double sampleRate); /** Sets the cutoff frequency of the filter */ void setCutoffFrequency (float value); /** Sets the resonance of the filter */ void setResonance (float value); //============================================================================== /** Resets the filter's processing pipeline. */ void reset(); /** Processes a single sample. */ float processSingleSampleRaw (const float &sample); private: //============================================================================== /** Updates the internal variables */ void updateProcessing(); //============================================================================== double sampleRate; std::atomic <float> frequency; std::atomic <float> resonance; float g, R2, h; float s1, s2; bool isActive, mustUpdateProcessing; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SVFLowpassFilterNL) }; //============================================================================== /** Diode clipper algorithm with TPT structure and Newton-Raphson's method to solve the nonlinearities */ class DiodeClipper { public: //============================================================================== DiodeClipper(); ~DiodeClipper(); //============================================================================== /** Initialization of the filter */ void initProcessing (double sampleRate); /** Sets the cutoff frequency of the filter */ void setCutoffFrequency (float value); //============================================================================== /** Resets the filter's processing pipeline. */ void reset(); /** Processes a single sample. */ float processSingleSampleRaw (const float &sample); private: //============================================================================== /** Updates the internal variables */ void updateProcessing(); //============================================================================== double sampleRate; std::atomic<float> frequency; float G, R2, h; float s1; double output; double deltaLim; bool isActive, mustUpdateProcessing; //============================================================================== // Constants const int numIterations = 8; const double Is = 14.11e-9; const double mu = 1.984; const double Vt = 26e-3; const double R = 2.2e3; const double tolerance = 1e-12; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DiodeClipper) }; <file_sep>/Source/SessionComponents.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "SessionComponents.h" //============================================================================== SettingsComponent::SettingsComponent (AudioDeviceManager *adm) : SessionComponent ("Settings", adm) { addAndMakeVisible (selectorComponent = new AudioDeviceSelectorComponent (*deviceManager, 0, 2, 0, 2, false, false, true, true)); } SettingsComponent::~SettingsComponent() { } void SettingsComponent::resized() { selectorComponent->setBounds (getLocalBounds()); } //============================================================================== AboutComponent::AboutComponent (AudioDeviceManager *adm) : SessionComponent ("About", adm) { } AboutComponent::~AboutComponent() { } void AboutComponent::resized() { } void AboutComponent::paint (Graphics& g) { g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId)); g.setColour (Colours::white); g.setFont (Font (16.f)); String strTemp = "Audio Developer Conference 2018 Workshop\n"; strTemp += "Designing digital effects with state-of-the-art DSP and audio filter algorithms\n\n"; strTemp += "Application and workshop designed by <NAME>\n"; strTemp += "With the help, advice and trust from the JUCE team and Zsolt GARAMVOLGYI\n"; strTemp += "Copyright (c) <NAME> 2017-2018\n\n"; g.drawFittedText (strTemp, getLocalBounds().reduced (20), Justification::topLeft, 20); } //============================================================================== JavascriptEngineComponent::JavascriptEngineComponent (AudioDeviceManager *adm) : SessionComponent ("Javascript Playground", adm) { addAndMakeVisible (editor = new CodeEditorComponent (codeDocument, nullptr)); editor->setFont ({ Font::getDefaultMonospacedFontName(), 14.0f, Font::plain }); editor->setTabSize (4, true); addAndMakeVisible (outputDisplay = new TextEditor()); outputDisplay->setMultiLine (true); outputDisplay->setReadOnly (true); outputDisplay->setCaretVisible (false); outputDisplay->setFont ({ Font::getDefaultMonospacedFontName(), 14.0f, Font::plain }); codeDocument.addListener (this); editor->loadContent ( "/**\n" " Javascript! In this simple demo, the native\n" " code provides an object called 'Demo' which\n" " has a method 'print' that writes to the\n" " console below...\n" "*/\n\n" "Demo.print (\"Newton-Raphson's algorithm in JUCE + Javascript!\");\n" "Demo.print (\"Calculus of square root of five\");\n" "Demo.print (\"\");\n\n" "function square_root_five_newton_raphson (x)\n" "{\n" " var g = x * x - 5; // expression of g in g (x) = 0 = x*x - 5\n" " var dg = 2 * x; // derivative of g (x)\n" " x = x - g / dg; // Newton-Raphson's algorithm application\n" " return x;\n" "}\n\n" "var x_0 = 1;\n\n" "Demo.print (\"Initial value = \" + x_0);\n" "Demo.print (\"\");\n\n" "var x = x_0;\n\n" "for (var i = 1; i < 10; ++i)\n" "{\n" " x = square_root_five_newton_raphson (x);\n" " Demo.print (\"Iteration \" + i + \" : x = \" + x);\n" "}\n\n" "Demo.print (\"\");\n" "Demo.print (\"Exact value : x = \" + Math.sqrt (5));\n" ); } JavascriptEngineComponent::~JavascriptEngineComponent() { } void JavascriptEngineComponent::resized() { auto r = getLocalBounds().reduced (8); editor->setBounds (r.removeFromTop (proportionOfHeight (0.6f))); outputDisplay->setBounds (r.withTrimmedTop (8)); } void JavascriptEngineComponent::paint (Graphics &g) { g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId)); } void JavascriptEngineComponent::codeDocumentTextInserted (const String&, int) { startTimer (300); } void JavascriptEngineComponent::codeDocumentTextDeleted (int, int) { startTimer (300); } void JavascriptEngineComponent::consoleOutput (const String& message) { outputDisplay->moveCaretToEnd(); outputDisplay->insertTextAtCaret (message + newLine); } void JavascriptEngineComponent::timerCallback() { stopTimer(); runScript(); } void JavascriptEngineComponent::runScript() { outputDisplay->clear(); JavascriptEngine engine; engine.maximumExecutionTime = RelativeTime::seconds (5); engine.registerNativeObject ("Demo", new DemoClass (*this)); auto startTime = Time::getMillisecondCounterHiRes(); auto result = engine.execute (codeDocument.getAllContent()); auto elapsedMs = Time::getMillisecondCounterHiRes() - startTime; if (result.failed()) outputDisplay->setText (result.getErrorMessage()); else outputDisplay->insertTextAtCaret ("\n (Execution time: " + String (elapsedMs, 2) + " milliseconds)"); } <file_sep>/Source/Sessions/Session7/SessionSevenDSP.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "SessionSevenDSP.h" //============================================================================== SVFLowpassFilterNL::SVFLowpassFilterNL() { frequency.store (1000.f); resonance.store (1.f / std::sqrt (2.f)); sampleRate = 44100.0; isActive = false; } SVFLowpassFilterNL::~SVFLowpassFilterNL() { } void SVFLowpassFilterNL::initProcessing (double _sampleRate) { jassert (_sampleRate > 0); sampleRate = _sampleRate; updateProcessing(); reset(); isActive = true; } void SVFLowpassFilterNL::setCutoffFrequency (float value) { jassert (value > 0.f && value < 0.5f * sampleRate); frequency.store (value); mustUpdateProcessing = true; } void SVFLowpassFilterNL::setResonance (float value) { jassert (value > 0); resonance.store (1.f / value); mustUpdateProcessing = true; } void SVFLowpassFilterNL::reset() { s1 = 0.f; s2 = 0.f; } float SVFLowpassFilterNL::processSingleSampleRaw (const float &sample) { if (!(isActive)) return 0.f; if (mustUpdateProcessing) updateProcessing(); auto yH = (sample - s1 * (R2 + g) - s2) * h; auto yB = g * yH + s1; auto yL = g * yB + s2; yB = std::tanh (yB); yL = std::tanh (yL); s1 = g * yH + yB; s2 = g * yB + yL; return yL; } void SVFLowpassFilterNL::updateProcessing() { mustUpdateProcessing = false; g = std::tan (float_Pi * frequency.load() / (float)sampleRate); R2 = resonance.load(); h = 1.f / (1 + R2 * g + g * g); } //============================================================================== DiodeClipperADC18::DiodeClipper() { frequency.store (1000.f); sampleRate = 44100.0; isActive = false; } DiodeClipperADC18::~DiodeClipper() { } void DiodeClipper::initProcessing (double _sampleRate) { jassert (_sampleRate > 0); sampleRate = _sampleRate; updateProcessing(); reset(); isActive = true; } void DiodeClipper::setCutoffFrequency (float value) { jassert (value > 0.f && value < 0.5f * sampleRate); frequency.store (value); mustUpdateProcessing = true; } void DiodeClipper::reset() { s1 = 0.f; output = 0.0; } float DiodeClipper::processSingleSampleRaw (const float &sample) { if (!(isActive)) return 0.f; if (mustUpdateProcessing) updateProcessing(); const auto in = sample; const auto p = G * (in - s1) + s1; double delta = 1e9; // Newton-Raphson iterations auto k = 0; while (std::abs (delta) > tolerance && k < numIterations) { auto J = p - (2 * G*R*Is) * std::sinh (output / mu / Vt) - output; auto dJ = -1 - G * 2 * R*Is / mu / Vt * std::cosh (output / mu / Vt); delta = -J / dJ; if (isnan (delta) || isinf (delta) || std::abs (delta) > deltaLim) delta = (delta >= 0 ? 1 : -1) * deltaLim; output = output + delta; k++; } auto v = (float)output - s1; s1 = (float)output + v; return (float)output; } void DiodeClipper::updateProcessing() { auto g = std::tan (float_Pi * frequency.load() / (float)sampleRate); G = g / (1 + g); deltaLim = mu * Vt * std::acosh (mu * Vt / 2.0 / (R * Is * G)); } <file_sep>/Source/Sessions/Session4/SessionFourDSP.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" class BallisticsFilter { public: //============================================================================== /** Constructor. */ BallisticsFilter(); /** Destructor. */ ~BallisticsFilter(); //============================================================================== /** Inits the processing by providing the sample rate. */ void initProcessing (double sampleRate); /** Resets the filter state. */ void reset (float zeroValue = 0.f); /** Processes one sample. */ float processSingleSample (float &sample); //============================================================================== /** Sets the attack time in ms. */ void setAttackTime (float attackTimeMs); /** Sets the release time in ms. */ void setReleaseTime (float releaseTimeMs); private: //============================================================================== /** @internal */ void updateProcessing(); //============================================================================== double sampleRate; bool mustUpdateProcessing, isActive; //============================================================================== std::atomic<float> prmAttack, prmRelease; //============================================================================== float cteAT, cteRL; float yold; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BallisticsFilter) }; <file_sep>/Source/Sessions/Session4/SessionFourComponent.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "SessionFourComponent.h" #include "../../Assets/LowFrequencyOscillator.h" //============================================================================== SessionFourComponent::SessionFourComponent (AudioDeviceManager *adm) : SessionComponent ("Compression", adm) { // ------------------------------------------------------------------------- addAndMakeVisible (thePlotComponent = new PlotComponent()); // ------------------------------------------------------------------------- addAndMakeVisible (sliderThreshold = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderThreshold->setRange (-80.0, 0.0); sliderThreshold->setValue (0.0, dontSendNotification); sliderThreshold->setDoubleClickReturnValue (true, 0.0); sliderThreshold->addListener (this); addAndMakeVisible (sliderRatio = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderRatio->setRange (1.0, 100.0); sliderRatio->setSkewFactor (0.2); sliderRatio->setValue (1.0, dontSendNotification); sliderRatio->addListener (this); addAndMakeVisible (sliderAttack = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderAttack->setRange (0.1, 1000.0); sliderAttack->setSkewFactor (0.2); sliderAttack->setValue (0.1, dontSendNotification); sliderAttack->addListener (this); addAndMakeVisible (sliderRelease = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderRelease->setRange (10.0, 10000.0); sliderRelease->setSkewFactor (0.2); sliderRelease->setValue (50.0, dontSendNotification); sliderRelease->addListener (this); // ------------------------------------------------------------------------- addAndMakeVisible (comboEnvelopeEnabled = new ComboBox()); comboEnvelopeEnabled->addItemList ({ "Disabled", "Enabled" }, 1); comboEnvelopeEnabled->addListener (this); comboEnvelopeEnabled->setSelectedId (1, dontSendNotification); // ------------------------------------------------------------------------- addAndMakeVisible (labelThreshold = new Label ("", "Threshold")); labelThreshold->setJustificationType (Justification::centred); labelThreshold->attachToComponent (sliderThreshold, false); addAndMakeVisible (labelRatio = new Label ("", "Ratio")); labelRatio->setJustificationType (Justification::centred); labelRatio->attachToComponent (sliderRatio, false); addAndMakeVisible (labelAttack = new Label ("", "Attack")); labelAttack->setJustificationType (Justification::centred); labelAttack->attachToComponent (sliderAttack, false); addAndMakeVisible (labelRelease = new Label ("", "Release")); labelRelease->setJustificationType (Justification::centred); labelRelease->attachToComponent (sliderRelease, false); addAndMakeVisible (labelEnvelopeEnabled = new Label ("", "Envelope")); labelEnvelopeEnabled->setJustificationType (Justification::centred); labelEnvelopeEnabled->attachToComponent (comboEnvelopeEnabled, false); // ------------------------------------------------------------------------- updateVisibility(); triggerAsyncUpdate(); } SessionFourComponent::~SessionFourComponent() { } void SessionFourComponent::paint (Graphics &g) { auto rect = getLocalBounds(); g.setColour (Colours::white); g.fillRect (rect.removeFromTop (getHeight() - 170)); g.setColour (getLookAndFeel().findColour (ResizableWindow::backgroundColourId)); g.fillRect (rect); } void SessionFourComponent::resized() { Rectangle<int> rect = getLocalBounds(); auto rectTop = rect.removeFromTop (getHeight() - 170); thePlotComponent->setBounds (rectTop.reduced (10, 10)); rect.removeFromTop (40); auto rectMid = rect.removeFromTop (100).reduced (10, 0); comboEnvelopeEnabled->setBounds (rectMid.withWidth (160).withSizeKeepingCentre (160, 24)); sliderThreshold->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200, 0)); sliderRatio->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 100, 0)); sliderAttack->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 200, 0)); sliderRelease->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 300, 0)); } void SessionFourComponent::updateVisibility() { auto isEnvelopeEnabled = comboEnvelopeEnabled->getSelectedId() == 2; sliderAttack->setVisible (isEnvelopeEnabled); sliderRelease->setVisible (isEnvelopeEnabled); } //============================================================================== void SessionFourComponent::sliderValueChanged (Slider *slider) { if (slider == sliderThreshold || slider == sliderRatio) { mustUpdateProcessing = true; } else if (slider == sliderAttack || slider == sliderRelease) { mustUpdateProcessing = true; } } void SessionFourComponent::comboBoxChanged (ComboBox *combo) { if (combo == comboEnvelopeEnabled) { mustUpdateProcessing = true; updateVisibility(); } } //============================================================================== void SessionFourComponent::prepareToPlay (int samplesPerBlockExpected, double sR) { SessionComponent::prepareToPlay (samplesPerBlockExpected, sR); theCompressor.ballisticsFilter.initProcessing (sR); updateProcessing(); reset(); isActive = true; } void SessionFourComponent::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) { if (mustUpdateProcessing) updateProcessing(); ScopedNoDenormals noDenormals; auto startSample = bufferToFill.startSample; auto numSamples = bufferToFill.numSamples; auto numChannels = jmax (2, bufferToFill.buffer->getNumChannels()); jassert (numSamples > 0); jassert (numChannels > 0); for (auto i = 0; i < numSamples; i++) { auto sideInput = 0.f; // Detector (peak) for (auto channel = 0; channel < numChannels; channel++) sideInput = jmax (sideInput, std::abs (bufferToFill.buffer->getSample (channel, i + startSample))); // Ballistics filter for envelope generation auto env = theCompressor.mustUseBallistics ? theCompressor.ballisticsFilter.processSingleSample (sideInput) : sideInput; // Compressor transfer function auto cv = (env <= theCompressor.thrlin ? 1.f : std::pow (env / theCompressor.thrlin, theCompressor.ratioinv - 1.f)); // Auto make-up gain cv *= theCompressor.makeupgain; // Processing for (auto channel = 0; channel < numChannels; channel++) bufferToFill.buffer->applyGain (channel, i + startSample, 1, cv); } } void SessionFourComponent::releaseAudioResources() { reset(); } void SessionFourComponent::reset() { theCompressor.ballisticsFilter.reset(); } void SessionFourComponent::updateProcessing() { mustUpdateProcessing = false; theCompressor.thrlin = (float) Decibels::decibelsToGain (sliderThreshold->getValue()); theCompressor.ratioinv = 1.f / (float)sliderRatio->getValue(); theCompressor.makeupgain = Decibels::decibelsToGain (-((float)sliderThreshold->getValue() * (1.f - theCompressor.ratioinv)) / 2.f); theCompressor.ballisticsFilter.setAttackTime ((float)sliderAttack->getValue()); theCompressor.ballisticsFilter.setReleaseTime ((float)sliderRelease->getValue()); theCompressor.mustUseBallistics = comboEnvelopeEnabled->getSelectedId() == 2; } //============================================================================== void SessionFourComponent::timerCallback() { stopThread (1000); startThread(); } void SessionFourComponent::run() { if (!(isActive)) return; // ------------------------------------------------------------------------- auto N = 2001; bufferData.setSize (3, N, false, false, true); if (threadShouldExit()) return; // ------------------------------------------------------------------------- auto *samples = bufferData.getWritePointer (0); for (auto i = 0; i < N; i++) samples[i] = i / (float)sampleRate * 1000.f; if (threadShouldExit()) return; // ------------------------------------------------------------------------- LowFrequencyOscillator theLFO; theLFO.setFrequency (50.0); theLFO.setType (LowFrequencyOscillator::lfoSquare); theLFO.initProcessing (sampleRate); theLFO.reset (7.f * float_Pi / 4.f); samples = bufferData.getWritePointer (1); for (auto i = 0; i < N; i++) samples[i] = theLFO.getNextSample(); if (threadShouldExit()) return; // ------------------------------------------------------------------------- BallisticsFilter theBallisticsFilter; theBallisticsFilter.setAttackTime ((float)sliderAttack->getValue()); theBallisticsFilter.setReleaseTime ((float)sliderRelease->getValue()); theBallisticsFilter.initProcessing (sampleRate); auto *dataY = bufferData.getWritePointer (2); auto isEnvelopeEnabled = comboEnvelopeEnabled->getSelectedId() == 2; for (auto i = 0; i < N; i++) { if (isEnvelopeEnabled) dataY[i] = theBallisticsFilter.processSingleSample (samples[i]); else dataY[i] = samples[i]; } // ------------------------------------------------------------------------- PlotComponent::Information information; information.minimumXValue = 0; information.maximumXValue = (N - 1.0) / sampleRate * 1000.0; information.gridXSize = 4.0; information.minimumYValue = -1.5; information.maximumYValue = 1.5; information.gridYSize = 0.25; information.displayGrid = true; information.strLabelX = "time (ms)"; information.strLabelY = "amplitude"; thePlotComponent->setInformation (information); // ------------------------------------------------------------------------- thePlotComponent->pushData (bufferData, N, 2); triggerAsyncUpdate(); } <file_sep>/Source/FileSystem.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" //============================================================================== /** Class with static functions to access to all the external data */ struct FileSystem { public: //============================================================================== static const File getDataFolder() { File fileExecutable = File::getSpecialLocation (File::SpecialLocationType::currentApplicationFile); if (fileExecutable.getSiblingFile ("./Data/").isDirectory()) return fileExecutable.getSiblingFile ("./Data/"); else if (fileExecutable.getSiblingFile ("../Data/").isDirectory()) return fileExecutable.getSiblingFile ("../Data/"); else if (fileExecutable.getSiblingFile ("../../Data/").isDirectory()) return fileExecutable.getSiblingFile ("../../Data/"); else if (fileExecutable.getSiblingFile ("../../../Data/").isDirectory()) return fileExecutable.getSiblingFile ("../../../Data/"); else if (fileExecutable.getSiblingFile ("../../../../Data/").isDirectory()) return fileExecutable.getSiblingFile ("../../../../Data/"); else if (fileExecutable.getSiblingFile ("../../../../../Data/").isDirectory()) return fileExecutable.getSiblingFile ("../../../../../Data/"); else if (fileExecutable.getSiblingFile ("../../../../../../Data/").isDirectory()) return fileExecutable.getSiblingFile ("../../../../../../Data/"); else if (fileExecutable.getSiblingFile("../../../../../../../Data/").isDirectory()) return fileExecutable.getSiblingFile("../../../../../../../Data/"); else return File(); } //============================================================================== static const File getAudioFolder() { if (getDataFolder() == File()) return File(); else return getDataFolder().getChildFile ("./Audio/"); } static const Array<File> getAudioList() { File folder = getAudioFolder(); Array <File> results; if (folder != File()) folder.findChildFiles (results, File::findFiles, true, "*.wav;*.aif;*.aiff;*.mp3"); return results; } }; <file_sep>/Source/Assets/PlotComponent.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" class PlotComponent : public Component, public AsyncUpdater { public: struct Information { String strTitle; String strLabelX; String strLabelY; double minimumXValue = 0; double maximumXValue = 0; double minimumYValue = 0; double maximumYValue = 0; bool isXAxisLogarithmic = false; bool displayGrid = true; double gridXSize = 0; double gridYSize = 0; bool gridXMustStartAtZero = true; bool gridYMustStartAtZero = true; double numOctavesMaxFullGridLog = 6.0; bool displayGridXValues = true; bool displayGridYValues = true; bool displayGridYValuesReverted = false; }; struct ColourIDs { Colour backgroundColour = Colours::white; Colour outlineColour = Colours::black; Array<Colour> dataColours = { Colour (0xFF0072BD), Colour (0xFFD95319), Colour (0xFFEDB120) }; Colour gridColour = Colours::lightgrey; Colour markerColour = Colours::black; Colour textColour = Colours::black; }; struct PlotLayout { float marginX = 0.f; float marginRight = 60.f; float marginY = 0.f; float marginBottom = 0.f; float markerSize = 4.f; float titleFontSize = 20.f; float titleSize = 60.f; float titleNoSize = 10.f; float labelFontSize = 16.f; float labelXSize = 30.f; float labelYSize = 30.f; float valuesFontSize = 14.f; float valuesXSize = 30.f; float valuesYSize = 40.f; float valuesLength = 50.f; float valuesYMargin = 5.f; float sizePoint = 6.f; Font fontPlotComponent = Font(); }; //============================================================================== PlotComponent(); ~PlotComponent(); //============================================================================== /** Sets the data in the Information structure. */ void setInformation (const Information &newInfo); /** Returns the data in the Information structure. */ const Information getInformation() const; //============================================================================== /** Sets the data in the ColourIDs structure. */ void setColourIDs (const ColourIDs &newInfo); /** Returns the data in the ColourIDs structure. */ const ColourIDs getColourIDs() const; //============================================================================== /** Sets the data in the PlotLayout structure. */ void setPlotLayout (const PlotLayout &newInfo); /** Returns the data in the PlotLayout structure. */ const PlotLayout getPlotLayout() const; /** Pushes the data to display (several outputs). */ void pushData (const AudioBuffer<float> &dataXY, int numPoints, int numEntries); private: //============================================================================== /** @internal */ void paint (Graphics&) override; /** @internal */ void resized() override; /** @internal */ void handleAsyncUpdate() override; //============================================================================== /** @internal */ void paintTitle (Graphics&, Rectangle<int>); /** @internal */ void paintValuesX (Graphics&, Rectangle<int>); /** @internal */ void paintValuesXLog (Graphics&, Rectangle<int>); /** @internal */ void paintValuesY (Graphics&, Rectangle<int>); /** @internal */ void paintLabelsX (Graphics&, Rectangle<int>); /** @internal */ void paintLabelsY (Graphics&, Rectangle<int>); /** @internal */ void paintGridX (Graphics&, Rectangle<int>); /** @internal */ void paintGridXLog (Graphics&, Rectangle<int>); /** @internal */ void paintGridY (Graphics&, Rectangle<int>); /** @internal */ void paintData (Graphics&, Rectangle<int>); //============================================================================== struct DataStructure { DataStructure() { numPoints.store (0); numEntries.store (0); } Array<float> dataX; Array<Array<float>> dataY; std::atomic<int> numPoints; std::atomic<int> numEntries; }; //============================================================================== CriticalSection processLock, dataLock; Information information; ColourIDs colourIDs; PlotLayout plotLayout; DataStructure dataStructure; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PlotComponent) }; <file_sep>/Source/Sessions/Session3/SessionThreeDSP.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" class SessionThreeDSP { public: //============================================================================== SessionThreeDSP() {} ~SessionThreeDSP() {} //============================================================================== enum AlgorithmType { Algorithm_BLT_NoWarping = 0, Algorithm_BLT_Warping, Algorithm_Forward_Euler, Algorithm_Backward_Euler, Algorithm_Trap, Algorithm_BDF2, Algorithm_ImpulseInvariance, Algorithm_Massberg, Algorithm_Vicanek }; //============================================================================== static const void calculusLP2Coefficients (float frequency, float Q, int algorithm, double sampleRate, int &order, float &b0, float &b1, float &b2, float &b3, float &b4, float &a1, float &a2, float &a3, float &a4); static const double getMagnitudeForFrequency (double frequency, double sampleRate, const float b0, const float b1, const float b2, const float b3, const float b4, const float a1, const float a2, const float a3, const float a4 ); static const double getPhaseForFrequency (double frequency, double sampleRate, const float b0, const float b1, const float b2, const float b3, const float b4, const float a1, const float a2, const float a3, const float a4); //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SessionThreeDSP) }; <file_sep>/Source/Sessions/Session4/SessionFourComponent.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "../../SessionComponents.h" #include "../../Assets/PlotComponent.h" #include "SessionFourDSP.h" class SessionFourComponent : public SessionComponent, public Slider::Listener, public ComboBox::Listener { public: //============================================================================== SessionFourComponent (AudioDeviceManager *adm); ~SessionFourComponent(); //============================================================================== void paint (Graphics &g) override; void resized() override; //============================================================================== void sliderValueChanged (Slider *slider) override; void comboBoxChanged (ComboBox *combo) override; //============================================================================== void prepareToPlay (int samplesPerBlockExpected, double sampleRate) override; void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override; void releaseAudioResources() override; void reset() override; private: //============================================================================== void timerCallback() override; void run() override; //============================================================================== void updateProcessing(); void updateVisibility(); //============================================================================== struct DynamicsCompressorState { float thrlin, ratioinv; float makeupgain; BallisticsFilter ballisticsFilter; bool mustUseBallistics; }; DynamicsCompressorState theCompressor; bool isActive = false; //============================================================================== ScopedPointer<PlotComponent> thePlotComponent; AudioBuffer<float> bufferData; //============================================================================== ScopedPointer<Slider> sliderThreshold, sliderRatio, sliderAttack, sliderRelease; ScopedPointer<Label> labelThreshold, labelRatio, labelAttack, labelRelease; ScopedPointer<ComboBox> comboEnvelopeEnabled; ScopedPointer<Label> labelEnvelopeEnabled; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SessionFourComponent) }; <file_sep>/Source/Sessions/Session5/SessionFiveDSP.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" class LinearSlewLimiter { public: //============================================================================== LinearSlewLimiter(); ~LinearSlewLimiter(); //============================================================================== void reset (float resetValue = 0.f); void setSlew (double sampleRate, double slewRiseMaximumSlopeInVpS, double slewFallMaximumSlopeInVpS); //============================================================================== float getSample (float &input); private: //============================================================================== float slewRiseMax, slewFallMax; float lastOutput; bool justReset; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinearSlewLimiter) }; class TPTFilter1stOrder { public: enum TPTFilterType { TypeLowPass = 0, TypeHighPass }; TPTFilter1stOrder(); /** Destructor. */ ~TPTFilter1stOrder(); //============================================================================== /** Initialization of the filter */ void initProcessing (double sampleRate); /** Sets the type of IIR filter */ void setType (TPTFilterType type); /** Sets the cutoff frequency of the IIR filter */ void setCutoffFrequency (float frequency); //============================================================================== /** Resets the filter's processing pipeline. */ void reset (const float s1eq = 0.f); /** Processes a single sample. */ float processSingleSampleRaw (const float &sample); private: //============================================================================== /** Updates the internal variables */ void updateProcessing(); //============================================================================== double sampleRate; std::atomic <int> type; std::atomic <float> frequency; float g, s1; int currentType = 0; bool isActive, mustUpdateProcessing; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TPTFilter1stOrder) }; <file_sep>/Source/Sessions/Session1/SessionOneComponent.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "../../SessionComponents.h" #include "../../Assets/PlotComponent.h" class SessionOneComponent : public SessionComponent, public Slider::Listener, public ComboBox::Listener { public: //============================================================================== SessionOneComponent (AudioDeviceManager *adm); ~SessionOneComponent(); //============================================================================== void paint (Graphics &g) override; void resized() override; //============================================================================== void sliderValueChanged (Slider *slider) override; void comboBoxChanged (ComboBox *combo) override; //============================================================================== void prepareToPlay (int samplesPerBlockExpected, double sampleRate) override; void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override; void releaseAudioResources() override; void reset() override; private: //============================================================================== void timerCallback() override; void run() override; void updateVisibility(); //============================================================================== void updateProcessing(); //============================================================================== struct FilterCoefficients { float b0, b1, b2; // Z transform coefficients (numerator) float a1, a2; // Z transform coefficients (denominator) }; struct FilterState { float v1, v2; // state variable for TDF2 }; FilterCoefficients theCoefficients; FilterState theFilters[2]; bool isActive = false; //============================================================================== ScopedPointer<PlotComponent> thePlotComponent; AudioBuffer<float> bufferData; //============================================================================== ScopedPointer<Slider> sliderFrequency, sliderResonance, sliderGain; ScopedPointer<ComboBox> comboType, comboDisplay; ScopedPointer<Label> labelFrequency, labelResonance, labelGain; ScopedPointer<Label> labelType, labelDisplay; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SessionOneComponent) }; <file_sep>/Source/Sessions/Session7/SessionSevenComponent.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "SessionSevenComponent.h" #include "../Session1/SessionOneDSP.h" #include "../Session2/SessionTwoDSP.h" #include "../Session3/SessionThreeDSP.h" #include "../../Assets/MathFunctions.h" //============================================================================== SessionSevenComponent::SessionSevenComponent (AudioDeviceManager *adm) : SessionComponent ("Models", adm) { // ------------------------------------------------------------------------- addAndMakeVisible (thePlotComponent = new PlotComponent()); // ------------------------------------------------------------------------- addAndMakeVisible (sliderGain = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderGain->setRange (-40.0, 40.0); sliderGain->setDoubleClickReturnValue (true, 0.0); sliderGain->setValue (0.0, dontSendNotification); sliderGain->addListener (this); addAndMakeVisible (sliderFrequency = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderFrequency->setRange (20.0, 22000.0); sliderFrequency->setSkewFactor (0.2); sliderFrequency->setValue (1000.0, dontSendNotification); sliderFrequency->addListener (this); addAndMakeVisible (sliderResonance = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderResonance->setRange (0.01, 100.0); sliderResonance->setDoubleClickReturnValue (true, 1.0 / std::sqrt (2.0)); sliderResonance->setSkewFactor (0.1); sliderResonance->setValue (1.0 / std::sqrt (2.0), dontSendNotification); sliderResonance->addListener (this); addAndMakeVisible (sliderModulation = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderModulation->setRange (0.0, 100.0); sliderModulation->setDoubleClickReturnValue (true, 50.0); sliderModulation->setValue (50.0, dontSendNotification); sliderModulation->addListener (this); addAndMakeVisible (sliderLFOFrequency = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderLFOFrequency->setRange (0.01, 20.0); sliderLFOFrequency->setDoubleClickReturnValue (true, 1.0); sliderLFOFrequency->setSkewFactor (0.1); sliderLFOFrequency->setValue (1.0, dontSendNotification); sliderLFOFrequency->addListener (this); addAndMakeVisible (sliderEnvAttack = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderEnvAttack->setRange (0.1, 1000.0); sliderEnvAttack->setSkewFactor (0.2); sliderEnvAttack->setValue (0.1, dontSendNotification); sliderEnvAttack->addListener (this); addAndMakeVisible (sliderEnvRelease = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderEnvRelease->setRange (10.0, 10000.0); sliderEnvRelease->setSkewFactor (0.2); sliderEnvRelease->setValue (50.0, dontSendNotification); sliderEnvRelease->addListener (this); addAndMakeVisible (sliderEnvSens = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderEnvSens->setRange (0.0, 100.0); sliderEnvSens->setDoubleClickReturnValue (true, 50.0); sliderEnvSens->setValue (50.0, dontSendNotification); sliderEnvSens->addListener (this); // ------------------------------------------------------------------------- addAndMakeVisible (comboModel = new ComboBox()); comboModel->addItem ("SVF NL (naive)", 1); comboModel->addItem ("Moog filter (JUCE)", 2); comboModel->addItem ("Diode Clipper (NR)", 3); comboModel->addListener (this); comboModel->setSelectedId (1, dontSendNotification); // ------------------------------------------------------------------------- addAndMakeVisible (comboModulationType = new ComboBox()); comboModulationType->addItemList ({ "None", "LFO Triangle", "LFO Square", "Env. Up", "Env. Down" }, 1); comboModulationType->addListener (this); comboModulationType->setSelectedId (1, dontSendNotification); // ------------------------------------------------------------------------- addAndMakeVisible (labelGain = new Label ("", "Drive")); labelGain->setJustificationType (Justification::centred); labelGain->attachToComponent (sliderGain, false); addAndMakeVisible (labelFrequency = new Label ("", "Frequency")); labelFrequency->setJustificationType (Justification::centred); labelFrequency->attachToComponent (sliderFrequency, false); addAndMakeVisible (labelResonance = new Label ("", "Resonance")); labelResonance->setJustificationType (Justification::centred); labelResonance->attachToComponent (sliderResonance, false); addAndMakeVisible (labelModulation = new Label ("", "Depth")); labelModulation->setJustificationType (Justification::centred); labelModulation->attachToComponent (sliderModulation, false); addAndMakeVisible (labelLFOFrequency = new Label ("", "LFO freq.")); labelLFOFrequency->setJustificationType (Justification::centred); labelLFOFrequency->attachToComponent (sliderLFOFrequency, false); addAndMakeVisible (labelEnvAttack = new Label ("", "Attack")); labelEnvAttack->setJustificationType (Justification::centred); labelEnvAttack->attachToComponent (sliderEnvAttack, false); addAndMakeVisible (labelEnvRelease = new Label ("", "Release")); labelEnvRelease->setJustificationType (Justification::centred); labelEnvRelease->attachToComponent (sliderEnvRelease, false); addAndMakeVisible (labelEnvSens = new Label ("", "Sensitivity")); labelEnvSens->setJustificationType (Justification::centred); labelEnvSens->attachToComponent (sliderEnvSens, false); addAndMakeVisible (labelModel = new Label ("", "Model")); labelModel->setJustificationType (Justification::centred); labelModel->attachToComponent (comboModel, false); addAndMakeVisible (labelModulationType = new Label ("", "Modulation Type")); labelModulationType->setJustificationType (Justification::centred); // ------------------------------------------------------------------------- lastEnvValue.store (0.5f); // ------------------------------------------------------------------------- theOversampling.reset (new dsp::Oversampling<float> (2)); theOversampling->clearOversamplingStages(); theOversampling->addOversamplingStage (dsp::Oversampling<float>::filterHalfBandPolyphaseIIR, 0.05f, -90.f, 0.05f, -90.f); theOversampling->addOversamplingStage (dsp::Oversampling<float>::filterHalfBandPolyphaseIIR, 0.05f, -90.f, 0.05f, -90.f); // ------------------------------------------------------------------------- updateVisibility(); triggerAsyncUpdate(); } SessionSevenComponent::~SessionSevenComponent() { } void SessionSevenComponent::paint (Graphics &g) { auto rect = getLocalBounds(); g.setColour (Colours::white); g.fillRect (rect.removeFromTop (getHeight() - 170)); g.setColour (getLookAndFeel().findColour (ResizableWindow::backgroundColourId)); g.fillRect (rect); } void SessionSevenComponent::resized() { Rectangle<int> rect = getLocalBounds(); auto rectTop = rect.removeFromTop (getHeight() - 170); thePlotComponent->setBounds (rectTop.reduced (10, 10)); rect.removeFromTop (40); auto rectMid = rect.removeFromTop (100).reduced (10, 0); comboModel->setBounds (rectMid.withWidth (130).withSizeKeepingCentre (130, 24).translated (0, -28)); comboModulationType->setBounds (rectMid.withWidth (130).withSizeKeepingCentre (130, 24).translated (0, 28)); labelModulationType->setBounds (rectMid.withWidth (130).withSizeKeepingCentre (130, 24).translated (0, 52)); auto sliderSize = 70; auto i = 0; rectMid = rectMid.withWidth (sliderSize); sliderGain->setBounds (rectMid.withSizeKeepingCentre (sliderSize, sliderSize).translated (160 + (sliderSize + 20) * i, 0)); i++; sliderFrequency->setBounds (rectMid.withSizeKeepingCentre (sliderSize, sliderSize).translated (160 + (sliderSize + 20) * i, 0)); i++; sliderResonance->setBounds (rectMid.withSizeKeepingCentre (sliderSize, sliderSize).translated (160 + (sliderSize + 20) * i, 0)); i++; sliderModulation->setBounds (rectMid.withSizeKeepingCentre (sliderSize, sliderSize).translated (160 + (sliderSize + 20) * i, 0)); i++; sliderLFOFrequency->setBounds (rectMid.withSizeKeepingCentre (sliderSize, sliderSize).translated (160 + (sliderSize + 20) * i, 0)); i++; i -= 2; sliderEnvAttack->setBounds (rectMid.withSizeKeepingCentre (sliderSize, sliderSize).translated (160 + (sliderSize + 20) * i, 0)); i++; sliderEnvRelease->setBounds (rectMid.withSizeKeepingCentre (sliderSize, sliderSize).translated (160 + (sliderSize + 20) * i, 0)); i++; sliderEnvSens->setBounds (rectMid.withSizeKeepingCentre (sliderSize, sliderSize).translated (160 + (sliderSize + 20) * i, 0)); i++; } //============================================================================== void SessionSevenComponent::sliderValueChanged (Slider *slider) { if (slider == sliderGain || slider == sliderResonance) { mustUpdateProcessing = true; } else if (slider == sliderFrequency) { mustUpdateProcessing = true; } else if (slider == sliderModulation || slider == sliderLFOFrequency) { mustUpdateProcessing = true; } else if (slider == sliderEnvAttack || slider == sliderEnvRelease || slider == sliderEnvSens) { mustUpdateProcessing = true; } } void SessionSevenComponent::comboBoxChanged (ComboBox *combo) { if (combo == comboModel) { mustUpdateProcessing = true; updateVisibility(); } else if (combo == comboModulationType) { mustUpdateProcessing = true; updateVisibility(); } } void SessionSevenComponent::updateVisibility() { auto modulation = comboModulationType->getSelectedId() - 1; labelModulation->setVisible (modulation == Modulation_LFO_Square || modulation == Modulation_LFO_Triangle); labelLFOFrequency->setVisible (modulation == Modulation_LFO_Square || modulation == Modulation_LFO_Triangle); sliderModulation->setVisible (modulation == Modulation_LFO_Square || modulation == Modulation_LFO_Triangle); sliderLFOFrequency->setVisible (modulation == Modulation_LFO_Square || modulation == Modulation_LFO_Triangle); labelEnvAttack->setVisible (modulation == Modulation_Envelope_Up || modulation == Modulation_Envelope_Down); labelEnvRelease->setVisible (modulation == Modulation_Envelope_Up || modulation == Modulation_Envelope_Down); labelEnvSens->setVisible (modulation == Modulation_Envelope_Up || modulation == Modulation_Envelope_Down); sliderEnvAttack->setVisible (modulation == Modulation_Envelope_Up || modulation == Modulation_Envelope_Down); sliderEnvRelease->setVisible (modulation == Modulation_Envelope_Up || modulation == Modulation_Envelope_Down); sliderEnvSens->setVisible (modulation == Modulation_Envelope_Up || modulation == Modulation_Envelope_Down); sliderResonance->setEnabled (comboModel->getSelectedId() - 1 != Model_DiodeClipper_NewtonRaphson); } //============================================================================== void SessionSevenComponent::prepareToPlay (int samplesPerBlockExpected, double sR) { SessionComponent::prepareToPlay (samplesPerBlockExpected, sR); auto oversamplingFactor = theOversampling->getOversamplingFactor(); theOversampling->initProcessing (samplesPerBlockExpected); for (auto channel = 0; channel < 2; channel++) { theFiltersNL[channel].initProcessing (sR * oversamplingFactor); theDiodeClipper[channel].initProcessing (sR * oversamplingFactor); } theMoogFilter.prepare ({ sR * oversamplingFactor, (uint32) (samplesPerBlockExpected * oversamplingFactor), 2u }); theMoogFilter.setMode (dsp::LadderFilter<float>::Mode::LPF24); bufferModulation.setSize (1, samplesPerBlockExpected * (int) oversamplingFactor); theLFO.initProcessing (sR * oversamplingFactor); theEnvelopeFollower.initProcessing (sR * oversamplingFactor); theSlewFilter.initProcessing (sR * oversamplingFactor); updateProcessing(); reset(); isActive = true; } void SessionSevenComponent::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) { if (mustUpdateProcessing) updateProcessing(); ScopedNoDenormals noDenormals; auto startSample = bufferToFill.startSample; auto numSamples = bufferToFill.numSamples; auto numSamplesOversampled = bufferToFill.numSamples * (int)theOversampling->getOversamplingFactor(); auto numChannels = jmax (2, bufferToFill.buffer->getNumChannels()); jassert (numSamples > 0); jassert (numChannels > 0); dsp::AudioBlock<float> inoutBlock (*(bufferToFill.buffer)); inoutBlock = inoutBlock.getSubBlock (startSample, numSamples); dsp::AudioBlock<float> oversampledBlock = theOversampling->processSamplesUp (inoutBlock); auto *envSamples = bufferModulation.getWritePointer (0); for (auto i = 0; i < numSamplesOversampled; i++) envSamples[i] = centralFreq; if (modulationType == Modulation_LFO_Square || modulationType == Modulation_LFO_Triangle) { for (auto i = 0; i < numSamplesOversampled; i++) envSamples[i] += theLFO.getNextSample() * depthVolume.getNextValue(); } else if (modulationType == Modulation_Envelope_Up || modulationType == Modulation_Envelope_Down) { for (auto i = 0; i < numSamplesOversampled; i++) { auto input = 0.f; for (auto channel = 0; channel < numChannels; channel++) input += oversampledBlock.getSample (channel, i); input /= (float)numChannels; envSamples[i] += theEnvelopeFollower.processSingleSample (input) * (modulationType == Modulation_Envelope_Down ? -1.f : 1.f); } } for (auto i = 0; i < numSamplesOversampled; i++) envSamples[i] = theSlewFilter.processSingleSampleRaw (envSamples[i]); for (auto i = 0; i < numSamplesOversampled; i++) envSamples[i] = jlimit (0.f, 1.f, envSamples[i]); lastEnvValue.store (envSamples[numSamples - 1]); if (modelType == Model_SVFNL_Naive) { oversampledBlock.multiply (gainVolume); for (auto channel = 0; channel < numChannels; channel++) { auto *samples = oversampledBlock.getChannelPointer (channel); for (auto i = 0; i < numSamplesOversampled; i++) { auto frequency = jmaplintolog (envSamples[i], 20.f, 22000.f); theFiltersNL[channel].setCutoffFrequency (frequency); samples[i] = theFiltersNL[channel].processSingleSampleRaw (samples[i]); } } } else if (modelType == Model_MoogFilter_JUCE) { for (auto i = 0; i < numSamplesOversampled; i++) { auto frequency = jmaplintolog (envSamples[i], 20.f, 22000.f); theMoogFilter.setCutoffFrequencyHz (frequency); auto blockSample = oversampledBlock.getSubBlock (i, 1); dsp::ProcessContextReplacing<float> context (blockSample); theMoogFilter.process (context); } } else if (modelType == Model_DiodeClipper_NewtonRaphson) { oversampledBlock.multiply (gainVolume); for (auto channel = 0; channel < numChannels; channel++) { auto *samples = oversampledBlock.getChannelPointer (channel); for (auto i = 0; i < numSamplesOversampled; i++) { auto frequency = jmaplintolog (envSamples[i], 20.f, 22000.f); theDiodeClipper[channel].setCutoffFrequency (frequency); samples[i] = theDiodeClipper[channel].processSingleSampleRaw (samples[i]); } } } theOversampling->processSamplesDown (inoutBlock); } void SessionSevenComponent::releaseAudioResources() { reset(); } void SessionSevenComponent::reset() { for (auto channel = 0; channel < 2; channel++) { theFiltersNL[channel].reset(); theDiodeClipper[channel].reset(); } theMoogFilter.reset(); auto oversamplingFactor = theOversampling->getOversamplingFactor(); theLFO.reset(); gainVolume.reset (sampleRate * oversamplingFactor, 0.05); depthVolume.reset (sampleRate * oversamplingFactor, 0.05); theEnvelopeFollower.reset(); theSlewFilter.reset(); theOversampling->reset(); } void SessionSevenComponent::updateProcessing() { mustUpdateProcessing = false; gainVolume.setValue (Decibels::decibelsToGain ((float)sliderGain->getValue())); modelType = comboModel->getSelectedId() - 1; modulationType = comboModulationType->getSelectedId() - 1; centralFreq = (float)jmaplogtolin (sliderFrequency->getValue(), 20.0, 22000.0); for (auto channel = 0; channel < 2; channel++) theFiltersNL[channel].setResonance ((float) sliderResonance->getValue()); theMoogFilter.setResonance ((float)jmaplogtolin (sliderResonance->getValue(), 0.01, 100.0)); theMoogFilter.setDrive (jmax (1.f, Decibels::decibelsToGain ((float)sliderGain->getValue()))); if (modulationType == Modulation_LFO_Square || modulationType == Modulation_LFO_Triangle) { theLFO.setType (modulationType == Modulation_LFO_Triangle ? LowFrequencyOscillator::lfoTriangle : LowFrequencyOscillator::lfoSquare); theLFO.setFrequency ((float) sliderLFOFrequency->getValue()); depthVolume.setValue ((float)sliderModulation->getValue() / 100.f); } else if (modulationType == Modulation_Envelope_Up || modulationType == Modulation_Envelope_Down) { theEnvelopeFollower.setAttackTime ((float)sliderEnvAttack->getValue()); theEnvelopeFollower.setReleaseTime ((float)sliderEnvRelease->getValue()); theEnvelopeFollower.setPreGain ((float)sliderEnvSens->getValue() - 50.0f); } theSlewFilter.setType (TPTFilter1stOrder::TypeLowPass); theSlewFilter.setCutoffFrequency (20.f); } //============================================================================== void SessionSevenComponent::timerCallback() { stopThread (1000); startThread(); } void SessionSevenComponent::run() { if (!(isActive)) return; // ------------------------------------------------------------------------- auto N = 2001; bufferData.setSize (3, N, false, false, true); if (threadShouldExit()) return; // ------------------------------------------------------------------------- auto *samples = bufferData.getWritePointer (0); for (auto i = 0; i < N; i++) samples[i] = i / (float)sampleRate * 1000.f; if (threadShouldExit()) return; // ------------------------------------------------------------------------- LowFrequencyOscillator theLFODisplay; theLFODisplay.setFrequency (100.0); theLFODisplay.setType (LowFrequencyOscillator::lfoSine); theLFODisplay.initProcessing (sampleRate); theLFODisplay.reset (7.f * float_Pi / 4.f); auto dataY = bufferData.getWritePointer (1); for (auto i = 0; i < N; i++) dataY[i] = theLFODisplay.getNextSample(); if (threadShouldExit()) return; // ------------------------------------------------------------------------- auto cutoffFrequency = jmaplintolog (jlimit (0.f, 1.f, lastEnvValue.load()), 20.f, 22000.f); auto Q = (float)sliderResonance->getValue(); auto drive = (float)Decibels::decibelsToGain (sliderGain->getValue()); auto model = comboModel->getSelectedId() - 1; if (model == Model_SVFNL_Naive) { SVFLowpassFilterNL theFilter; theFilter.setCutoffFrequency (cutoffFrequency); theFilter.setResonance (Q); theFilter.initProcessing (sampleRate); for (auto i = 0; i < N; i++) { auto result = drive * dataY[i]; result = theFilter.processSingleSampleRaw (result); dataY[i] = result; } } else if (model == Model_MoogFilter_JUCE) { dsp::LadderFilter<float> ladderFilter; ladderFilter.setMode (dsp::LadderFilter<float>::Mode::LPF24); ladderFilter.setDrive (jmax (1.f, (float)Decibels::decibelsToGain (sliderGain->getValue()))); ladderFilter.setCutoffFrequencyHz (cutoffFrequency); ladderFilter.setResonance ((float)jmaplogtolin (sliderResonance->getValue(), 0.01, 100.0)); ladderFilter.prepare ({ sampleRate, (uint32) N, 1u }); dsp::AudioBlock<float> inoutBlock (bufferData); inoutBlock = inoutBlock.getSingleChannelBlock (1); dsp::ProcessContextReplacing<float> context (inoutBlock); ladderFilter.process (context); } else if (model == Model_DiodeClipper_NewtonRaphson) { DiodeClipperADC18 diodeClipper; diodeClipper.setCutoffFrequency (cutoffFrequency); diodeClipper.initProcessing (sampleRate); for (auto i = 0; i < N; i++) { auto result = drive * dataY[i]; result = diodeClipper.processSingleSampleRaw (result); dataY[i] = result; } } // ------------------------------------------------------------------------- PlotComponent::Information information; information.minimumXValue = 0; information.maximumXValue = (N - 1.0) / sampleRate * 1000.0; information.gridXSize = 4.0; information.minimumYValue = -1.5; information.maximumYValue = 1.5; information.gridYSize = 0.25; information.displayGrid = true; information.strLabelX = "time (ms)"; information.strLabelY = "amplitude"; thePlotComponent->setInformation (information); // ------------------------------------------------------------------------- thePlotComponent->pushData (bufferData, N, 1); triggerAsyncUpdate(); } <file_sep>/Source/Sessions/Session5/SessionFiveComponent.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "../../SessionComponents.h" #include "../../Assets/PlotComponent.h" #include "../Session4/SessionFourDSP.h" #include "SessionFiveDSP.h" class SessionFiveComponent : public SessionComponent, public Slider::Listener, public ComboBox::Listener { public: //============================================================================== enum Smoothing { Smoothing_NoSmoothing = 0, Smoothing_Ballistics, Smoothing_BallisticsSmoothedValue, Smoothing_BallisticsSmoothedValueFilter, Smoothing_BallisticsSmoothedValueLinearSlewLimiting }; //============================================================================== SessionFiveComponent (AudioDeviceManager *adm); ~SessionFiveComponent(); //============================================================================== void paint (Graphics &g) override; void resized() override; //============================================================================== void sliderValueChanged (Slider *slider) override; void comboBoxChanged (ComboBox *combo) override; //============================================================================== void prepareToPlay (int samplesPerBlockExpected, double sampleRate) override; void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override; void releaseAudioResources() override; void reset() override; private: //============================================================================== void timerCallback() override; void run() override; //============================================================================== void updateProcessing(); void updateVisibility(); //============================================================================== struct DynamicsCompressorState { float thrlin, ratioinv; LinearSmoothedValue<float> makeupgain; BallisticsFilter ballisticsFilter; TPTFilter1stOrder slewFilter; LinearSlewLimiter slewLimiter; int smoothingAlgorithm; }; DynamicsCompressorState theCompressor; bool isActive = false; //============================================================================== ScopedPointer<PlotComponent> thePlotComponent; AudioBuffer<float> bufferData; //============================================================================== ScopedPointer<Slider> sliderThreshold, sliderRatio, sliderAttack, sliderRelease; ScopedPointer<Label> labelThreshold, labelRatio, labelAttack, labelRelease; ScopedPointer<ComboBox> comboSmoothingAlgorithm; ScopedPointer<Label> labelSmoothingAlgorithm; ScopedPointer<Slider> sliderSlewFreq, sliderSlewLinear; ScopedPointer<Label> labelSlewFreq, labelSlewLinear; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SessionFiveComponent) }; <file_sep>/Source/Sessions/Session6/SessionSixDSP.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "SessionSixDSP.h" //============================================================================== EnvelopeFollower::EnvelopeFollower() { prmGain.store (0.f); prmOutput.store (0.f); prmAttack.store (1.f); prmRelease.store (50.f); isActive = false; } EnvelopeFollower::~EnvelopeFollower() { } //============================================================================== void EnvelopeFollower::setPreGain (float gaindB) { prmGain.store (jlimit (-200.f, 100.f, gaindB)); mustUpdateProcessing = true; } void EnvelopeFollower::setVolume (float volumedB) { prmOutput.store (jlimit (-200.f, 100.f, volumedB)); mustUpdateProcessing = true; } void EnvelopeFollower::setAttackTime (float attackTimeMs) { prmAttack.store (jlimit (0.001f, 1000.f, attackTimeMs)); mustUpdateProcessing = true; } void EnvelopeFollower::setReleaseTime (float releaseTimeMs) { prmRelease.store (jlimit (10.f, 50000.f, releaseTimeMs)); mustUpdateProcessing = true; } //============================================================================== void EnvelopeFollower::initProcessing (double sR) { jassert (sR > 0); sampleRate = sR; theBallisticsFilter.initProcessing (sR); updateProcessing(); reset(); isActive = true; } void EnvelopeFollower::reset (float zeroValue) { gainVolume.reset (sampleRate, 0.05); outputVolume.reset (sampleRate, 0.05); theBallisticsFilter.reset (zeroValue); } float EnvelopeFollower::processSingleSample (float sample) { if (mustUpdateProcessing) updateProcessing(); auto output = sample * gainVolume.getNextValue(); output = std::abs (output); output = theBallisticsFilter.processSingleSample (output); output = jlimit (0.f, 1.f, output * outputVolume.getNextValue()); return output; } void EnvelopeFollower::updateProcessing() { mustUpdateProcessing = false; theBallisticsFilter.setAttackTime (prmAttack.load()); theBallisticsFilter.setReleaseTime (prmRelease.load()); gainVolume.setValue (Decibels::decibelsToGain (prmGain.load(), -200.f)); outputVolume.setValue (Decibels::decibelsToGain (prmOutput.load(), -200.f)); } <file_sep>/Source/MainComponent.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "MainComponent.h" // You need to include all the session components headers you need there #include "./Sessions/Session1/SessionOneComponent.h" #include "./Sessions/Session3/SessionThreeComponent.h" #include "./Sessions/Session4/SessionFourComponent.h" #include "./Sessions/Session5/SessionFiveComponent.h" #include "./Sessions/Session6/SessionSixComponent.h" #include "./Sessions/Session7/SessionSevenComponent.h" //============================================================================== MainComponent::MainComponent() : thread ("audio file buffering") { // ------------------------------------------------------------------------- // Here is the place where we add the session components theSessionComponents.add (new SessionOneComponent (&deviceManager)); theSessionComponents.add (new SessionThreeComponent (&deviceManager)); theSessionComponents.add (new SessionFourComponent (&deviceManager)); theSessionComponents.add (new SessionFiveComponent (&deviceManager)); theSessionComponents.add (new SessionSixComponent (&deviceManager)); theSessionComponents.add (new SessionSevenComponent (&deviceManager)); theSessionComponents.add (new SettingsComponent (&deviceManager)); for (auto i = 0; i < theSessionComponents.size(); i++) addChildComponent (theSessionComponents[i]); // -------------------------------------------------------------------------------- setLookAndFeel (&theLF); // -------------------------------------------------------------------------------- addAndMakeVisible (buttonPlay = new TextButton ("Play")); buttonPlay->addListener (this); buttonPlay->setConnectedEdges (Button::ConnectedOnRight); addAndMakeVisible (buttonStop = new TextButton ("Stop")); buttonStop->addListener (this); buttonStop->setConnectedEdges (Button::ConnectedOnLeft); // -------------------------------------------------------------------------------- addAndMakeVisible (comboAudioFiles = new ComboBox()); comboAudioFiles->addListener (this); fileListAudio = FileSystem::getAudioList(); for (auto i = 0; i < fileListAudio.size(); i++) comboAudioFiles->addItem (fileListAudio[i].getFileNameWithoutExtension(), i + 1); comboAudioFiles->setSelectedId (1, dontSendNotification); // ------------------------------------------------------------------------- addAndMakeVisible (listDemos = new ListBox()); listDemos->setModel (this); listDemos->setColour (ListBox::backgroundColourId, Colour::greyLevel (0.2f)); // ------------------------------------------------------------------------- formatManager.registerBasicFormats(); thread.startThread (3); currentAudioFileSource = nullptr; // ------------------------------------------------------------------------- addAndMakeVisible (theThumbComponent = new AudioThumbnailComponent (deviceManager, formatManager)); theThumbComponent->setTransportSource (&transportSource); // ------------------------------------------------------------------------- // Here is the place where we set the session component we want to see at startup listDemos->selectRow (0); setAudioChannels (0, 2); setSize (920, 600); } MainComponent::~MainComponent() { releaseResources(); shutdownAudio(); setLookAndFeel (nullptr); } //============================================================================== void MainComponent::prepareToPlay (int samplesPerBlockExpected, double sampleRate) { transportSource.prepareToPlay (samplesPerBlockExpected, sampleRate); for (auto i = 0; i < theSessionComponents.size(); i++) theSessionComponents[i]->prepareToPlay (samplesPerBlockExpected, sampleRate); } void MainComponent::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) { // ----------------------------------------------------------------------------- bufferToFill.clearActiveBufferRegion(); transportSource.getNextAudioBlock (bufferToFill); // ----------------------------------------------------------------------------- const int index = listDemos->getSelectedRow(); theSessionComponents[index]->getNextAudioBlock (bufferToFill); } void MainComponent::releaseResources() { transportSource.stop(); transportSource.releaseResources(); for (auto i = 0; i < theSessionComponents.size(); i++) theSessionComponents[i]->releaseAudioResources(); } void MainComponent::loadAudioFile (File fileAudio) { // unload the previous file source and delete it.. transportSource.stop(); transportSource.setSource (nullptr); currentAudioFileSource = nullptr; AudioFormatReader* reader = formatManager.createReaderFor (fileAudio); if (reader != nullptr) { currentAudioFileSource = new AudioFormatReaderSource (reader, true); currentAudioFileSource->setLooping (true); // ..and plug it into our transport source transportSource.setSource (currentAudioFileSource, 32768, // tells it to buffer this many samples ahead &thread, // this is the background thread to use for reading-ahead reader->sampleRate, // allows for sample rate correction 2); // for stereo URL theURL = URL (File (fileAudio)); theThumbComponent->setCurrentURL (theURL); } } void MainComponent::setAudioChannels (int numInputChannels, int numOutputChannels, const XmlElement* const xml) { String audioError = deviceManager.initialise (numInputChannels, numOutputChannels, xml, true); jassert (audioError.isEmpty()); deviceManager.addAudioCallback (&audioSourcePlayer); audioSourcePlayer.setSource (this); if (fileListAudio.size() > 0) loadAudioFile (fileListAudio[0]); } void MainComponent::shutdownAudio() { transportSource.stop(); thread.stopThread (1000); audioSourcePlayer.setSource (nullptr); transportSource.setSource (nullptr); deviceManager.removeAudioCallback (&audioSourcePlayer); deviceManager.closeAudioDevice(); } //============================================================================== void MainComponent::paint (Graphics& g) { g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId).brighter()); } void MainComponent::resized() { Rectangle<int> rect = getLocalBounds(); if (rect.getWidth() > 600) { listDemos->setBounds (rect.removeFromLeft (210)); listDemos->setRowHeight (20); } else { listDemos->setBounds (rect.removeFromLeft (130)); listDemos->setRowHeight (30); } auto fullRect = rect; auto rectTop = rect.removeFromTop (100); rectTop.reduce (10, 10); comboAudioFiles->setBounds (rectTop.removeFromTop (40).withWidth (200).withSizeKeepingCentre (200,24)); buttonPlay->setBounds (rectTop.withWidth (100).withSizeKeepingCentre (100, 24)); buttonStop->setBounds (buttonPlay->getBounds().translated (100, 0)); for (auto i = 0; i < theSessionComponents.size(); i++) theSessionComponents[i]->setBounds (i >= theSessionComponents.size() - 2 ? fullRect : rect); auto rectThumb = fullRect.reduced (10, 10); rectThumb.removeFromLeft (210); rectThumb = rectThumb.removeFromTop (80); theThumbComponent->setBounds (rectThumb); } //============================================================================== int MainComponent::getNumRows() { return theSessionComponents.size(); } void MainComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected) { if (rowIsSelected) g.fillAll (Colours::deepskyblue); g.setFont (Font (13)); g.setColour (Colours::white); g.drawText (theSessionComponents[rowNumber]->getName(), 0, 0, width, height, Justification::centredLeft); } void MainComponent::selectedRowsChanged (int lastRowSelected) { for (auto i = 0; i < theSessionComponents.size(); i++) theSessionComponents[i]->setVisible (i == lastRowSelected); buttonPlay->setVisible (lastRowSelected < theSessionComponents.size() - 2); buttonStop->setVisible (lastRowSelected < theSessionComponents.size() - 2); comboAudioFiles->setVisible (lastRowSelected < theSessionComponents.size() - 2); theThumbComponent->setVisible (lastRowSelected < theSessionComponents.size() - 2); if (lastRowSelected >= theSessionComponents.size() - 2) { transportSource.stop(); } } void MainComponent::buttonClicked (Button *button) { if (button == buttonPlay) { transportSource.setLooping (true); transportSource.start(); } else if (button == buttonStop) { transportSource.stop(); transportSource.setPosition (0.0); } } void MainComponent::comboBoxChanged (ComboBox *combo) { if (combo == comboAudioFiles) { const int index = comboAudioFiles->getSelectedId() - 1; File fileAudio = fileListAudio[index]; loadAudioFile (fileAudio); } } <file_sep>/Source/Sessions/Session6/SessionSixDSP.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "../Session4/SessionFourDSP.h" #include "../Session5/SessionFiveDSP.h" class EnvelopeFollower { public: //============================================================================== /** Constructor. */ EnvelopeFollower(); /** Destructor. */ ~EnvelopeFollower(); //============================================================================== /** Inits the processing by providing the sample rate. */ void initProcessing (double sampleRate); /** Resets the filter state. */ void reset (float zeroValue = 0.f); /** Processes one sample. */ float processSingleSample (float sample); //============================================================================== /** Sets a volume to apply before any processing to the sidechain signal. */ void setPreGain (float gaindB); /** Sets a volume to apply to the signal after processing */ void setVolume (float volumedB); /** Sets the attack time in the ballistics filter. */ void setAttackTime (float attackTimeMs); /** Sets the release time in the ballistics filter. */ void setReleaseTime (float releaseTimeMs); private: //============================================================================== /** @internal */ void updateProcessing(); //============================================================================== double sampleRate; bool mustUpdateProcessing, isActive; //============================================================================== std::atomic<float> prmGain, prmOutput; std::atomic<float> prmAttack, prmRelease; //============================================================================== BallisticsFilter theBallisticsFilter; LinearSmoothedValue<float> gainVolume, outputVolume; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EnvelopeFollower) }; <file_sep>/Source/Sessions/Session6/SessionSixComponent.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "../../SessionComponents.h" #include "../../Assets/PlotComponent.h" #include "SessionSixDSP.h" #include "../../Assets/LowFrequencyOscillator.h" class SessionSixComponent : public SessionComponent, public Slider::Listener, public ComboBox::Listener { public: //============================================================================== enum ModulationType { Modulation_None = 0, Modulation_LFO_Triangle, Modulation_LFO_Square, Modulation_Envelope_Up, Modulation_Envelope_Down }; enum StructureType { Structure_TDF2 = 0, Structure_TDF2_Smoothing, Structure_TPT, Structure_TPT_Smoothing }; //============================================================================== SessionSixComponent (AudioDeviceManager *adm); ~SessionSixComponent(); //============================================================================== void paint (Graphics &g) override; void resized() override; //============================================================================== void sliderValueChanged (Slider *slider) override; void comboBoxChanged (ComboBox *combo) override; //============================================================================== void prepareToPlay (int samplesPerBlockExpected, double sampleRate) override; void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override; void releaseAudioResources() override; void reset() override; private: //============================================================================== void timerCallback() override; void run() override; void updateVisibility(); //============================================================================== void updateProcessing(); //============================================================================== AudioBuffer<float> bufferModulation; LowFrequencyOscillator theLFO; LinearSmoothedValue<float> depthVolume; EnvelopeFollower theEnvelopeFollower; TPTFilter1stOrder theSlewFilter; //============================================================================== struct FilterStateTPT { float s1, s2; // state variable for TPT }; struct FilterStateTDF2 { float v1, v2; // state variable for TDF2 }; FilterStateTDF2 theFiltersTDF2[2]; FilterStateTPT theFiltersTPT[2]; bool isActive = false; std::atomic<float> lastEnvValue; int modulationType, algorithmType; bool isSmoothing; float centralFreq, R2; //============================================================================== ScopedPointer<PlotComponent> thePlotComponent; AudioBuffer<float> bufferData; //============================================================================== ScopedPointer<Slider> sliderFrequency, sliderResonance, sliderModulation; ScopedPointer<ComboBox> comboAlgorithm, comboModulationType; ScopedPointer<Slider> sliderLFOFrequency, sliderEnvAttack, sliderEnvRelease, sliderEnvSens; ScopedPointer<Label> labelFrequency, labelResonance, labelModulation; ScopedPointer<Label> labelAlgorithm, labelModulationType; ScopedPointer<Label> labelLFOFrequency, labelEnvAttack, labelEnvRelease, labelEnvSens; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SessionSixComponent) }; <file_sep>/Source/Assets/AudioThumbnailComponent.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" //============================================================================== class AudioThumbnailComponent : public Component, public ChangeBroadcaster, private ChangeListener, private Timer { public: AudioThumbnailComponent (AudioDeviceManager& adm, AudioFormatManager& afm) : audioDeviceManager (adm), thumbnailCache (5), thumbnail (128, afm, thumbnailCache) { thumbnail.addChangeListener (this); } ~AudioThumbnailComponent() { thumbnail.removeChangeListener (this); } void paint (Graphics& g) override { g.fillAll (Colour (0xff495358)); g.setColour (Colours::white); if (thumbnail.getTotalLength() > 0.0) { thumbnail.drawChannels (g, getLocalBounds().reduced (2), 0.0, thumbnail.getTotalLength(), 1.0f); g.setColour (Colours::black); g.fillRect (static_cast<float> (currentPosition * getWidth()), 0.0f, 1.0f, static_cast<float> (getHeight())); } else { g.drawFittedText ("No audio file loaded.\nDrop a file here or click the \"Load File...\" button.", getLocalBounds(), Justification::centred, 2); } } void setCurrentURL (const URL& u) { if (currentURL == u) return; loadURL (u); } URL getCurrentURL() { return currentURL; } void setTransportSource (AudioTransportSource* newSource) { transportSource = newSource; struct ResetCallback : public CallbackMessage { ResetCallback (AudioThumbnailComponent& o) : owner (o) {} void messageCallback() override { owner.reset(); } AudioThumbnailComponent& owner; }; (new ResetCallback (*this))->post(); } private: AudioDeviceManager& audioDeviceManager; AudioThumbnailCache thumbnailCache; AudioThumbnail thumbnail; AudioTransportSource* transportSource = nullptr; URL currentURL; double currentPosition = 0.0; //============================================================================== void changeListenerCallback (ChangeBroadcaster*) override { repaint(); } void reset() { currentPosition = 0.0; repaint(); if (transportSource == nullptr) stopTimer(); else startTimerHz (25); } void loadURL (const URL& u, bool notify = false) { if (currentURL == u) return; currentURL = u; InputSource* inputSource = nullptr; #if ! JUCE_IOS if (u.isLocalFile()) { inputSource = new FileInputSource (u.getLocalFile()); } else #endif { if (inputSource == nullptr) inputSource = new URLInputSource (u); } thumbnail.setSource (inputSource); if (notify) sendChangeMessage(); } void timerCallback() override { if (transportSource != nullptr) { currentPosition = transportSource->getCurrentPosition() / thumbnail.getTotalLength(); repaint(); } } void mouseDrag (const MouseEvent& e) override { if (transportSource != nullptr) { const ScopedLock sl (audioDeviceManager.getAudioCallbackLock()); transportSource->setPosition ((jmax (static_cast<double> (e.x), 0.0) / getWidth()) * thumbnail.getTotalLength()); } } }; <file_sep>/Source/Assets/StringFunctions.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" //============================================================================== struct StringFunctions { template<typename FloatType> static const String getIdealRepresentationForNumber (FloatType value, FloatType reference) { auto intNumber = roundToInt (std::floor (value)); auto fracNumber = value - intNumber; if (fracNumber == (FloatType) 0.0) return String (roundToInt (value)); else if (std::abs (1 - intNumber / value) < (FloatType) 1e-5) return String (roundToInt (value)); else if (std::abs (value) * 100 < std::abs (reference) && std::abs (value) < 1 && reference != -1) return "0"; else if (std::abs (value) <= (FloatType) 1e-5) { String strResult = String (value).replace ("e0", "e").replace ("e-0", "e-"); return strResult; } else return String (value, 6).trimCharactersAtEnd ("0").trimCharactersAtEnd ("."); } static const double getValueFromStringWithUnits (String strValue) { String strNumber, strUnit; strValue = strValue.toLowerCase(); strNumber = strValue.retainCharacters ("0123456789.-"); strUnit = strValue.retainCharacters ("abcdefghijklmnopqrstuvwxyz"); auto result = strNumber.getDoubleValue(); if (strUnit.compare ("k") == 0) result *= 1e3; else if (strUnit.compare ("meg") == 0) result *= 1e6; else if (strUnit.compare ("g") == 0) result *= 1e9; else if (strUnit.compare ("t") == 0) result *= 1e12; else if (strUnit.compare ("m") == 0) result *= 1e-3; else if (strUnit.compare ("u") == 0) result *= 1e-6; else if (strUnit.compare ("n") == 0) result *= 1e-9; else if (strUnit.compare ("p") == 0) result *= 1e-12; else if (strUnit.compare ("f") == 0) result *= 1e-15; return result; } static const String getStringWithUnitsFromValue (double value, int numDecimals = 7) { String strResult; if (numDecimals <= 0) { if (std::abs (value) >= 1e12) strResult = String (roundToInt (value / 1e12)); else if (std::abs (value) >= 1e9) strResult = String (roundToInt (value / 1e9)); else if (std::abs (value) >= 1e6) strResult = String (roundToInt (value / 1e6)); else if (std::abs (value) >= 1e3) strResult = String (roundToInt (value / 1e3)); else if (std::abs (value) >= 1e0) strResult = String (roundToInt (value / 1e0)); else if (std::abs (value) >= 1e-3) strResult = String (roundToInt (value / 1e-3)); else if (std::abs (value) >= 1e-6) strResult = String (roundToInt (value / 1e-6)); else if (std::abs (value) >= 1e-9) strResult = String (roundToInt (value / 1e-9)); else if (std::abs (value) >= 1e-12) strResult = String (roundToInt (value / 1e-12)); else if (std::abs (value) >= 1e-15) strResult = String (roundToInt (value / 1e-15)); } else { auto valueUnit = 1.0; if (std::abs (value) >= 1e12) valueUnit = value / 1e12; else if (std::abs (value) >= 1e9) valueUnit = value / 1e9; else if (std::abs (value) >= 1e6) valueUnit = value / 1e6; else if (std::abs (value) >= 1e3) valueUnit = value / 1e3; else if (std::abs (value) >= 1e0) valueUnit = value / 1e0; else if (std::abs (value) >= 1e-3) valueUnit = value / 1e-3; else if (std::abs (value) >= 1e-6) valueUnit = value / 1e-6; else if (std::abs (value) >= 1e-9) valueUnit = value / 1e-9; else if (std::abs (value) >= 1e-12) valueUnit = value / 1e-12; else if (std::abs (value) >= 1e-15) valueUnit = value / 1e-15; strResult = String (valueUnit, numDecimals); } if (strResult.indexOf (".") != -1) { strResult = strResult.trimCharactersAtEnd ("0"); strResult = strResult.trimCharactersAtEnd ("."); } if (std::abs (value) >= 1e12) strResult += "T"; else if (std::abs (value) >= 1e9) strResult += "G"; else if (std::abs (value) >= 1e6) strResult += "Meg"; else if (std::abs (value) >= 1e3) strResult += "k"; else if (std::abs (value) >= 1e0) strResult += ""; else if (std::abs (value) >= 1e-3) strResult += "m"; else if (std::abs (value) >= 1e-6) strResult += "u"; else if (std::abs (value) >= 1e-9) strResult += "n"; else if (std::abs (value) >= 1e-12) strResult += "p"; else if (std::abs (value) >= 1e-15) strResult += "f"; return strResult; } }; <file_sep>/Source/Sessions/Session1/SessionOneDSP.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" class SessionOneDSP { public: //============================================================================== SessionOneDSP() {} ~SessionOneDSP() {} //============================================================================== enum FilterType { Type_LowPass1 = 0, Type_HighPass1, Type_LowPass2, Type_BandPass2, Type_HighPass2, Type_Peak }; //============================================================================== static const void calculusCoefficients (float frequency, float Q, float gain, int type, double sampleRate, float &b0, float &b1, float &b2, float &a1, float &a2); static const double getMagnitudeForFrequency (double frequency, double sampleRate, const float b0, const float b1, const float b2, const float a1, const float a2); static const double getPhaseForFrequency (double frequency, double sampleRate, const float b0, const float b1, const float b2, const float a1, const float a2); //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SessionOneDSP) }; <file_sep>/Source/Sessions/Session6/SessionSixComponent.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "SessionSixComponent.h" #include "../Session1/SessionOneDSP.h" #include "../Session2/SessionTwoDSP.h" #include "../Session3/SessionThreeDSP.h" #include "../../Assets/MathFunctions.h" //============================================================================== SessionSixComponent::SessionSixComponent (AudioDeviceManager *adm) : SessionComponent ("Filters", adm) { // ------------------------------------------------------------------------- addAndMakeVisible (thePlotComponent = new PlotComponent()); // ------------------------------------------------------------------------- addAndMakeVisible (sliderFrequency = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderFrequency->setRange (20.0, 22000.0); sliderFrequency->setSkewFactor (0.2); sliderFrequency->setValue (1000.0, dontSendNotification); sliderFrequency->addListener (this); addAndMakeVisible (sliderResonance = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderResonance->setRange (0.01, 100.0); sliderResonance->setDoubleClickReturnValue (true, 1.0 / std::sqrt (2.0)); sliderResonance->setSkewFactor (0.1); sliderResonance->setValue (1.0 / std::sqrt (2.0), dontSendNotification); sliderResonance->addListener (this); addAndMakeVisible (sliderModulation = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderModulation->setRange (0.0, 100.0); sliderModulation->setDoubleClickReturnValue (true, 50.0); sliderModulation->setValue (50.0, dontSendNotification); sliderModulation->addListener (this); addAndMakeVisible (sliderLFOFrequency = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderLFOFrequency->setRange (0.01, 20.0); sliderLFOFrequency->setDoubleClickReturnValue (true, 1.0); sliderLFOFrequency->setSkewFactor (0.1); sliderLFOFrequency->setValue (1.0, dontSendNotification); sliderLFOFrequency->addListener (this); addAndMakeVisible (sliderEnvAttack = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderEnvAttack->setRange (0.1, 1000.0); sliderEnvAttack->setSkewFactor (0.2); sliderEnvAttack->setValue (0.1, dontSendNotification); sliderEnvAttack->addListener (this); addAndMakeVisible (sliderEnvRelease = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderEnvRelease->setRange (10.0, 10000.0); sliderEnvRelease->setSkewFactor (0.2); sliderEnvRelease->setValue (50.0, dontSendNotification); sliderEnvRelease->addListener (this); addAndMakeVisible (sliderEnvSens = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderEnvSens->setRange (0.0, 100.0); sliderEnvSens->setDoubleClickReturnValue (true, 50.0); sliderEnvSens->setValue (50.0, dontSendNotification); sliderEnvSens->addListener (this); // ------------------------------------------------------------------------- addAndMakeVisible (comboAlgorithm = new ComboBox()); comboAlgorithm->addSectionHeading ("Transposed Direct Form 2"); comboAlgorithm->addItem ("TDF2", 1); comboAlgorithm->addItem ("TDF2 + smoothing", 2); comboAlgorithm->addSectionHeading ("Topology preserving transform"); comboAlgorithm->addItem ("TPT", 3); comboAlgorithm->addItem ("TPT + smoothing", 4); comboAlgorithm->addListener (this); comboAlgorithm->setSelectedId (1, dontSendNotification); // ------------------------------------------------------------------------- addAndMakeVisible (comboModulationType = new ComboBox()); comboModulationType->addItemList ({ "None", "LFO Triangle", "LFO Square", "Env. Up", "Env. Down" }, 1); comboModulationType->addListener (this); comboModulationType->setSelectedId (1, dontSendNotification); // ------------------------------------------------------------------------- addAndMakeVisible (labelFrequency = new Label ("", "Frequency")); labelFrequency->setJustificationType (Justification::centred); labelFrequency->attachToComponent (sliderFrequency, false); addAndMakeVisible (labelResonance = new Label ("", "Resonance")); labelResonance->setJustificationType (Justification::centred); labelResonance->attachToComponent (sliderResonance, false); addAndMakeVisible (labelModulation = new Label ("", "Depth")); labelModulation->setJustificationType (Justification::centred); labelModulation->attachToComponent (sliderModulation, false); addAndMakeVisible (labelLFOFrequency = new Label ("", "LFO freq.")); labelLFOFrequency->setJustificationType (Justification::centred); labelLFOFrequency->attachToComponent (sliderLFOFrequency, false); addAndMakeVisible (labelEnvAttack = new Label ("", "Attack")); labelEnvAttack->setJustificationType (Justification::centred); labelEnvAttack->attachToComponent (sliderEnvAttack, false); addAndMakeVisible (labelEnvRelease = new Label ("", "Release")); labelEnvRelease->setJustificationType (Justification::centred); labelEnvRelease->attachToComponent (sliderEnvRelease, false); addAndMakeVisible (labelEnvSens = new Label ("", "Sensitivity")); labelEnvSens->setJustificationType (Justification::centred); labelEnvSens->attachToComponent (sliderEnvSens, false); addAndMakeVisible (labelAlgorithm = new Label ("", "Structure")); labelAlgorithm->setJustificationType (Justification::centred); labelAlgorithm->attachToComponent (comboAlgorithm, false); addAndMakeVisible (labelModulationType = new Label ("", "Modulation Type")); labelModulationType->setJustificationType (Justification::centred); // ------------------------------------------------------------------------- lastEnvValue.store (0.5f); // ------------------------------------------------------------------------- updateVisibility(); triggerAsyncUpdate(); } SessionSixComponent::~SessionSixComponent() { } void SessionSixComponent::paint (Graphics &g) { auto rect = getLocalBounds(); g.setColour (Colours::white); g.fillRect (rect.removeFromTop (getHeight() - 170)); g.setColour (getLookAndFeel().findColour (ResizableWindow::backgroundColourId)); g.fillRect (rect); } void SessionSixComponent::resized() { Rectangle<int> rect = getLocalBounds(); auto rectTop = rect.removeFromTop (getHeight() - 170); thePlotComponent->setBounds (rectTop.reduced (10, 10)); rect.removeFromTop (40); auto rectMid = rect.removeFromTop (100).reduced (10, 0); comboAlgorithm->setBounds (rectMid.withWidth (160).withSizeKeepingCentre (160, 24).translated (0, -28)); comboModulationType->setBounds (rectMid.withWidth (160).withSizeKeepingCentre (160, 24).translated (0, 28)); labelModulationType->setBounds (rectMid.withWidth (160).withSizeKeepingCentre (160, 24).translated (0, 52)); sliderFrequency->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200, 0)); sliderResonance->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 100, 0)); sliderModulation->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 200, 0)); sliderLFOFrequency->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 300, 0)); sliderEnvAttack->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 200, 0)); sliderEnvRelease->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 300, 0)); sliderEnvSens->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 400, 0)); } //============================================================================== void SessionSixComponent::sliderValueChanged (Slider *slider) { if (slider == sliderFrequency || slider == sliderResonance) { mustUpdateProcessing = true; } else if (slider == sliderModulation || slider == sliderLFOFrequency) { mustUpdateProcessing = true; } else if (slider == sliderEnvAttack || slider == sliderEnvRelease || slider == sliderEnvSens) { mustUpdateProcessing = true; } } void SessionSixComponent::comboBoxChanged (ComboBox *combo) { if (combo == comboAlgorithm) { mustUpdateProcessing = true; } else if (combo == comboModulationType) { mustUpdateProcessing = true; updateVisibility(); } } void SessionSixComponent::updateVisibility() { auto modulation = comboModulationType->getSelectedId() - 1; labelModulation->setVisible (modulation == Modulation_LFO_Square || modulation == Modulation_LFO_Triangle); labelLFOFrequency->setVisible (modulation == Modulation_LFO_Square || modulation == Modulation_LFO_Triangle); sliderModulation->setVisible (modulation == Modulation_LFO_Square || modulation == Modulation_LFO_Triangle); sliderLFOFrequency->setVisible (modulation == Modulation_LFO_Square || modulation == Modulation_LFO_Triangle); labelEnvAttack->setVisible (modulation == Modulation_Envelope_Up || modulation == Modulation_Envelope_Down); labelEnvRelease->setVisible (modulation == Modulation_Envelope_Up || modulation == Modulation_Envelope_Down); labelEnvSens->setVisible (modulation == Modulation_Envelope_Up || modulation == Modulation_Envelope_Down); sliderEnvAttack->setVisible (modulation == Modulation_Envelope_Up || modulation == Modulation_Envelope_Down); sliderEnvRelease->setVisible (modulation == Modulation_Envelope_Up || modulation == Modulation_Envelope_Down); sliderEnvSens->setVisible (modulation == Modulation_Envelope_Up || modulation == Modulation_Envelope_Down); } //============================================================================== void SessionSixComponent::prepareToPlay (int samplesPerBlockExpected, double sR) { SessionComponent::prepareToPlay (samplesPerBlockExpected, sR); bufferModulation.setSize (1, samplesPerBlockExpected); theLFO.initProcessing (sR); theEnvelopeFollower.initProcessing (sR); theSlewFilter.initProcessing (sR); updateProcessing(); reset(); isActive = true; } void SessionSixComponent::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) { if (mustUpdateProcessing) updateProcessing(); ScopedNoDenormals noDenormals; auto startSample = bufferToFill.startSample; auto numSamples = bufferToFill.numSamples; auto numChannels = jmax (2, bufferToFill.buffer->getNumChannels()); jassert (numSamples > 0); jassert (numChannels > 0); auto *envSamples = bufferModulation.getWritePointer (0); for (auto i = 0; i < numSamples; i++) envSamples[i] = centralFreq; if (modulationType == Modulation_LFO_Square || modulationType == Modulation_LFO_Triangle) { for (auto i = 0; i < numSamples; i++) envSamples[i] += theLFO.getNextSample() * depthVolume.getNextValue(); } else if (modulationType == Modulation_Envelope_Up || modulationType == Modulation_Envelope_Down) { for (auto i = 0; i < numSamples; i++) { auto input = 0.f; for (auto channel = 0; channel < numChannels; channel++) input += bufferToFill.buffer->getSample (channel, startSample + i); input /= (float)numChannels; envSamples[i] += theEnvelopeFollower.processSingleSample (input) * (modulationType == Modulation_Envelope_Down ? -1.f : 1.f); } } if (isSmoothing) { for (auto i = 0; i < numSamples; i++) envSamples[i] = theSlewFilter.processSingleSampleRaw (envSamples[i]); } for (auto i = 0; i < numSamples; i++) envSamples[i] = jlimit (0.f, 1.f, envSamples[i]); lastEnvValue.store (envSamples[numSamples - 1]); if (algorithmType == Structure_TDF2 || algorithmType == Structure_TDF2_Smoothing) { for (auto channel = 0; channel < numChannels; channel++) { float b0, b1, b2, a1, a2; auto *samples = bufferToFill.buffer->getWritePointer (channel); auto v1 = theFiltersTDF2[channel].v1; auto v2 = theFiltersTDF2[channel].v2; for (auto i = 0; i < numSamples; i++) { auto input = samples[i + startSample]; auto frequency = jmaplintolog (envSamples[i], 20.f, 22000.f); SessionOneDSP::calculusCoefficients (frequency, (float)sliderResonance->getValue(), 0.f, SessionOneDSP::Type_LowPass2, sampleRate, b0, b1, b2, a1, a2); auto output = b0 * input + v1; v1 = b1 * input + v2 - a1 * output; v2 = b2 * input - a2 * output; samples[i + startSample] = output; } theFiltersTDF2[channel].v1 = v1; theFiltersTDF2[channel].v2 = v2; } } else { for (auto channel = 0; channel < numChannels; channel++) { float g, h; auto *samples = bufferToFill.buffer->getWritePointer (channel); auto s1 = theFiltersTPT[channel].s1; auto s2 = theFiltersTPT[channel].s2; for (auto i = 0; i < numSamples; i++) { auto input = samples[i + startSample]; auto frequency = jmaplintolog (envSamples[i], 20.f, 22000.f); g = std::tan (float_Pi * frequency / (float)sampleRate); h = 1.f / (1 + R2 * g + g * g); auto yH = (input - s1 * (R2 + g) - s2) * h; auto yB = g * yH + s1; auto yL = g * yB + s2; s1 = g * yH + yB; s2 = g * yB + yL; samples[i + startSample] = yL; } theFiltersTPT[channel].s1 = s1; theFiltersTPT[channel].s2 = s2; } } } void SessionSixComponent::releaseAudioResources() { reset(); } void SessionSixComponent::reset() { for (auto channel = 0; channel < 2; channel++) { theFiltersTDF2[channel].v1 = 0; theFiltersTDF2[channel].v2 = 0; theFiltersTPT[channel].s1 = 0; theFiltersTPT[channel].s2 = 0; } theLFO.reset(); depthVolume.reset (sampleRate, 0.05); theEnvelopeFollower.reset(); theSlewFilter.reset(); } void SessionSixComponent::updateProcessing() { mustUpdateProcessing = false; algorithmType = comboAlgorithm->getSelectedId() - 1; modulationType = comboModulationType->getSelectedId() - 1; centralFreq = (float)jmaplogtolin (sliderFrequency->getValue(), 20.0, 22000.0); R2 = 1.f / (float) sliderResonance->getValue(); if (modulationType == Modulation_LFO_Square || modulationType == Modulation_LFO_Triangle) { theLFO.setType (modulationType == Modulation_LFO_Triangle ? LowFrequencyOscillator::lfoTriangle : LowFrequencyOscillator::lfoSquare); theLFO.setFrequency ((float) sliderLFOFrequency->getValue()); depthVolume.setValue ((float)sliderModulation->getValue() / 100.f); } else if (modulationType == Modulation_Envelope_Up || modulationType == Modulation_Envelope_Down) { theEnvelopeFollower.setAttackTime ((float)sliderEnvAttack->getValue()); theEnvelopeFollower.setReleaseTime ((float)sliderEnvRelease->getValue()); theEnvelopeFollower.setPreGain ((float)sliderEnvSens->getValue() - 50.0f); } theSlewFilter.setType (TPTFilter1stOrder::TypeLowPass); theSlewFilter.setCutoffFrequency (20.f); isSmoothing = (algorithmType == Structure_TDF2_Smoothing || algorithmType == Structure_TPT_Smoothing); } //============================================================================== void SessionSixComponent::timerCallback() { stopThread (1000); startThread(); } void SessionSixComponent::run() { if (!(isActive)) return; // ------------------------------------------------------------------------- auto N = 1001; bufferData.setSize (2, N, false, false, true); if (threadShouldExit()) return; // ------------------------------------------------------------------------- float b0D, b1D, b2D, a1D, a2D; auto cutoffFrequency = jmaplintolog (jlimit (0.f, 1.f, lastEnvValue.load()), 20.f, 22000.f); SessionOneDSP::calculusCoefficients (cutoffFrequency, (float)sliderResonance->getValue(), 0.f, SessionOneDSP::Type_LowPass2, sampleRate, b0D, b1D, b2D, a1D, a2D); if (threadShouldExit()) return; // ------------------------------------------------------------------------- auto *dataX = bufferData.getWritePointer (0); auto *dataYD = bufferData.getWritePointer (1); for (auto i = 0; i < N; i++) { auto frequency = jmaplintolog (i / (N - 1.0), 10.0, 22000.0); auto magnitudeD = SessionOneDSP::getMagnitudeForFrequency (frequency, sampleRate, b0D, b1D, b2D, a1D, a2D); dataX[i] = (float)frequency; dataYD[i] = (float)Decibels::gainToDecibels (magnitudeD); if (threadShouldExit()) return; } // ------------------------------------------------------------------------- PlotComponent::Information information; information.minimumXValue = 10.0; information.maximumXValue = 22000.0; information.isXAxisLogarithmic = true; information.minimumYValue = -80.0; information.maximumYValue = 40.0; information.gridYSize = 10.0; information.displayGrid = true; information.strLabelX = "frequency (Hz)"; information.strLabelY = "magnitude (dB)"; thePlotComponent->setInformation (information); // ------------------------------------------------------------------------- thePlotComponent->pushData (bufferData, N, 1); triggerAsyncUpdate(); } <file_sep>/Source/Sessions/Session3/SessionThreeComponent.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "SessionThreeComponent.h" #include "../Session1/SessionOneDSP.h" #include "../Session2/SessionTwoDSP.h" #include "SessionThreeDSP.h" #include "../../Assets/MathFunctions.h" //============================================================================== SessionThreeComponent::SessionThreeComponent (AudioDeviceManager *adm) : SessionComponent ("Frequency warping", adm) { // ------------------------------------------------------------------------- addAndMakeVisible (thePlotComponent = new PlotComponent()); // ------------------------------------------------------------------------- addAndMakeVisible (sliderFrequency = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderFrequency->setRange (20.0, 22000.0); sliderFrequency->setSkewFactor (0.2); sliderFrequency->setValue (1000.0, dontSendNotification); sliderFrequency->addListener (this); addAndMakeVisible (sliderResonance = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderResonance->setRange (0.01, 100.0); sliderResonance->setDoubleClickReturnValue (true, 1.0 / std::sqrt (2.0)); sliderResonance->setSkewFactor (0.1); sliderResonance->setValue (1.0 / std::sqrt (2.0), dontSendNotification); sliderResonance->addListener (this); addAndMakeVisible (sliderGain = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderGain->setRange (-40.0, 40.0); sliderGain->setDoubleClickReturnValue (true, 0.0); sliderGain->addListener (this); // ------------------------------------------------------------------------- addAndMakeVisible (comboType = new ComboBox()); comboType->addItemList ({ "Low-pass 2nd order" }, 3); comboType->addListener (this); comboType->setSelectedId (3, dontSendNotification); addAndMakeVisible (comboDisplay = new ComboBox()); comboDisplay->addItemList ({ "Magnitude (A+D)", "Phase (A+D)" }, 1); comboDisplay->addListener (this); comboDisplay->setSelectedId (1, dontSendNotification); addAndMakeVisible (comboAlgorithm = new ComboBox()); comboAlgorithm->addSectionHeading ("Bilinear transform"); comboAlgorithm->addItem ("BLT - no warping", SessionThreeDSP::Algorithm_BLT_NoWarping + 1); comboAlgorithm->addItem ("BLT - warping", SessionThreeDSP::Algorithm_BLT_Warping + 1); comboAlgorithm->addItem ("BLT - warping (oversampled 4 times)", 99); comboAlgorithm->addSectionHeading ("Numerical integration methods"); comboAlgorithm->addItem ("Forward Euler", SessionThreeDSP::Algorithm_Forward_Euler + 1); comboAlgorithm->addItem ("Backward Euler", SessionThreeDSP::Algorithm_Backward_Euler + 1); comboAlgorithm->addItem ("Trapezoidal", SessionThreeDSP::Algorithm_Trap + 1); comboAlgorithm->addItem ("Backward Differentiation Formula 2", SessionThreeDSP::Algorithm_BDF2 + 1); comboAlgorithm->addSectionHeading ("Other methods"); comboAlgorithm->addItem ("Impulse Invariance", SessionThreeDSP::Algorithm_ImpulseInvariance + 1); comboAlgorithm->addItem ("Massberg", SessionThreeDSP::Algorithm_Massberg + 1); comboAlgorithm->addItem ("Vicanek", SessionThreeDSP::Algorithm_Vicanek + 1); comboAlgorithm->addListener (this); comboAlgorithm->setSelectedId (1, dontSendNotification); // ------------------------------------------------------------------------- addAndMakeVisible (labelFrequency = new Label ("", "Frequency")); labelFrequency->setJustificationType (Justification::centred); labelFrequency->attachToComponent (sliderFrequency, false); addAndMakeVisible (labelResonance = new Label ("", "Resonance")); labelResonance->setJustificationType (Justification::centred); labelResonance->attachToComponent (sliderResonance, false); addAndMakeVisible (labelGain = new Label ("", "Gain")); labelGain->setJustificationType (Justification::centred); labelGain->attachToComponent (sliderGain, false); addAndMakeVisible (labelType = new Label ("", "Type")); labelType->setJustificationType (Justification::centred); labelType->attachToComponent (comboType, false); addAndMakeVisible (labelDisplay = new Label ("", "Display")); labelDisplay->setJustificationType (Justification::centred); labelDisplay->attachToComponent (comboDisplay, false); addAndMakeVisible (labelAlgorithm = new Label ("", "Algorithm")); labelAlgorithm->setJustificationType (Justification::centred); // ------------------------------------------------------------------------- theOversampling.reset (new dsp::Oversampling<float> (2, 2, dsp::Oversampling<float>::filterHalfBandPolyphaseIIR, true)); // ------------------------------------------------------------------------- updateVisibility(); triggerAsyncUpdate(); } SessionThreeComponent::~SessionThreeComponent() { } void SessionThreeComponent::paint (Graphics &g) { auto rect = getLocalBounds(); g.setColour (Colours::white); g.fillRect (rect.removeFromTop (getHeight() - 170)); g.setColour (getLookAndFeel().findColour (ResizableWindow::backgroundColourId)); g.fillRect (rect); } void SessionThreeComponent::resized() { Rectangle<int> rect = getLocalBounds(); auto rectTop = rect.removeFromTop (getHeight() - 170); thePlotComponent->setBounds (rectTop.reduced (10, 10)); rect.removeFromTop (40); auto rectMid = rect.removeFromTop (100).reduced (10, 0); comboType->setBounds (rectMid.withWidth (160).withSizeKeepingCentre (160, 24).translated (0, -28)); comboAlgorithm->setBounds (rectMid.withWidth (160).withSizeKeepingCentre (160, 24).translated (0, 28)); labelAlgorithm->setBounds (rectMid.withWidth (160).withSizeKeepingCentre (160, 24).translated (0, 52)); sliderFrequency->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200, 0)); sliderResonance->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 100, 0)); sliderGain->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 200, 0)); comboDisplay->setBounds (rectMid.withWidth (160).withSizeKeepingCentre (160, 24).translated (200 + 320, 0)); } //============================================================================== void SessionThreeComponent::sliderValueChanged (Slider *slider) { if (slider == sliderFrequency) { mustUpdateProcessing = true; } else if (slider == sliderResonance) { mustUpdateProcessing = true; } else if (slider == sliderGain) { mustUpdateProcessing = true; } } void SessionThreeComponent::comboBoxChanged (ComboBox *combo) { if (combo == comboType) { mustUpdateProcessing = true; updateVisibility(); } else if (combo == comboDisplay) { } else if (combo == comboAlgorithm) { mustUpdateProcessing = true; updateVisibility(); } } void SessionThreeComponent::updateVisibility() { auto type = comboType->getSelectedId() - 1; labelResonance->setEnabled (type != SessionTwoDSP::Type_LowPass1 && type != SessionTwoDSP::Type_HighPass1); sliderResonance->setEnabled (type != SessionTwoDSP::Type_LowPass1 && type != SessionTwoDSP::Type_HighPass1); labelGain->setEnabled (type == SessionTwoDSP::Type_Peak); sliderGain->setEnabled (type == SessionTwoDSP::Type_Peak); } //============================================================================== void SessionThreeComponent::prepareToPlay (int samplesPerBlockExpected, double sR) { SessionComponent::prepareToPlay (samplesPerBlockExpected, sR); theOversampling->initProcessing (samplesPerBlockExpected); updateProcessing(); reset(); isActive = true; } void SessionThreeComponent::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) { if (mustUpdateProcessing) updateProcessing(); ScopedNoDenormals noDenormals; auto startSample = bufferToFill.startSample; auto numSamples = bufferToFill.numSamples; auto numChannels = jmax (2, bufferToFill.buffer->getNumChannels()); jassert (numSamples > 0); jassert (numChannels > 0); if (comboAlgorithm->getSelectedId() == 99) { dsp::AudioBlock<float> inoutBlock (*(bufferToFill.buffer)); inoutBlock = inoutBlock.getSubBlock (startSample, numSamples); dsp::AudioBlock<float> overBlock = theOversampling->processSamplesUp (inoutBlock); for (auto channel = 0; channel < numChannels; channel++) { auto *samples = overBlock.getChannelPointer (channel); auto b0 = theCoefficients.b0; auto b1 = theCoefficients.b1; auto b2 = theCoefficients.b2; auto a1 = theCoefficients.a1; auto a2 = theCoefficients.a2; auto v1 = theFilters[channel].v1; auto v2 = theFilters[channel].v2; for (auto i = 0; i < overBlock.getNumSamples(); i++) { auto input = samples[i]; auto output = b0 * input + v1; v1 = b1 * input + v2 - a1 * output; v2 = b2 * input - a2 * output; samples[i] = output; } theFilters[channel].v1 = v1; theFilters[channel].v2 = v2; } theOversampling->processSamplesDown (inoutBlock); } else { for (auto channel = 0; channel < numChannels; channel++) { auto *samples = bufferToFill.buffer->getWritePointer (channel); auto b0 = theCoefficients.b0; auto b1 = theCoefficients.b1; auto b2 = theCoefficients.b2; auto a1 = theCoefficients.a1; auto a2 = theCoefficients.a2; auto v1 = theFilters[channel].v1; auto v2 = theFilters[channel].v2; if (theCoefficients.order > 2) { auto b3 = theCoefficients.b3; auto b4 = theCoefficients.b4; auto a3 = theCoefficients.a3; auto a4 = theCoefficients.a4; auto v3 = theFilters[channel].v3; auto v4 = theFilters[channel].v4; for (auto i = 0; i < numSamples; i++) { auto input = samples[i + startSample]; auto output = b0 * input + v1; v1 = b1 * input + v2 - a1 * output; v2 = b2 * input + v3 - a2 * output; v3 = b3 * input + v4 - a3 * output; v4 = b4 * input - a4 * output; samples[i + startSample] = output; } theFilters[channel].v3 = v3; theFilters[channel].v4 = v4; } else { for (auto i = 0; i < numSamples; i++) { auto input = samples[i + startSample]; auto output = b0 * input + v1; v1 = b1 * input + v2 - a1 * output; v2 = b2 * input - a2 * output; samples[i + startSample] = output; } } theFilters[channel].v1 = v1; theFilters[channel].v2 = v2; } } } void SessionThreeComponent::releaseAudioResources() { reset(); } void SessionThreeComponent::reset() { for (auto channel = 0; channel < 2; channel++) { theFilters[channel].v1 = 0; theFilters[channel].v2 = 0; theFilters[channel].v3 = 0; theFilters[channel].v4 = 0; } theOversampling->reset(); } void SessionThreeComponent::updateProcessing() { mustUpdateProcessing = false; if (comboAlgorithm->getSelectedId() == 99) { SessionThreeDSP::calculusLP2Coefficients ((float)sliderFrequency->getValue(), (float)sliderResonance->getValue(), SessionThreeDSP::Algorithm_BLT_Warping, sampleRate * 4, theCoefficients.order, theCoefficients.b0, theCoefficients.b1, theCoefficients.b2, theCoefficients.b3, theCoefficients.b4, theCoefficients.a1, theCoefficients.a2, theCoefficients.a3, theCoefficients.a4); } else { SessionThreeDSP::calculusLP2Coefficients ((float)sliderFrequency->getValue(), (float)sliderResonance->getValue(), comboAlgorithm->getSelectedId() - 1, sampleRate, theCoefficients.order, theCoefficients.b0, theCoefficients.b1, theCoefficients.b2, theCoefficients.b3, theCoefficients.b4, theCoefficients.a1, theCoefficients.a2, theCoefficients.a3, theCoefficients.a4); } } //============================================================================== void SessionThreeComponent::timerCallback() { stopThread (1000); startThread(); } void SessionThreeComponent::run() { if (!(isActive)) return; // ------------------------------------------------------------------------- auto N = 1001; bufferData.setSize (3, N, false, false, true); if (threadShouldExit()) return; // ------------------------------------------------------------------------- float b0A, b1A, b2A, a1A, a2A; float b0D, b1D, b2D, b3D, b4D, a1D, a2D, a3D, a4D; int order; SessionTwoDSP::calculusAnalogCoefficients ((float)sliderFrequency->getValue(), (float)sliderResonance->getValue(), (float)sliderGain->getValue(), comboType->getSelectedId() - 1, b0A, b1A, b2A, a1A, a2A); if (comboAlgorithm->getSelectedId() == 99) { SessionThreeDSP::calculusLP2Coefficients ((float)sliderFrequency->getValue(), (float)sliderResonance->getValue(), SessionThreeDSP::Algorithm_BLT_Warping, sampleRate * 4, order, b0D, b1D, b2D, b3D, b4D, a1D, a2D, a3D, a4D); } else { SessionThreeDSP::calculusLP2Coefficients ((float)sliderFrequency->getValue(), (float)sliderResonance->getValue(), comboAlgorithm->getSelectedId() - 1, sampleRate, order, b0D, b1D, b2D, b3D, b4D, a1D, a2D, a3D, a4D); } if (threadShouldExit()) return; // ------------------------------------------------------------------------- auto *dataX = bufferData.getWritePointer (0); auto *dataYA = bufferData.getWritePointer (1); auto *dataYD = bufferData.getWritePointer (2); auto displayMagnitude = comboDisplay->getSelectedId() == 1; if (displayMagnitude) { for (auto i = 0; i < N; i++) { auto frequency = jmaplintolog (i / (N - 1.0), 10.0, 22000.0); auto magnitudeA = SessionTwoDSP::getAnalogMagnitudeForFrequency (frequency, b0A, b1A, b2A, a1A, a2A); double magnitudeD = 0; if (order > 2) { magnitudeD = SessionThreeDSP::getMagnitudeForFrequency (frequency, sampleRate, b0D, b1D, b2D, b3D, b4D, a1D, a2D, a3D, a4D); } else { magnitudeD = SessionOneDSP::getMagnitudeForFrequency (frequency, sampleRate * (comboAlgorithm->getSelectedId() == 99 ? 4 : 1), b0D, b1D, b2D, a1D, a2D); } dataX[i] = (float)frequency; dataYA[i] = (float)Decibels::gainToDecibels (magnitudeA); dataYD[i] = (float)Decibels::gainToDecibels (magnitudeD); if (threadShouldExit()) return; } } else { for (auto i = 0; i < N; i++) { auto frequency = jmaplintolog (i / (N - 1.0), 10.0, 22000.0); auto phaseA = SessionTwoDSP::getAnalogPhaseForFrequency (frequency, b0A, b1A, b2A, a1A, a2A); double phaseD = 0; if (order > 2) { phaseD = SessionThreeDSP::getPhaseForFrequency (frequency, sampleRate, b0D, b1D, b2D, b3D, b4D, a1D, a2D, a3D, a4D); } else { phaseD = SessionOneDSP::getPhaseForFrequency (frequency, sampleRate * (comboAlgorithm->getSelectedId() == 99 ? 4 : 1), b0D, b1D, b2D, a1D, a2D); } dataX[i] = (float)frequency; dataYA[i] = (float)(phaseA / double_Pi * 180.0); dataYD[i] = (float)(phaseD / double_Pi * 180.0); if (threadShouldExit()) return; } } // ------------------------------------------------------------------------- PlotComponent::Information information; information.minimumXValue = 10.0; information.maximumXValue = 22000.0; information.isXAxisLogarithmic = true; if (displayMagnitude) { information.minimumYValue = -80.0; information.maximumYValue = 40.0; information.gridYSize = 10.0; } else { information.minimumYValue = -200.0; information.maximumYValue = 200.0; information.gridYSize = 45.0; information.gridYMustStartAtZero = true; } information.displayGrid = true; information.strLabelX = "frequency (Hz)"; if (displayMagnitude) information.strLabelY = "magnitude (dB)"; else information.strLabelY = "phase (degrees)"; thePlotComponent->setInformation (information); // ------------------------------------------------------------------------- thePlotComponent->pushData (bufferData, N, 2); triggerAsyncUpdate(); } <file_sep>/Source/Sessions/Session1/SessionOneComponent.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "SessionOneComponent.h" #include "SessionOneDSP.h" #include "../../Assets/MathFunctions.h" //============================================================================== SessionOneComponent::SessionOneComponent (AudioDeviceManager *adm) : SessionComponent ("EQ", adm) { // ------------------------------------------------------------------------- addAndMakeVisible (thePlotComponent = new PlotComponent()); // ------------------------------------------------------------------------- addAndMakeVisible (sliderFrequency = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderFrequency->setRange (20.0, 22000.0); sliderFrequency->setSkewFactor (0.2); sliderFrequency->setValue (1000.0, dontSendNotification); sliderFrequency->addListener (this); addAndMakeVisible (sliderResonance = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderResonance->setRange (0.01, 100.0); sliderResonance->setDoubleClickReturnValue (true, 1.0 / std::sqrt (2.0)); sliderResonance->setSkewFactor (0.1); sliderResonance->setValue (1.0 / std::sqrt (2.0), dontSendNotification); sliderResonance->addListener (this); addAndMakeVisible (sliderGain = new Slider (Slider::RotaryVerticalDrag, Slider::TextBoxBelow)); sliderGain->setRange (-40.0, 40.0); sliderGain->setDoubleClickReturnValue (true, 0.0); sliderGain->addListener (this); // ------------------------------------------------------------------------- addAndMakeVisible (comboType = new ComboBox()); comboType->addItemList ({ "Low-pass 1st order", "High-pass 1st order", "Low-pass 2nd order", "Band-pass 2nd order", "High-pass 2nd order", "Peak filter"}, 1); comboType->addListener (this); comboType->setSelectedId (1, dontSendNotification); addAndMakeVisible (comboDisplay = new ComboBox()); comboDisplay->addItemList ({ "Magnitude", "Phase" }, 1); comboDisplay->addListener (this); comboDisplay->setSelectedId (1, dontSendNotification); // ------------------------------------------------------------------------- addAndMakeVisible (labelFrequency = new Label ("", "Frequency")); labelFrequency->setJustificationType (Justification::centred); labelFrequency->attachToComponent (sliderFrequency, false); addAndMakeVisible (labelResonance = new Label ("", "Resonance")); labelResonance->setJustificationType (Justification::centred); labelResonance->attachToComponent (sliderResonance, false); addAndMakeVisible (labelGain = new Label ("", "Gain")); labelGain->setJustificationType (Justification::centred); labelGain->attachToComponent (sliderGain, false); addAndMakeVisible (labelType = new Label ("", "Type")); labelType->setJustificationType (Justification::centred); labelType->attachToComponent (comboType, false); addAndMakeVisible (labelDisplay = new Label ("", "Display")); labelDisplay->setJustificationType (Justification::centred); labelDisplay->attachToComponent (comboDisplay, false); // ------------------------------------------------------------------------- updateVisibility(); triggerAsyncUpdate(); } SessionOneComponent::~SessionOneComponent() { } void SessionOneComponent::paint (Graphics &g) { auto rect = getLocalBounds(); g.setColour (Colours::white); g.fillRect (rect.removeFromTop (getHeight() - 170)); g.setColour (getLookAndFeel().findColour (ResizableWindow::backgroundColourId)); g.fillRect (rect); } void SessionOneComponent::resized() { Rectangle<int> rect = getLocalBounds(); auto rectTop = rect.removeFromTop (getHeight() - 170); thePlotComponent->setBounds (rectTop.reduced (10, 10)); rect.removeFromTop (40); auto rectMid = rect.removeFromTop (100).reduced (10, 0); comboType->setBounds (rectMid.withWidth (160).withSizeKeepingCentre (160, 24)); sliderFrequency->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200, 0)); sliderResonance->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 100, 0)); sliderGain->setBounds (rectMid.withWidth (80).withSizeKeepingCentre (80, 80).translated (200 + 200, 0)); comboDisplay->setBounds (rectMid.withWidth (160).withSizeKeepingCentre (160, 24).translated (200 + 320, 0)); } //============================================================================== void SessionOneComponent::sliderValueChanged (Slider *slider) { if (slider == sliderFrequency) { mustUpdateProcessing = true; } else if (slider == sliderResonance) { mustUpdateProcessing = true; } else if (slider == sliderGain) { mustUpdateProcessing = true; } } void SessionOneComponent::comboBoxChanged (ComboBox *combo) { if (combo == comboType) { mustUpdateProcessing = true; updateVisibility(); } } void SessionOneComponent::updateVisibility() { auto type = comboType->getSelectedId() - 1; labelResonance->setEnabled (type != SessionOneDSP::Type_LowPass1 && type != SessionOneDSP::Type_HighPass1); sliderResonance->setEnabled (type != SessionOneDSP::Type_LowPass1 && type != SessionOneDSP::Type_HighPass1); labelGain->setEnabled (type == SessionOneDSP::Type_Peak); sliderGain->setEnabled (type == SessionOneDSP::Type_Peak); } //============================================================================== void SessionOneComponent::prepareToPlay (int samplesPerBlockExpected, double sR) { SessionComponent::prepareToPlay (samplesPerBlockExpected, sR); updateProcessing(); reset(); isActive = true; } void SessionOneComponent::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) { if (mustUpdateProcessing) updateProcessing(); ScopedNoDenormals noDenormals; auto startSample = bufferToFill.startSample; auto numSamples = bufferToFill.numSamples; auto numChannels = jmax (2, bufferToFill.buffer->getNumChannels()); jassert (numSamples > 0); jassert (numChannels > 0); for (auto channel = 0; channel < numChannels; channel++) { auto *samples = bufferToFill.buffer->getWritePointer (channel); auto b0 = theCoefficients.b0; auto b1 = theCoefficients.b1; auto b2 = theCoefficients.b2; auto a1 = theCoefficients.a1; auto a2 = theCoefficients.a2; auto v1 = theFilters[channel].v1; auto v2 = theFilters[channel].v2; for (auto i = 0; i < numSamples; i++) { auto input = samples[i + startSample]; auto output = b0 * input + v1; v1 = b1 * input + v2 - a1 * output; v2 = b2 * input - a2 * output; samples[i + startSample] = output; } theFilters[channel].v1 = v1; theFilters[channel].v2 = v2; } } void SessionOneComponent::releaseAudioResources() { reset(); } void SessionOneComponent::reset() { for (auto channel = 0; channel < 2; channel++) { theFilters[channel].v1 = 0; theFilters[channel].v2 = 0; } } void SessionOneComponent::updateProcessing() { mustUpdateProcessing = false; SessionOneDSP::calculusCoefficients ((float)sliderFrequency->getValue(), (float)sliderResonance->getValue(), (float)sliderGain->getValue(), comboType->getSelectedId() - 1, sampleRate, theCoefficients.b0, theCoefficients.b1, theCoefficients.b2, theCoefficients.a1, theCoefficients.a2); } //============================================================================== void SessionOneComponent::timerCallback() { stopThread (1000); startThread(); } void SessionOneComponent::run() { if (!(isActive)) return; // ------------------------------------------------------------------------- auto N = 1001; bufferData.setSize (2, N, false, false, true); if (threadShouldExit()) return; // ------------------------------------------------------------------------- float b0, b1, b2, a1, a2; SessionOneDSP::calculusCoefficients ((float)sliderFrequency->getValue(), (float)sliderResonance->getValue(), (float)sliderGain->getValue(), comboType->getSelectedId() - 1, sampleRate, b0, b1, b2, a1, a2); if (threadShouldExit()) return; // ------------------------------------------------------------------------- auto *dataX = bufferData.getWritePointer (0); auto *dataY = bufferData.getWritePointer (1); auto displayMagnitude = comboDisplay->getSelectedId() == 1; if (displayMagnitude) { for (auto i = 0; i < N; i++) { auto frequency = jmaplintolog (i / (N - 1.0), 10.0, 22000.0); auto magnitude = SessionOneDSP::getMagnitudeForFrequency (frequency, sampleRate, b0, b1, b2, a1, a2); dataX[i] = (float)frequency; dataY[i] = (float)Decibels::gainToDecibels (magnitude); if (threadShouldExit()) return; } } else { for (auto i = 0; i < N; i++) { auto frequency = jmaplintolog (i / (N - 1.0), 10.0, 22000.0); auto phase = SessionOneDSP::getPhaseForFrequency (frequency, sampleRate, b0, b1, b2, a1, a2); dataX[i] = (float)frequency; dataY[i] = (float)(phase / double_Pi * 180.0); if (threadShouldExit()) return; } } // ------------------------------------------------------------------------- PlotComponent::Information information; information.minimumXValue = 10.0; information.maximumXValue = 22000.0; information.isXAxisLogarithmic = true; if (displayMagnitude) { information.minimumYValue = -80.0; information.maximumYValue = 40.0; information.gridYSize = 10.0; } else { information.minimumYValue = -200.0; information.maximumYValue = 200.0; information.gridYSize = 45.0; information.gridYMustStartAtZero = true; } information.displayGrid = true; information.strLabelX = "frequency (Hz)"; if (displayMagnitude) information.strLabelY = "magnitude (dB)"; else information.strLabelY = "phase (degrees)"; thePlotComponent->setInformation (information); // ------------------------------------------------------------------------- thePlotComponent->pushData (bufferData, N, 1); triggerAsyncUpdate(); } <file_sep>/Source/Sessions/Session7/SessionSevenComponent.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "../../SessionComponents.h" #include "../../Assets/PlotComponent.h" #include "../Session6/SessionSixDSP.h" #include "SessionSevenDSP.h" #include "../../Assets/LowFrequencyOscillator.h" //============================================================================== class SessionSevenComponent : public SessionComponent, public Slider::Listener, public ComboBox::Listener { public: //============================================================================== enum ModulationType { Modulation_None = 0, Modulation_LFO_Triangle, Modulation_LFO_Square, Modulation_Envelope_Up, Modulation_Envelope_Down }; enum ModelType { Model_SVFNL_Naive = 0, Model_MoogFilter_JUCE, Model_DiodeClipper_NewtonRaphson }; //============================================================================== SessionSevenComponent (AudioDeviceManager *adm); ~SessionSevenComponent(); //============================================================================== void paint (Graphics &g) override; void resized() override; //============================================================================== void sliderValueChanged (Slider *slider) override; void comboBoxChanged (ComboBox *combo) override; //============================================================================== void prepareToPlay (int samplesPerBlockExpected, double sampleRate) override; void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override; void releaseAudioResources() override; void reset() override; private: //============================================================================== void timerCallback() override; void run() override; void updateVisibility(); //============================================================================== void updateProcessing(); //============================================================================== AudioBuffer<float> bufferModulation; LowFrequencyOscillator theLFO; LinearSmoothedValue<float> depthVolume, gainVolume; EnvelopeFollower theEnvelopeFollower; TPTFilter1stOrder theSlewFilter; //============================================================================== ScopedPointer<dsp::Oversampling<float>> theOversampling; //============================================================================== SVFLowpassFilterNL theFiltersNL[2]; dsp::LadderFilter<float> theMoogFilter; DiodeClipper theDiodeClipper[2]; float centralFreq; bool isActive = false; //============================================================================== std::atomic<float> lastEnvValue; int modulationType, modelType; //============================================================================== ScopedPointer<PlotComponent> thePlotComponent; AudioBuffer<float> bufferData; //============================================================================== ScopedPointer<Slider> sliderGain; ScopedPointer<Slider> sliderFrequency, sliderResonance, sliderModulation; ScopedPointer<ComboBox> comboModel, comboModulationType; ScopedPointer<Slider> sliderLFOFrequency, sliderEnvAttack, sliderEnvRelease, sliderEnvSens; ScopedPointer<Label> labelGain; ScopedPointer<Label> labelFrequency, labelResonance, labelModulation; ScopedPointer<Label> labelModel, labelModulationType; ScopedPointer<Label> labelLFOFrequency, labelEnvAttack, labelEnvRelease, labelEnvSens; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SessionSevenComponent) }; <file_sep>/Source/Sessions/Session2/SessionTwoDSP.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "SessionTwoDSP.h" //============================================================================== const void SessionTwoDSP::calculusAnalogCoefficients (float frequency, float Q, float gain, int type, float &b0, float &b1, float &b2, float &a1, float &a2) { auto w0 = (float)(2.0 * double_Pi * frequency); auto A = (float)(Decibels::decibelsToGain (gain / 2.0)); if (type == Type_LowPass1) { auto a0 = 1.0f; b0 = 1.0f / a0; b1 = 0.0f; b2 = 0.0f; a1 = (1.0f / w0) / a0; a2 = 0.0f; } else if (type == Type_HighPass1) { auto a0 = 1.0f; b0 = 0.f; b1 = (1.0f / w0) / a0; b2 = 0.0f; a1 = (1.0f / w0) / a0; a2 = 0.0f; } else if (type == Type_LowPass2) { auto a0 = 1.f; b0 = 1.f / a0; b1 = 0.f; b2 = 0.f; a1 = (1.0f / (Q * w0)) / a0; a2 = (1.0f / (w0 * w0)) / a0; } else if (type == Type_BandPass2) { auto a0 = 1.f; b0 = 0.f; b1 = (1.0f / (Q * w0)) / a0; b2 = 0.f; a1 = (1.0f / (Q * w0)) / a0; a2 = (1.0f / (w0 * w0)) / a0; } else if (type == Type_HighPass2) { auto a0 = 1.f; b0 = 0.f; b1 = 0.f; b2 = (1.0f / (w0 * w0)) / a0; a1 = (1.0f / (Q * w0)) / a0; a2 = (1.0f / (w0 * w0)) / a0; } else if (type == Type_Peak) { auto a0 = 1.f; b0 = 1.0f / a0; b1 = (A / (Q * w0)) / a0; b2 = (1.0f / w0 / w0) / a0; a1 = (1.0f / (A * Q * w0)) / a0; a2 = (1.0f / (w0 * w0)) / a0; } else { b0 = 1.0f; b1 = 0.0f; b2 = 0.0f; a1 = 0.0f; a2 = 0.0f; } } const void SessionTwoDSP::calculusPreWarpedCoefficients (float frequency, float Q, float gain, int type, double _sampleRate, float &b0, float &b1, float &b2, float &a1, float &a2) { auto Ts = (float)(1.0 / _sampleRate); auto w0 = (float)(2.0 * double_Pi * frequency); auto A = (float)(Decibels::decibelsToGain (gain / 2.0)); Ts = (float) (std::tan (w0 * Ts / 2.0) * 2.0 / w0); auto Ts2 = Ts * Ts; auto w02 = w0 * w0; auto A2 = A * A; if (type == Type_LowPass1) { auto a0 = Ts * w0 + 2.0f; b0 = (Ts * w0) / a0; b1 = (Ts * w0) / a0; b2 = 0.0f; a1 = (Ts * w0 - 2.0f) / a0; a2 = 0.0f; } else if (type == Type_HighPass1) { auto a0 = Ts * w0 + 2.0f; b0 = 2.0f / a0; b1 = -2.0f / a0; b2 = 0.0f; a1 = (Ts * w0 - 2.0f) / a0; a2 = 0.0f; } else if (type == Type_LowPass2) { auto a0 = Q * Ts2 * w02 + 2 * Ts * w0 + 4 * Q; b0 = (Q * Ts2 * w02) / a0; b1 = (2 * Q * Ts2 * w02) / a0; b2 = (Q * Ts2 * w02) / a0; a1 = (2 * Q * Ts2 * w02 - 8 * Q) / a0; a2 = (Q * Ts2 * w02 - 2 * Ts * w0 + 4 * Q) / a0; } else if (type == Type_BandPass2) { auto a0 = Q * Ts2 * w02 + 2 * Ts * w0 + 4 * Q; b0 = (2 * Ts * w0) / a0; b1 = 0.0; b2 = (-2 * Ts * w0) / a0; a1 = (2 * Q * Ts2 * w02 - 8 * Q) / a0; a2 = (Q * Ts2 * w02 - 2 * Ts * w0 + 4 * Q) / a0; } else if (type == Type_HighPass2) { auto a0 = Q * Ts2 * w02 + 2 * Ts * w0 + 4 * Q; b0 = (4 * Q) / a0; b1 = (-8 * Q) / a0; b2 = (4 * Q) / a0; a1 = (2 * Q * Ts2 * w02 - 8 * Q) / a0; a2 = (Q * Ts2 * w02 - 2 * Ts * w0 + 4 * Q) / a0; } else if (type == Type_Peak) { auto a0 = A * Q * Ts2 * w02 + 2 * Ts * w0 + 4 * A * Q; b0 = (2 * A2 * Ts * w0 + Q * A * Ts2 * w02 + Q * A * 4) / a0; b1 = (2 * A * Q * Ts2 * w02 - 8 * A * Q) / a0; b2 = (-2 * A2 * Ts * w0 + Q * A * Ts2 * w02 + Q * A * 4) / a0; a1 = (2 * A * Q * Ts2 * w02 - 8 * A * Q) / a0; a2 = (A * Q * Ts2 * w02 - 2 * Ts * w0 + 4 * A * Q) / a0; } else { b0 = 1.0f; b1 = 0.0f; b2 = 0.0f; a1 = 0.0f; a2 = 0.0f; } } const double SessionTwoDSP::getAnalogMagnitudeForFrequency (double frequency, const float b0, const float b1, const float b2, const float a1, const float a2) { constexpr std::complex<double> j (0, 1); jassert (frequency >= 0); std::complex<double> numerator = 0.0, denominator = 0.0, factor = 1.0; std::complex<double> jw = MathConstants<double>::twoPi * frequency * j; numerator += ((double)b0) * factor; factor *= jw; numerator += ((double)b1) * factor; factor *= jw; numerator += ((double)b2) * factor; denominator = 1.0; factor = jw; denominator += ((double)a1) * factor; factor *= jw; denominator += ((double)a2) * factor; return std::abs (numerator / denominator); } const double SessionTwoDSP::getAnalogPhaseForFrequency (double frequency, const float b0, const float b1, const float b2, const float a1, const float a2) { constexpr std::complex<double> j (0, 1); jassert (frequency >= 0); std::complex<double> numerator = 0.0, denominator = 0.0, factor = 1.0; std::complex<double> jw = MathConstants<double>::twoPi * frequency * j; numerator += ((double)b0) * factor; factor *= jw; numerator += ((double)b1) * factor; factor *= jw; numerator += ((double)b2) * factor; denominator = 1.0; factor = jw; denominator += ((double)a1) * factor; factor *= jw; denominator += ((double)a2) * factor; return std::arg (numerator / denominator); } <file_sep>/Source/SessionComponents.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" //============================================================================== /* This component lives inside our window, and this is where you should put all your controls and content. */ class SessionComponent : public Component, public AsyncUpdater, public Timer, public Thread { public: //============================================================================== SessionComponent (String strName = String(), AudioDeviceManager *adm = nullptr) : Thread ("") { setName (strName); deviceManager = adm; setLookAndFeel (&theLF); } virtual ~SessionComponent() { setLookAndFeel (nullptr); stopTimer(); stopThread (1000); } //============================================================================== virtual void paint (Graphics& g) override { g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId)); } virtual void resized() override {} //============================================================================== virtual void prepareToPlay (int samplesPerBlockExpected, double _sampleRate) { jassert (_sampleRate > 0); ignoreUnused (samplesPerBlockExpected); sampleRate = _sampleRate; } virtual void getNextAudioBlock (const AudioSourceChannelInfo& /*bufferToFill*/) {} virtual void releaseAudioResources() {} virtual void reset() {} void visibilityChanged() override { if (isVisible()) startTimerHz (30); else { stopTimer(); stopThread (1000); } } protected: //============================================================================== virtual void timerCallback() override {} virtual void run() override {} //============================================================================== bool mustUpdateProcessing = false; double sampleRate = 44100.0; //============================================================================== AudioDeviceManager *deviceManager; LookAndFeel_V4 theLF; private: //============================================================================== void handleAsyncUpdate() override { repaint(); } //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SessionComponent) }; //============================================================================== /* This component lives inside our window, and this is where you should put all your controls and content. */ class SettingsComponent : public SessionComponent { public: //============================================================================== SettingsComponent (AudioDeviceManager *adm); ~SettingsComponent(); //============================================================================== void resized() override; private: //============================================================================== ScopedPointer<AudioDeviceSelectorComponent> selectorComponent; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SettingsComponent) }; //============================================================================== /* This component lives inside our window, and this is where you should put all your controls and content. */ class AboutComponent : public SessionComponent { public: //============================================================================== AboutComponent (AudioDeviceManager *adm); ~AboutComponent(); //============================================================================== void resized() override; void paint (Graphics &g) override; private: //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AboutComponent) }; //============================================================================== /* This component lives inside our window, and this is where you should put all your controls and content. */ class JavascriptEngineComponent : public SessionComponent, private CodeDocument::Listener { public: //============================================================================== JavascriptEngineComponent (AudioDeviceManager *adm); ~JavascriptEngineComponent(); //============================================================================== void resized() override; void paint (Graphics &g) override; private: //============================================================================== // This class is used by the script, and provides methods that the JS can call. struct DemoClass : public DynamicObject { DemoClass (JavascriptEngineComponent& demo) : owner (demo) { setMethod ("print", print); } static Identifier getClassName() { return "Demo"; } static var print (const var::NativeFunctionArgs& args) { if (args.numArguments > 0) if (auto* thisObject = dynamic_cast<DemoClass*> (args.thisObject.getObject())) thisObject->owner.consoleOutput (args.arguments[0].toString()); return var::undefined(); } JavascriptEngineComponent& owner; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DemoClass) }; //============================================================================== void timerCallback() override; void runScript(); void codeDocumentTextInserted (const String&, int) override; void codeDocumentTextDeleted (int, int) override; //============================================================================== void consoleOutput (const String& message); //============================================================================== CodeDocument codeDocument; ScopedPointer<CodeEditorComponent> editor; ScopedPointer<TextEditor> outputDisplay; //============================================================================== JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JavascriptEngineComponent) }; <file_sep>/Source/Sessions/Session1/SessionOneDSP.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "SessionOneDSP.h" //============================================================================== const void SessionOneDSP::calculusCoefficients (float frequency, float Q, float gain, int type, double sampleRate, float &b0, float &b1, float &b2, float &a1, float &a2) { auto Ts = (float)(1.0 / sampleRate); auto w0 = (float)(2.0 * double_Pi * frequency); auto A = (float)(Decibels::decibelsToGain (gain / 2.0)); auto Ts2 = Ts * Ts; auto w02 = w0 * w0; auto A2 = A * A; if (type == Type_LowPass1) { auto a0 = Ts * w0 + 2.0f; b0 = (Ts * w0) / a0; b1 = (Ts * w0) / a0; b2 = 0.0f; a1 = (Ts * w0 - 2.0f) / a0; a2 = 0.0f; } else if (type == Type_HighPass1) { auto a0 = Ts * w0 + 2.0f; b0 = 2.0f / a0; b1 = -2.0f / a0; b2 = 0.0f; a1 = (Ts * w0 - 2.0f) / a0; a2 = 0.0f; } else if (type == Type_LowPass2) { auto a0 = Q * Ts2 * w02 + 2 * Ts * w0 + 4 * Q; b0 = (Q * Ts2 * w02) / a0; b1 = (2 * Q * Ts2 * w02) / a0; b2 = (Q * Ts2 * w02) / a0; a1 = (2 * Q * Ts2 * w02 - 8 * Q) / a0; a2 = (Q * Ts2 * w02 - 2 * Ts * w0 + 4 * Q) / a0; } else if (type == Type_BandPass2) { auto a0 = Q * Ts2 * w02 + 2 * Ts * w0 + 4 * Q; b0 = (2 * Ts * w0) / a0; b1 = 0.0f; b2 = (-2 * Ts * w0) / a0; a1 = (2 * Q * Ts2 * w02 - 8 * Q) / a0; a2 = (Q * Ts2 * w02 - 2 * Ts * w0 + 4 * Q) / a0; } else if (type == Type_HighPass2) { auto a0 = Q * Ts2 * w02 + 2 * Ts * w0 + 4 * Q; b0 = (4 * Q) / a0; b1 = (-8 * Q) / a0; b2 = (4 * Q) / a0; a1 = (2 * Q * Ts2 * w02 - 8 * Q) / a0; a2 = (Q * Ts2 * w02 - 2 * Ts * w0 + 4 * Q) / a0; } else if (type == Type_Peak) { auto a0 = A * Q * Ts2 * w02 + 2 * Ts * w0 + 4 * A * Q; b0 = (2 * A2 * Ts * w0 + Q * A * Ts2 * w02 + Q * A * 4) / a0; b1 = (2 * A * Q * Ts2 * w02 - 8 * A * Q) / a0; b2 = (-2 * A2 * Ts * w0 + Q * A * Ts2 * w02 + Q * A * 4) / a0; a1 = (2 * A * Q * Ts2 * w02 - 8 * A * Q) / a0; a2 = (A * Q * Ts2 * w02 - 2 * Ts * w0 + 4 * A * Q) / a0; } else { b0 = 1.0f; b1 = 0.0f; b2 = 0.0f; a1 = 0.0f; a2 = 0.0f; } } const double SessionOneDSP::getMagnitudeForFrequency (double frequency, double sampleRate, const float b0, const float b1, const float b2, const float a1, const float a2) { constexpr std::complex<double> j (0, 1); jassert (frequency >= 0 && frequency <= sampleRate * 0.5); std::complex<double> numerator = 0.0, denominator = 0.0, factor = 1.0; std::complex<double> expjwT = std::exp (-MathConstants<double>::twoPi * frequency * j / sampleRate); numerator += ((double)b0) * factor; factor *= expjwT; numerator += ((double)b1) * factor; factor *= expjwT; numerator += ((double)b2) * factor; denominator = 1.0; factor = expjwT; denominator += ((double)a1) * factor; factor *= expjwT; denominator += ((double)a2) * factor; return std::abs (numerator / denominator); } const double SessionOneDSP::getPhaseForFrequency (double frequency, double sampleRate, const float b0, const float b1, const float b2, const float a1, const float a2) { constexpr std::complex<double> j (0, 1); jassert (frequency >= 0 && frequency <= sampleRate * 0.5); std::complex<double> numerator = 0.0, denominator = 0.0, factor = 1.0; std::complex<double> expjwT = std::exp (-MathConstants<double>::twoPi * frequency * j / sampleRate); numerator += ((double)b0) * factor; factor *= expjwT; numerator += ((double)b1) * factor; factor *= expjwT; numerator += ((double)b2) * factor; denominator = 1.0; factor = expjwT; denominator += ((double)a1) * factor; factor *= expjwT; denominator += ((double)a2) * factor; return std::arg (numerator / denominator); } <file_sep>/Source/Assets/MathFunctions.h /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" //============================================================================== /** Remaps a normalised value (between 0 and 1) to a target range, with a logarithmic mapping. The target range must be strictly positive. */ template <typename Type> const Type jmaplintolog (Type value0To1, Type targetRangeMin, Type targetRangeMax) { jassert (targetRangeMin > 0); jassert (targetRangeMax > 0); return std::pow ((Type) 10.0, value0To1 * std::log10 (targetRangeMax) + ((Type) 1.0 - value0To1) * std::log10 (targetRangeMin)); } /** Remaps a logarithmically mapped value to a linear normalised value (between 0 and 1). */ template <typename Type> const Type jmaplogtolin (Type valueLog, Type targetRangeMin, Type targetRangeMax) { jassert (targetRangeMin > 0); jassert (targetRangeMax > 0); return (std::log10 (valueLog) - std::log10 (targetRangeMin)) / (std::log10 (targetRangeMax) - std::log10 (targetRangeMin)); } <file_sep>/Source/Assets/LowFrequencyOscillator.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "LowFrequencyOscillator.h" // ========================================================================= LowFrequencyOscillator::LowFrequencyOscillator() { sampleRate = 44100; setFrequency (1.0); setType (TypeLFO::lfoSine); setVolume (1.f); theRandom.setSeedRandomly(); outputVolume.setValue (1.f); } LowFrequencyOscillator::~LowFrequencyOscillator() { } void LowFrequencyOscillator::setFrequency (double newFrequency) { frequency = newFrequency; factor = 2.0 * double_Pi * newFrequency / sampleRate; } void LowFrequencyOscillator::setVolume (float newVolume) { outputVolume.setValue (newVolume); } void LowFrequencyOscillator::setType (TypeLFO newType) { type = newType; } void LowFrequencyOscillator::initProcessing (double newSampleRate) { sampleRate = newSampleRate; setFrequency (frequency); } void LowFrequencyOscillator::reset (double initialPhase) { outputVolume.reset (sampleRate, 0.05); copyPhase (initialPhase); } const float LowFrequencyOscillator::getNextSample() { auto output = 0.f; if (type == lfoSine) { output = -std::cos (static_cast<float> (phase)); } else if (type == lfoTriangle) { if (phase < double_Pi) output = 2.f * static_cast<float> (phase / double_Pi) - 1.f; else output = -2.f * static_cast<float> (phase / double_Pi) + 3.f; } else if (type == lfoSawtooth) { output = static_cast<float> (phase / double_Pi) - 1.f; } else if (type == lfoSquare) { output = (phase < double_Pi) ? 1.f : -1.f; } else { output = theRandom.nextFloat() * 2.f - 1.f; } phase += factor; if (phase >= 2 * double_Pi) phase -= 2 * double_Pi; return output * outputVolume.getNextValue(); } void LowFrequencyOscillator::copyPhase (double newPhase) { phase = jlimit (0.0, 2 * double_Pi, newPhase); } const double LowFrequencyOscillator::getPhase() { return phase; } <file_sep>/Source/Sessions/Session3/SessionThreeDSP.cpp /* ============================================================================== <NAME> DSPExamples ============================================================================== */ #include "../Session1/SessionOneDSP.h" #include "../Session2/SessionTwoDSP.h" #include "SessionThreeDSP.h" //============================================================================== const void SessionThreeDSP::calculusLP2Coefficients (float frequency, float Q, int algorithm, double _sampleRate, int &order, float &b0, float &b1, float &b2, float &b3, float &b4, float &a1, float &a2, float &a3, float &a4) { auto Ts = 1.0 / _sampleRate; auto w0 = 2.0 * double_Pi * frequency; if (algorithm == Algorithm_BLT_NoWarping || algorithm == Algorithm_BLT_Warping || algorithm == Algorithm_Trap) { if (algorithm == Algorithm_BLT_Warping) Ts = std::tan (w0 * Ts / 2.0) * 2.0 / w0; auto Ts2 = Ts * Ts; auto w02 = w0 * w0; auto a0 = Q * Ts2 * w02 + 2 * Ts * w0 + 4 * Q; b0 = (float)((Q * Ts2 * w02) / a0); b1 = (float)((2 * Q * Ts2 * w02) / a0); b2 = (float)((Q * Ts2 * w02) / a0); a1 = (float)((2 * Q * Ts2 * w02 - 8 * Q) / a0); a2 = (float)((Q * Ts2 * w02 - 2 * Ts * w0 + 4 * Q) / a0); b3 = 0.f; b4 = 0.f; a3 = 0.f; a4 = 0.f; order = 2; } else if (algorithm == Algorithm_Forward_Euler) { auto Ts2 = Ts * Ts; auto w02 = w0 * w0; auto a0 = Q; b0 = 0.f; b1 = 0.f; b2 = (float)((Q * Ts2 * w02) / a0); a1 = (float)((Ts * w0 - 2 * Q) / a0); a2 = (float)((Q - Ts * w0 + Q * Ts2 * w02) / a0); b3 = 0.f; b4 = 0.f; a3 = 0.f; a4 = 0.f; order = 2; } else if (algorithm == Algorithm_Backward_Euler) { auto Ts2 = Ts * Ts; auto w02 = w0 * w0; auto a0 = Q + Ts * w0 + Q * Ts2 * w02; b0 = (float)((Q * Ts2 * w02) / a0); b1 = 0.f; b2 = 0.f; a1 = (float)((-Ts * w0 - 2 * Q) / a0); a2 = (float)(Q / a0); b3 = 0.f; b4 = 0.f; a3 = 0.f; a4 = 0.f; order = 2; } else if (algorithm == Algorithm_BDF2) { auto Ts2 = Ts * Ts; auto w02 = w0 * w0; auto a0 = 4 * Q * Ts2 * w02 + 6 * Ts * w0 + 9 * Q; b0 = (float)((4 * Q * Ts2 * w02) / a0); b1 = 0.f; b2 = 0.f; b3 = 0.f; b4 = 0.f; a1 = (float)((-24 * Q - 8 * Ts * w0) / a0); a2 = (float)((22 * Q + 2 * Ts * w0) / a0); a3 = (float)(-8*Q / a0); a4 = (float)(Q / a0); order = 4; } else if (algorithm == Algorithm_ImpulseInvariance) { float b0A, b1A, b2A, a0A, a1A, a2A; SessionTwoDSP::calculusAnalogCoefficients (frequency, Q, 0.f, SessionTwoDSP::FilterType::Type_LowPass2, b0A, b1A, b2A, a1A, a2A); a0A = 1.f; b0A /= a2A; b1A /= a2A; b2A /= a2A; a0A /= a2A; a1A /= a2A; a2A /= a2A; std::complex<double> delta = a1A * a1A - 4 * a0A * a2A; std::complex<double> s1 = (std::complex<double> (-a1A) - std::sqrt (delta)) / std::complex<double> (2 * a2A); std::complex<double> s2 = (std::complex<double> (-a1A) + std::sqrt (delta)) / std::complex<double> (2 * a2A); auto B0 = std::complex<double> (b0A - a0A * b2A); auto B1 = std::complex<double> (b1A - a1A * b2A); auto K1 = (B0 + B1 * s1) / (s1 - s2); auto K2 = -(B0 + B1 * s2) / (s1 - s2); auto e1 = std::exp (s1 * std::complex<double> (Ts)); auto e2 = std::exp (s2 * std::complex<double> (Ts)); auto e12 = std::exp ((s1 + s2) * std::complex<double> (Ts)); auto CR = std::complex<double> (Ts / 2) * (K1 + K2); a1 = (float) -std::real (e1 + e2); a2 = (float)std::real (e12); b0 = (float)std::real (std::complex<double> (Ts) * (K1 + K2 + std::complex<double> (b2A)) - CR); b1 = (float)std::real (-std::complex<double> (Ts) * (K1 * e2 + K2 * e1 - std::complex<double> (b2A) * (e1 + e2)) - CR * std::complex<double> (a1)); b2 = (float)std::real (std::complex<double> (Ts * b2A) * e12 - CR * std::complex<double> (a2)); b3 = 0.f; b4 = 0.f; a3 = 0.f; a4 = 0.f; order = 2; } else if (algorithm == Algorithm_Massberg) { auto Wn = w0 * Ts; auto Q2 = Q * Q; auto prec = 1e-6; auto g1 = 2 / std::sqrt (std::pow (2 - std::pow (std::sqrt (2)*double_Pi / Wn, 2), 2) + std::pow (2 * double_Pi / (Q*Wn), 2)); if (std::abs (1 - g1) < prec) g1 = g1 - prec; double Ws = 0.0; if (Q > sqrt (0.5)) { auto gr = 2 * Q2 / sqrt (4 * Q2 - 1); auto Wr = jmax (jmin (std::abs (std::tan ((double) Wn*std::sqrt (1 - 1 / (2 * Q2)) / 2)), 1 / prec), prec); Ws = Wr * std::sqrt (std::sqrt ((gr * gr - g1 * g1) / (gr * gr - 1))); } else { Ws = jmin (std::tan (Wn * std::sqrt ((2 - 1 / Q2 + std::sqrt ((1 - 4 * Q2) / (Q2 * Q2) + 4 / g1)) / 2) / 2), Wn * std::sqrt (std::sqrt (1 - g1 * g1)) / 2); } auto wp = 2 * std::atan (Ws); auto gp = 1 / std::sqrt (std::pow (1 - std::pow (wp / Wn, 2), 2) + std::pow (wp / (Q * Wn), 2)); auto wz = 2 * std::atan (Ws / std::sqrt (g1)); auto gz = 1 / std::sqrt (std::pow (1.0 - std::pow (wz / Wn, 2), 2) + std::pow (wz / (Q*Wn), 2)); auto qp = std::sqrt (g1 * (gp * gp - gz * gz) / ((g1 + gz * gz)*std::pow (g1 - 1, 2))); auto qz = std::sqrt (g1 * g1 * (gp * gp - gz * gz) / (gz * gz * (g1 + gp * gp)*std::pow (g1 - 1, 2.0))); auto Ws2 = Ws * Ws; auto a0 = (float) (Ws2 + Ws / qp + 1); b0 = (float)(Ws2 + std::sqrt (g1)*Ws / qz + g1) / a0; b1 = (float)(2 * (Ws2 - g1)) / a0; b2 = (float)(Ws2 - std::sqrt (g1)*Ws / qz + g1) / a0; a1 = (float)(2 * (Ws2 - 1)) / a0; a2 = (float)(Ws2 - Ws / qp + 1) / a0; b3 = 0.f; b4 = 0.f; a3 = 0.f; a4 = 0.f; order = 2; } else if (algorithm == Algorithm_Vicanek) { float b0A, b1A, b2A, a0A, a1A, a2A; SessionTwoDSP::calculusAnalogCoefficients (frequency, Q, 0.f, SessionTwoDSP::FilterType::Type_LowPass2, b0A, b1A, b2A, a1A, a2A); a0A = 1.f; b0A /= a2A; b1A /= a2A; b2A /= a2A; a0A /= a2A; a1A /= a2A; a2A /= a2A; std::complex<double> delta = a1A * a1A - 4 * a0A * a2A; std::complex<double> s1 = (std::complex<double> (-a1A) - std::sqrt (delta)) / std::complex<double> (2 * a2A); std::complex<double> s2 = (std::complex<double> (-a1A) + std::sqrt (delta)) / std::complex<double> (2 * a2A); auto e1 = std::exp (s1 * std::complex<double> (Ts)); auto e2 = std::exp (s2 * std::complex<double> (Ts)); auto e12 = std::exp ((s1 + s2) * std::complex<double> (Ts)); auto a1d = -std::real (e1 + e2); auto a2d = std::real (e12); a1 = (float)a1d; a2 = (float)a2d; auto A0 = std::pow (1 + a1d + a2d, 2); auto A1 = std::pow (1 - a1d + a2d, 2); auto A2 = -4 * a2; auto phi0 = 1 - std::pow (std::sin (w0 / 2 * Ts), 2); auto phi1 = std::pow (std::sin (w0 / 2 * Ts), 2); auto phi2 = 4 * phi0 * phi1; auto R1 = Q * Q * (A0 * phi0 + A1 * phi1 + A2 * phi2); auto B0 = A0; auto B1 = jmax (0.0, (R1 - B0 * phi0) / phi1); b0 = 0.5f * (float)(std::sqrt (B0) + std::sqrt (B1)); b1 = (float)(std::sqrt (B0)) - b0; b2 = 0.f; b3 = 0.f; b4 = 0.f; a3 = 0.f; a4 = 0.f; order = 2; } else { b0 = 1.f; b1 = 0.f; b2 = 0.f; b3 = 0.f; b4 = 0.f; a1 = 0.f; a2 = 0.f; a3 = 0.f; a4 = 0.f; order = 0; } } const double SessionThreeDSP::getMagnitudeForFrequency (double frequency, double sampleRate, const float b0, const float b1, const float b2, const float b3, const float b4, const float a1, const float a2, const float a3, const float a4) { constexpr std::complex<double> j (0, 1); jassert (frequency >= 0 && frequency <= sampleRate * 0.5); std::complex<double> numerator = 0.0, denominator = 0.0, factor = 1.0; std::complex<double> expjwT = std::exp (-MathConstants<double>::twoPi * frequency * j / sampleRate); numerator += ((double)b0) * factor; factor *= expjwT; numerator += ((double)b1) * factor; factor *= expjwT; numerator += ((double)b2) * factor; factor *= expjwT; numerator += ((double)b3) * factor; factor *= expjwT; numerator += ((double)b4) * factor; denominator = 1.0; factor = expjwT; denominator += ((double)a1) * factor; factor *= expjwT; denominator += ((double)a2) * factor; factor *= expjwT; denominator += ((double)a3) * factor; factor *= expjwT; denominator += ((double)a4) * factor; return std::abs (numerator / denominator); } const double SessionThreeDSP::getPhaseForFrequency (double frequency, double sampleRate, const float b0, const float b1, const float b2, const float b3, const float b4, const float a1, const float a2, const float a3, const float a4) { constexpr std::complex<double> j (0, 1); jassert (frequency >= 0 && frequency <= sampleRate * 0.5); std::complex<double> numerator = 0.0, denominator = 0.0, factor = 1.0; std::complex<double> expjwT = std::exp (-MathConstants<double>::twoPi * frequency * j / sampleRate); numerator += ((double)b0) * factor; factor *= expjwT; numerator += ((double)b1) * factor; factor *= expjwT; numerator += ((double)b2) * factor; factor *= expjwT; numerator += ((double)b3) * factor; factor *= expjwT; numerator += ((double)b4) * factor; denominator = 1.0; factor = expjwT; denominator += ((double)a1) * factor; factor *= expjwT; denominator += ((double)a2) * factor; factor *= expjwT; denominator += ((double)a3) * factor; factor *= expjwT; denominator += ((double)a4) * factor; return std::arg (numerator / denominator); }
3a3c0c6cf372bc08e1e084fdc557fceefc879606
[ "C", "C++" ]
35
C++
shossa3/DSPExamples
3afdcc1312be3ec5c943523f3861b5a19a443c88
1893456f1d54adda8115ff4299db5fba7745ccc6
refs/heads/master
<repo_name>ilackarms/kernel4fun<file_sep>/basic-i686-kernel/kernel.c /* Surely you will remove the processor conditionals and this comment appropriately depending on whether or not you use C++. */ #if !defined(__cplusplus) #include <stdbool.h> /* C doesn't have booleans by default. */ #endif #include <stddef.h> #include <stdint.h> /* Check if the compiler thinks we are targeting the wrong os */ #if defined(__linux__) #error "You are not using a cross-compiler, ain't gonna work bruh" #endif /* This kernel will only run on 32-bit ix86 targets. */ #if !defined(__i386__) #error "This kernel needs to be compiled with a ix86-elf compiler" #endif /* Hardware text mode color constants, */ enum vga_color { VGA_COLOR_BLACK = 0, VGA_COLOR_BLUE = 1, VGA_COLOR_GREEN = 2, VGA_COLOR_CYAN = 3, VGA_COLOR_RED = 4, VGA_COLOR_MAGENTA = 5, VGA_COLOR_BROWN = 6, VGA_COLOR_LIGHT_GREY = 7, VGA_COLOR_DARK_GREY = 8, VGA_COLOR_LIGHT_BLUE = 9, VGA_COLOR_LIGHT_GREEN = 10, VGA_COLOR_LIGHT_CYAN = 11, VGA_COLOR_LIGHT_RED = 12, VGA_COLOR_LIGHT_MAGENTA = 13, VGA_COLOR_LIGHT_BROWN = 14, VGA_COLOR_WHITE = 15, }; static inline uint8_t vga_entry_color(enum vga_color fg, enum vga_color bg) { return fg | bg << 4; } static inline uint16_t vga_entry(unsigned char uc, uint8_t color) { return (uint16_t) uc | (uint16_t) color << 8; } size_t strlen(const char* str) { size_t len = 0; while (str[len]) len++; return len; } static const size_t VGA_WIDTH = 80; static const size_t VGA_HEIGHT = 25; size_t terminal_row; size_t terminal_column; uint8_t terminal_color; uint16_t* terminal_buffer; void terminal_initialize(void) { terminal_row = 0; terminal_column = 0; terminal_color = vga_entry_color(VGA_COLOR_LIGHT_GREY, VGA_COLOR_BLACK); terminal_buffer = (uint16_t*) 0xB8000; for (size_t y = 0; y < VGA_HEIGHT; y++) { for (size_t x = 0; x < VGA_WIDTH; x++) { const size_t index = y * VGA_WIDTH + x; terminal_buffer[index] = vga_entry(' ', terminal_color); } } } void terminal_setcolor(uint8_t color) { terminal_color = color; } void terminal_putentryat(unsigned char c, uint8_t color, size_t x, size_t y) { const size_t index = y * VGA_WIDTH + x; terminal_buffer[index] = vga_entry(c, color); } void move_terminal_rows_up() { for (size_t y = 0; y < VGA_HEIGHT; y++) { for (size_t x = 0; x < VGA_WIDTH; x++) { const size_t index = y * VGA_WIDTH + x; terminal_buffer[index] = terminal_buffer[index+VGA_WIDTH]; } } } void terminal_putchar(unsigned char c) { if (c == '\n') { terminal_column = 0; if (++terminal_row == VGA_HEIGHT) { terminal_row--; move_terminal_rows_up(); } return; } terminal_putentryat(c, terminal_color, terminal_column, terminal_row); if (++terminal_column == VGA_WIDTH) { terminal_column = 0; if (++terminal_row == VGA_HEIGHT) { terminal_row--; move_terminal_rows_up(); } } } void terminal_write(const char* data, size_t size) { for (size_t i = 0; i < size; i++) terminal_putchar((unsigned char) data[i]); } void terminal_writestring(const char* data) { terminal_write(data, strlen(data)); } bool sleep_check; void fake_sleep(const size_t ms) { size_t j = 0; for (size_t i = 0; i < ms * 1000; i++) { j += i; } if (j) { sleep_check = !sleep_check; } } #if defined(__cplusplus) extern "C" /* Use C linkage for kernel_main. */ #endif void kernel_main(void) { /* initialize terminal interface */ terminal_initialize(); //print 250 lines, scroll for (size_t i = 0; i < 250; i++){ for (size_t j = 0; j < i % 11; j++) { terminal_writestring("p"); } fake_sleep(20000); terminal_writestring("\n"); } if (sleep_check) { terminal_writestring("Finished.\n"); } }<file_sep>/basic-i686-kernel/Makefile all: kernel.bin kernel.bin: linker.ld boot.o kernel.o i686-elf-gcc -T linker.ld -o kernel.bin -ffreestanding -O2 -nostdlib boot.o kernel.o -lgcc boot.o: boot.s i686-elf-as boot.s -o boot.o kernel.o: kernel.c i686-elf-gcc -c kernel.c -o kernel.o -std=gnu99 -ffreestanding -O2 -Wall -Wextra .PHONY: clean clean: rm -f boot.o kernel.o kernel.bin
bb12e3f70036784bc503c127e43585d4fc33fd2f
[ "C", "Makefile" ]
2
C
ilackarms/kernel4fun
337be65a7df94ff19289b7ce95ca5789271aa19a
f0cfed1d7284f43306e9826536ba9171b73347d6
refs/heads/master
<file_sep># glscope WebGL Oscilloscope <file_sep>import { createShader, createProgram } from './util'; // const SPECTOR = require('spectorjs'); // const spector = new SPECTOR.Spector(); // spector.displayUI(); export const vertexShaderSource = `#version 300 es // an attribute is an input (in) to a vertex shader. // It will receive data from a buffer in vec2 a_position; uniform vec4 u_color; uniform vec2 u_scale; uniform vec2 u_xRange; uniform vec2 u_yRange; out vec4 v_color; // all shaders have a main function void main() { // gl_Position is a special variable a vertex shader // is responsible for setting vec2 t_position = vec2( ((a_position.x - u_xRange.x) / (u_xRange.y - u_xRange.x)) * 2.0 + -1.0, ((a_position.y - u_yRange.x) / (u_yRange.y - u_yRange.x)) * 2.0 + -1.0 ); v_color = u_color; gl_Position = vec4(t_position * u_scale, 0.0, 1.0); } `; export const fragmentShaderSource = `#version 300 es // fragment shaders don't have a default precision so we need // to pick one. highp is a good default. It means "high precision" precision highp float; in vec4 v_color; // we need to declare an output for the fragment shader out vec4 outColor; void main() { outColor = v_color; } `; export interface GlscopeSignal { color: number[], data: number[], }; export class Glscope { private gl: WebGL2RenderingContext; private program: WebGLProgram | undefined = undefined; private positionAttribLocation: number = -1; private colorLocation: WebGLUniformLocation | null = null; private scaleLocation: WebGLUniformLocation | null = null; private yRangeLocation: WebGLUniformLocation | null = null; private xRangeLocation: WebGLUniformLocation | null = null; private _scale: number[] = []; private _xRange: number[] = []; private _yRange: number[] = []; private signals: GlscopeSignal[] = []; constructor(canvas: HTMLCanvasElement) { const gl = canvas.getContext('webgl2', { alpha: false, antialias: false, }); if (gl) { this.gl = gl; } else { throw new Error('Cannot get webgl2 context from canvas.'); } gl.canvas.addEventListener('mousemove', (ev: any) => { const x: number = ev.clientX; const out = this.signals.map(signal => [signal.data[x * 2], signal.data[x * 2 + 1]]); console.log(JSON.stringify(out)); }); gl.canvas.addEventListener('mousewheel', (ev: any) => { const dy: number = ev.deltaY; const scale = dy * 0.0005; this.scale = [this.scale[0] + scale, this.scale[1] + scale]; }); } get scale() { return this._scale; } set scale(values: number[]) { if (this.scaleLocation) { this._scale = values; this.gl.uniform2fv(this.scaleLocation, new Float32Array(this.scale)); } else { throw new Error('Scale location is not initalized.') } } get xRange() { return this._xRange; } set xRange(values: number[]) { if (this.xRangeLocation) { this._xRange = values; this.gl.uniform2fv(this.xRangeLocation, new Float32Array(this.xRange)); } else { throw new Error('X range location is not initalized.') } } get yRange() { return this._yRange; } set yRange(values: number[]) { if (this.yRangeLocation) { this._yRange = values; this.gl.uniform2fv(this.yRangeLocation, new Float32Array(this.yRange)); } else { throw new Error('Y range location is not initalized.') } } init(): void { const vertexShader = createShader(this.gl, this.gl.VERTEX_SHADER, vertexShaderSource); const fragmentShader = createShader(this.gl, this.gl.FRAGMENT_SHADER, fragmentShaderSource); if (vertexShader && fragmentShader) { this.program = createProgram(this.gl, vertexShader, fragmentShader); if (this.program) { // Tell WebGL how to convert from clip space to pixels this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height); this.positionAttribLocation = this.gl.getAttribLocation(this.program, 'a_position'); // Tell it to use our program (pair of shaders) this.gl.useProgram(this.program); this.colorLocation = this.gl.getUniformLocation(this.program, 'u_color'); this.scaleLocation = this.gl.getUniformLocation(this.program, 'u_scale'); this.xRangeLocation = this.gl.getUniformLocation(this.program, 'u_xRange'); this.yRangeLocation = this.gl.getUniformLocation(this.program, 'u_yRange'); this.xRange = [0, 50000]; this.yRange = [-1000, 1000]; this.scale = [1, 1]; const self = this; function loop() { self.gl.clearColor(0.0, 0.0, 0.0, 1.0); self.gl.clear(self.gl.COLOR_BUFFER_BIT | self.gl.DEPTH_BUFFER_BIT); for (const signal of self.signals) { self.draw(signal.data, signal.color); self.gl.drawArrays(self.gl.LINE_STRIP, 0, signal.data.length / 2); } requestAnimationFrame(loop); } requestAnimationFrame(loop); } } } addSignal(signal: GlscopeSignal) { this.signals.push(signal); } addData(index: number, time: number, amplitude: number) { this.signals[index].data.push(time, amplitude); } draw(vertices: number[], color: number[]) { if (this.program) { const torqueVertexBufferObject = this.gl.createBuffer(); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, torqueVertexBufferObject); this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(vertices), this.gl.STATIC_DRAW); this.gl.uniform4fv(this.colorLocation, new Float32Array(color)); this.gl.vertexAttribPointer( this.positionAttribLocation, // attribute location (index) 2, // number of elements per attribute (2 components per iteration) this.gl.FLOAT, // type of elements false, // normalized 0, // 0 = move forward size * sizeof(type) each iteration to get the next position 0, // start at the beginning of the buffer ); this.gl.enableVertexAttribArray(this.positionAttribLocation); } } } <file_sep>export function createShader(gl: WebGL2RenderingContext, type: number, source: string) { const shader = gl.createShader(type); if (shader) { gl.shaderSource(shader, source); gl.compileShader(shader); const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (success) { return shader; } console.log(gl.getShaderInfoLog(shader)); gl.deleteShader(shader); } } export function createProgram(gl: WebGL2RenderingContext, vertexShader: WebGLShader, fragmentShader: WebGLShader) { const program = gl.createProgram(); if (program) { gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); const success = gl.getProgramParameter(program, gl.LINK_STATUS); if (success) { return program; } console.log(gl.getProgramInfoLog(program)); gl.deleteProgram(program); } } <file_sep>const path = require('path'); const fs = require('fs'); const csvPath = path.resolve(__dirname, process.argv[2]); const yindex = parseInt(process.argv[3]); const contents = fs.readFileSync(csvPath, { encoding: 'utf8' }); let data = contents.split('\n'); data.shift(); data = data.map(line => line.split(',').map(n => Number(n))); data = data.reduce((prev, curr) => { prev.push(`${parseFloat(curr[0])},${parseFloat(curr[yindex])}`); return prev; }, []); process.stdout.write(`[${data.join(',')}]\n`);
b5dd83b228e383d87f23fd365405ef59d675434a
[ "Markdown", "TypeScript", "JavaScript" ]
4
Markdown
markosankovic/glscope
5816a07cd044bf7fa036277c1bf4a54e2741c253
bd605b24a93fe6622c2ac3f0014fdfcba6d0a093
refs/heads/master
<file_sep>/* *********************************************************************** Cach tinh: + Buoc 1. Tinh electron_population[s][v][i]: N_s,v,i - Phuong phap 1: Nearest grid points cho huong thep phuong x - Phuong phap 2: NEC (Nearest-Element-Center) + Buoc 2. Tinh Ns la tong cua N_s,v,i theo v va i + Buoc 3. Tinh Psi_s,v,i(y,z) square + Buoc 4 va 5. Tinh electron density [1/m3] electron density se la dau vao cho Poisson Starting date: March 30, 2010 Update: March 31, 2010 Update: May 20, 2010 MOT LOI rat CO BAN. Can reset gia tri electron_density cho lan chay ke tiep. Vi no la tinh tong va lap di lap lai nhieu lan theo thoi gian Latest update: June 2, 2010. Da mo rong electron density ra ca vung Oxide nhung KHONG TINH o BIEN ************************************************************************* */ #include <stdio.h> #include "mpi.h" #include "nrutil.h" void electron_density_caculation(){ // Goi ham double ***Get_electron_density(); int Get_save_electron_population(); int Get_save_electron_density(); void save_electron_population(double ***electron_population, int nx_max, int v_max, int NSELECT); int Get_NSELECT(); int Get_n_used();// Vi ham nay NGAY SAU ham delete_particle() nen n_used o day CHI BAO GOM iv=1,2,3 double **Get_p(),Get_mesh_size_x(),Get_mesh_size_y(),Get_mesh_size_z(); int *Get_valley(),*Get_subband(); double *****Get_wave(); // Lay wave function tu 2D Schrodinger // Cac bien local double ***electron_density = Get_electron_density(); int electron_population_save_or_not = Get_save_electron_population();// Co save vao file khong ? int electron_density_save_or_not = Get_save_electron_density(); int Get_nx0(),Get_nx1(), Get_nya(),Get_nyb(),Get_nza(),Get_nzb(); int nx0 = Get_nx0(); int nx1 = Get_nx1();// da thay doi thanh electron_density = d3matrix(nx0,nx1,0,ny,0,nz);ny=nyb-nya, nz=nzb-nza int nya = Get_nya(); int nyb = Get_nyb();// Nhung do wave function chi lay o LOI Silicon nen ta chi tinh trong doan do thoi int nza = Get_nza(); int nzb = Get_nzb(); int nx_max = nx1-nx0; // int nx_max = Get_nx_max(); int ny_max = nyb - nya;// De thay doi it nhat co the int nz_max = nzb - nza; int NSELECT = Get_NSELECT(); int n_used = Get_n_used(); //printf("\n n_used at electron_density_caculation() = %d",n_used); double mesh_size_x = Get_mesh_size_x(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); double **p = Get_p(); int *valley = Get_valley(); int *subband = Get_subband(); double *****wave = Get_wave(); // Thuc hien int s,v,i,n,j,k; double x_position; double ***electron_population;// N_s,v,i: electron population cho MOI section s-th, valley v-th va subband i-th double *Ns; // Bien trung gian la tong cua N_s,v,i theo v va i double *****wave_square; // bien trung gian de tinh wave * wave electron_population = d3matrix(0,nx_max,1,3,1,NSELECT);// Can khoi tao Ns = dvector(0,nx_max); // chay cho tat ca cac section wave_square = d5matrix(0,nx_max,1,3,1,NSELECT,0,ny_max,0,nz_max); for(s=0; s<=nx_max; s++){ Ns[s] = 0.0; for(v=1; v<=3; v++){ for(i=1; i<=NSELECT; i++){ electron_population[s][v][i]=0.0; for(j=0; j<=ny_max; j++){ // chay cho diem tren truc y for(k=0; k<=nz_max; k++){// chay cho diem tren truc z wave_square[s][v][i][j][k] = 0.0; } } } } } // End of for(s=0; s<=nx_max; s++){ // Buoc 1: Tinh electron population /* //Cach 1. Nearest grid points for(n = 1; n<=n_used; n++){ if(valley[n] != 9){ x_position = p[n][2]; s = (int)(x_position/mesh_size_x + 0.5);// vi tri section cua hat n-th. PHAI CONG THEM 0.5 nhe if(s < 0) { s = 0;} if(s > nx_max) { s = nx_max;} // De khong vuot qua chi so mang v = valley[n]; // valley cua hat thu n-th i = subband[n]; // subband cua hat n-th electron_population[s][v][i] += 1; // tai cac vi tri s,v,i thi tang len 1 }// End of if(valley[n] != 9) }// End of for(n = 1; n<=n_used; n++) */ // Ket thuc cach 1 ///* // Cach 2: NEC (Nearest-Element-Center) for(n = 1; n<=n_used; n++){ if(valley[n] != 9){// chi xet hat co iv=1,2,3 ma thoi. Thuc ra khong can lenh nay. Nhung lam cho chac x_position = p[n][2]; s = (int)(x_position/mesh_size_x + 0.5); // vi tri section cua hat n-th if(s < 0) { s=0;} if(s>=nx_max){ s=nx_max-1;}// do phuong phap NEC yeu cau v = valley[n]; // valley cua hat thu n-th i = subband[n]; // subband cua hat n-th electron_population[s][v][i] += 0.5; // electron_population[s+1][v][i] += 0.5; }// End of if(valley[n] != 9) }// End of for(n = 1; n<=n_used; n++) // Trick de tranh tao ra electron density qua bien doi. Co can dung TRICK khong? CHUA BIET 01/04/10 14:28 //electron_population[0][v][i] = 2.0*electron_population[0][v][i];//((s==0)||(s==nx_max)) thi nhan cho 2 //electron_population[nx_max][v][i] = 2.0*electron_population[nx_max][v][i]; //*/ // Ket thuc cach 2 int myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); if(myrank ==0){ // Save tai mot node thoi //SAVE electron population or NOT if (electron_population_save_or_not ==1){ // =1: Co SAVE int v_max=3;// la 3 valley pairs vao the nay cho chuyen nghiep save_electron_population(electron_population,nx_max,v_max,NSELECT); } } // Buoc 2. Tinh Ns la tong cua N_s,v,i the v va i for(s=0; s<=nx_max; s++){ for(v=1; v<=3; v++){ for(i=1; i<=NSELECT; i++){ Ns[s] += electron_population[s][v][i]; } } }// End of for(s=0; s<=nx_max; s++) //for(s=0; s<=nx_max; s++){ //printf("\n Number of partice at s-th %d =%f",s,Ns[s]); //if(Ns[s]== 0.0){ //printf("\n Ns[%d]=%f",s,Ns[s]); // Ns[s] = 1.0e-1;} //(May 28, 2010) (SAI: Co the) trick de tranh chia cho 0 luc tinh electron_density. Xay ra luc KIEM TRA nhu the nay //} // Buoc 3: Tinh Psi_s,v,i(y,z) square for(s=0; s<=nx_max; s++){ for(v=1; v<=3; v++){ for(i=1; i<=NSELECT; i++){ for(j=0; j<=ny_max; j++){ // Chay tu 0 da the hien so diem chia la + 1 roi (May 30, 2010) for(k=0; k<=nz_max; k++){ wave_square[s][v][i][j][k] = wave[s][v][i][j][k]*wave[s][v][i][j][k]; } } } } } // End of for(s=0; s<=nx_max; s++){ // Buoc 4. Tinh electron_density [1/m3] // Truoc khi tinh electron_density can reset no vi neu khong lai tinh ca lan truoc do - no la tinh TONG va duoc lap di lap lai theo thoi gian // Buoc 4.1. Reset. NHUNG CHI O PHAN LOI SILICON THOI (June 02, 2010) for(s=0; s<=nx_max; s++){ for(j=nya; j<=nyb; j++){ for(k=nza; k<=nzb; k++){ electron_density[s][j][k]=0.0;// Phan Loi silicon cho ve 0 } } } // Buoc 4.2. Tinh toan gia tri CAN DICH HE TOA DO for(s=0; s<=nx_max; s++){ if(Ns[s] != 0.0){// Vi neu khong co hat nao o trong section thi co nghia la electron_population=0 do do electron_density =0 (May 28, 2010) for(v=1; v<=3; v++){ for(i=1; i<=NSELECT; i++){ for(j=0; j<=ny_max; j++){ for(k=0; k<=nz_max; k++){ electron_density[s][j+nya][k+nza] += (electron_population[s][v][i]/Ns[s])*wave_square[s][v][i][j][k]; // printf("\n electron_density = %le",electron_density[s][j][k]); } } } } }// End of if(Ns[s] =! 0.0){ }// End of for(s=0; s<=nx_max; s++) // Buoc 5: Tinh electron density theo THE TICH [1/m3]. Chi tinh tai loi Silicon //double volume = mesh_size_x*mesh_size_y*mesh_size_z;//the tich. SAI hat bay gio theo phuong x la classical con theo y va z la quantum double volume = mesh_size_x*mesh_size_y*ny_max*mesh_size_z*nz_max; for(s=0; s<=nx_max; s++){ for(j=0; j<=ny_max; j++){ for(k=0; k<=nz_max; k++){ electron_density[s][j+nya][k+nza] = electron_density[s][j+nya][k+nza]/volume;// [1/m3] } } }// End of for(s=0; s<=nx_max; s++) // Free local variables free_d3matrix(electron_population,0,nx_max,1,3,1,NSELECT); free_dvector(Ns,0,nx_max); free_d5matrix(wave_square,0,nx_max,1,3,1,NSELECT,0,ny_max,0,nz_max); return; } // End of electron_density_caculation /* ***************************************************************************** De SAVE N_s,v,i: electron population cho MOI section s-th, valley v-th va subband i-th INPUT: + electron_population[s][v][i] + s: so section di tu 0 den nx_max + v=1,2,or 3: 3 cap valley pairs + i=1 den NSELECT so subbands cho moi valley OUTPUT: + SAVE electron_population[s][v][i] Starting date: March 30, 2010 Latest update: March 30, 2010 ***************************************************************************** */ void save_electron_population(double ***electron_population,int nx_max,int v_max,int NSELECT){ FILE *f; f = fopen("Electron_population.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL) { printf("\n Cannot open file Electron_population.dat"); return ; } fprintf(f,"\n #section valley subband Number_of_Electron \n"); int s,v,i; for(s=0; s<=nx_max; s++){ for(v=1; v<=v_max; v++){ for(i=1; i<=NSELECT; i++){ fprintf(f," %d %d %d %f\n",s,v,i,electron_population[s][v][i]); } } } fclose(f); return; } // End of void save_Density_of_State_1D(int s_th) /* ***************************************************************************** De SAVE electron_density[s][y][z] co nghia la electron_density[x][y][z] INPUT: + electron_density[s-th][j][k] + s-th: dinh save o section nao? Cu the 1 section ma thoi tu 0 den nx_max + j: diem chay theo phuong y di tu 0 den ny_max (ny_max = nyb - nya) + k: diem chay theo phuong z di tu 0 den nz_max (nz_max = nzb - nza) OUTPUT: + SAVE electron_density[s-th][y][z] tai s-th section Starting date: March 31, 2010 Latest update: June 15, 2010 ***************************************************************************** */ void save_electron_density(char *fn) { double ***Get_electron_density(); double ***electron_density = Get_electron_density(); double Get_mesh_size_y(),Get_mesh_size_z(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); int Get_nx0(),Get_nx1(), Get_nya(),Get_nyb(),Get_nza(),Get_nzb(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nya = Get_nya(); int nyb = Get_nyb(); int nza = Get_nza(); int nzb = Get_nzb(); int nx_max = nx1-nx0; int ny_max = nyb - nya;// De thay doi it nhat co the int nz_max = nzb - nza; FILE *f;f = fopen(fn,"w"); // "w" neu tep ton tai no se bi xoa //f = fopen("Electron_Density.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL) { printf("\n Cannot open file at save_electron_density.c"); return ; } fprintf(f,"\n #y z electron_density[1/m3] section_th \n"); int myrank, i,j, s_th; double y,z; // x MPI_Comm_rank(MPI_COMM_WORLD,&myrank); if(myrank == 0){ // Save tai mot node thoi s_th =(int)(nx_max/2 + 0.5); // Luon save cho section o GIUA // NOTE: nen o nhung time step dau tien co the no se bang 0 // ngay time step dau tien thi voi s_th=3 Ket qua electron_density rat dep for(i=0; i<=ny_max; i++){ y = (double)(i)*mesh_size_y/1.0e-9;// doi tu [m] sang [nm] for(j=0; j<=nz_max; j++){ z = (double)(j)*mesh_size_z/1.0e-9;// doi tu [m] sang [nm] fprintf(f," %le %le %le %d \n",y,z,electron_density[s_th][i+nya][j+nza],s_th); } } } fclose(f); return; } // End of void save_Density_of_State_1D(int s_th) /* ***************************************************************************** De SAVE electron_density[s][y][z] co nghia la electron_density[x][y][z] INPUT: + electron_density[s-th][j][k] + s-th: save for all sections + j: diem chay theo phuong y di tu 0 den ny_max (ny_max = nyb - nya) + k: diem chay theo phuong z di tu 0 den nz_max (nz_max = nzb - nza) OUTPUT: + SAVE electron_density[s][y][z] tai all sections Note: For checing only Starting date: June 04, 2010 Latest update: June 04, 2010 ***************************************************************************** */ void save_electron_density_all_sections(char *fn) { double ***Get_electron_density(); double ***electron_density = Get_electron_density(); int Get_nx0(),Get_nx1(), Get_nya(),Get_nyb(), Get_nza(),Get_nzb();// int Get_nya(), Get_nza();// Can dich he toa do int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nya = Get_nya(); int nyb = Get_nyb(); int nza = Get_nza(); int nzb = Get_nzb(); int ny_max = nyb - nya;// De thay doi it nhat co the int nz_max = nzb - nza; double Get_mesh_size_y(),Get_mesh_size_z(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); // Thuc hien FILE *f; f = fopen(fn,"w"); // "w" neu tep ton tai no se bi xoa //f = fopen("Electron_Density_All_Sections.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL) { printf("\n Cannot open file at save_electron_density_all_sections.c"); return ; } fprintf(f,"\n #y z electron_density[1/m3] section_th \n"); int s,i,j,myrank; double y,z; // x MPI_Comm_rank(MPI_COMM_WORLD,&myrank); if(myrank ==0){ // Save tai mot node thoi for(s=nx0; s<=nx1; s++){ for(i=0; i<=ny_max; i++){ y = (double)(i)*mesh_size_y/1.0e-9;// doi tu [m] sang [nm] for(j=0; j<=nz_max; j++){ z = (double)(j)*mesh_size_z/1.0e-9;// doi tu [m] sang [nm] fprintf(f," %le %le %le %d \n",y,z,electron_density[s][i+nya][j+nza],s); } } } } fclose(f); return; } // End of void save_Density_of_State_1D(int s_th) <file_sep>#include "nanowire.h" static int PRINT_MidPotFlag ; static int PRINT_Pot3dFlag ; void SetPRINT_MidPotFlag(int n) { PRINT_MidPotFlag = n ; } void SetPRINT_Pot3dFlag(int n ) { PRINT_Pot3dFlag = n ; } int GetPRINT_MidPotFlag() { return(PRINT_MidPotFlag) ; } int GetPRINT_Pot3dFlag() { return(PRINT_Pot3dFlag) ; } void print_output() { // print outputs char fn[100] ; double vd = GetDrainVoltage() ; double vg = GetGateVoltage() ; if ( GetPRINT_Pot3dFlag() ) sprintf(fn,"pot3d.r-Vd%.2lf-Vg%.2lf",vd,vg) ; else sprintf(fn,"pot3d.r") ; print_potential_plain(fn) ; if ( GetPRINT_MidPotFlag() ) { sprintf(fn,"mpot.r") ; print_midline_potential_plain(fn) ; } } <file_sep>#define kB (1.380650e-23) /* Boltzmann Constant */ #define Planck (6.626068e-34) /* Planck Constant */ #define M0 (9.109382e-31) /* Free Electron Mass */ #define Pi (3.1415926535) /* Pi */ #define q0 (1.602176e-19) /* Electron Charge */ #define e_0 (8.854188e-12) /* Permittivity in vacuum */ #define NANOM 1.0e-09 #define sqrt2 1.4142135623730950 #define sqrt3 1.7320508075688773 <file_sep>/* **************************************************************** Ham de thuc hien viec giai 2D Schrodinger cho tat ca cross-section va 3 cap valley pairs. INPUT: + s: s-th section + v: v-th valley pair + m1,m2: la hai tham so cho cac valley pairs. Vi du (m1=0.19, m2=0.916) + potential Phi(i,j,k) tu viec guest potential va sau do tu 3D Poisson OUTPUT: + E_s,v,i (eigen energy for each cross-section, valley pair and subband + Wave_s,v,i(y,z): wave tuong ung Starting date: Feb 23, 2010 Update: Feb 24, 2010 Update: May 09, 2010 (Them tham so de mapping voi 3D Poisson) Update: May 10, 2010 (Parallel) Latest update: May 30: SUA SAI o SO DIEM CHIA. THUC TE SO DIEM CHIA o cross-section CAN TANG THEM 1 ****************************************************************** */ #include <stdio.h> #include <math.h> #include <string.h> #include "petscksp.h" #include "nanowire.h" #include "region.h" #include "nrutil.h" #include "constants.h" #include "mpi.h" void Solved_2D_Schro_Parallel_for_MSMC(int *argc, char ***argv){ // Goi cac ham void Schrodinger2D(int s, int v, double m1, double m2); // Cac bien local int Get_nx0(),Get_nx1(); // int Get_nx_max(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; //printf("\n nx0=%d, nx1=%d,nx_max=%d",nx0,nx1,nx_max);// de thay doi it nhat int NXMAX = nx_max+1;// Do ta chay section tu 0 den nx_max nen tong so lan can chay la NXMAX double Get_ml(), Get_mt(); double ml = Get_ml(); double mt = Get_mt(); //printf("\n ml=%f, mt=%f", ml,mt); int Get_NSELECT(); int NSELECT = Get_NSELECT(); int Get_nya(),Get_nyb(),Get_nza(),Get_nzb(); int nya = Get_nya(); int nyb = Get_nyb(); int nza = Get_nza(); int nzb = Get_nzb(); int ny_max = nyb - nya; int nz_max = nzb - nza; int ny = ny_max + 1;// (May 30, 2010) int ny = ny_max; Do so diem chia tren loi Silicon can +1 int nz = nz_max + 1; //int nz = nz_max; // Thuc hien int s,v; // s-th section, v-th valley pair double m1, m2; int size,rank;// So luong processor va rank tuong ung int ierr; // thong bao loi // Buoc 1. Lay rank va size ierr = MPI_Comm_size(MPI_COMM_WORLD, &size);// Lay number of processor; // Initialize MPI o ham main() roi ierr = MPI_Comm_rank(MPI_COMM_WORLD, &rank);// lay rank cua this process if ( rank==0 ){ // master node printf ( "\n" ); printf ( "The number of processes is %d\n", size ); if (size==1){ //printf("\n KHONG CHAY SONG SONG o Master node: STOP"); //exit(1);//Se dung lenh nay khi KHONG su dung master node } }// End of if ( rank==0 ) //NOTE.chay tai rank=0,1,2,3,4. printf("\n Chay cho cac valley"); // Buoc 2. Chay SONG SONG cho cac node. Moi node ung voi rank cua minh se giai 2D Schrodinger o cac section khac nhau // Dau tien phai cho eig va wave ve 0. Neu chay 1 node thi khong can nhung ta lai chay nhieu node va moi node thi ghi 1 phan du lieu vao. Nen can // xoa du lieu cu double ***Get_eig(), *****Get_wave(); double ***eig = Get_eig(); double *****wave = Get_wave(); int i,j,k; for(s=nx0; s<=nx1; s++){ for(v=1; v<=3; v++){ for(i=1; i<=NSELECT; i++){ eig[s][v][i] = 0.0; for(j=0; j<=ny_max; j++){// Chay tu 0 den ny_max = nyb-nya da the hien so diem chia can cong them 1 for(k=0; k<=nz_max; k++){ wave[s][v][i][j][k] = 0.0; } } } } } // Valley pair 1. m1 = mt; m2 = mt; v = 1; for(s=NXMAX*(rank)/(size); s<=(NXMAX*(rank+1))/(size)-1; s++){// Cong thuc khi chay ca Master node //printf("\n ***********************"); Schrodinger2D(s,v,m1,m2); //printf("\n The section %d with valley %d are solved",s,v); } // Valley pair 2 m1 = ml; m2 = mt; v = 2; for(s=NXMAX*(rank)/(size); s<=(NXMAX*(rank+1))/(size)-1; s++){// Cong thuc khi chay ca Master node //printf("\n ***********************"); Schrodinger2D(s,v,m1,m2); //printf("\n The section %d with valley %d are solved",s,v); } // Valley pair 3. // chi can giai khi no khong doi xung. Tinh Sau m1 = mt; m2 = ml; v = 3; for(s=NXMAX*(rank)/(size); s<=(NXMAX*(rank+1))/(size)-1; s++){// Cong thuc khi chay ca Master node //printf("\n ***********************"); Schrodinger2D(s,v,m1,m2); //printf("\n The section %d with valley %d are solved",s,v); } // Buoc 3. Sau khi chay song song thi cac MANG eig va wave o cac node chi luu cac gia tri ma no SOLVE thoi // LAP DAY cac gia tri cua eig va wave o cac node. Ta KHOI TAO mang eig va wave giong nhau ve KICH THUOC cho tat ca cac node. void convert_3Dmatrix_to_array(int M, int N,int P, double ***mtx, double *a);// Su dung cho eigen energy void convert_array_to_3Dmatrix(int M, int N,int P, double *a, double ***mtx); void convert_5Dmatrix_to_array(int M, int N,int P,int Q,int R, double *****mtx, double *a);// su dung cho wave void convert_array_to_5Dmatrix(int M, int N,int P,int Q,int R, double *a,double *****mtx); int Get_save_eig_wavefuntion(); // Flag chi ra co SAVE hay KHONG? // Buoc 3.1. Thuc hien cho eigen int count1 = NXMAX*3*NSELECT;//number of elements cua eigen energy to be sent. PHU THUOC section, valley, subband double *eig_array = dvector(0,count1);//do ***eig la mang 3 chieu ta can chuyen no sang mang 1 chieu double *eig_sum = dvector(0,count1);//tong eigen-energy tu TAT CA cac node: LAP DAY gia tri eigen TUONG UNG cho chay NOI TIEP for(i=0; i<=count1; i++){ eig_array[i]=0.0; eig_sum[i]=0.0; } convert_3Dmatrix_to_array(nx_max,3,NSELECT,eig,eig_array);// chuyen 3D eigen thanh 1D eigen MPI_Allreduce(eig_array,eig_sum,count1+1,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);// Su dung ham MPI_Allreduce de CONG va PHAN BO cho tat ca cac node convert_array_to_3Dmatrix(nx_max,3,NSELECT, eig_sum,eig);// Chuyen lai 1D eigen thanh 3D eigen // Buoc 3.2. Thuc hien cho wave (May 13, 2010) int count2 = NXMAX*3*NSELECT*ny*nz;//number of elements cua wave to be sent. PHU THUOC section, valley, subband, y va z // vi index 0 den ny_max tu la co ny=ny_max+1 diem double *wave_array = dvector(0,count2);//do *****wave la mang 5 chieu ta can chuyen no sang mang 1 chieu double *wave_sum = dvector(0,count2);//tong wave tu TAT CA cac node: LAP DAY gia tri wave TUONG UNG cho chay NOI TIEP for(i=0; i<=count2; i++){ wave_array[i]=0.0; wave_sum[i]=0.0; } convert_5Dmatrix_to_array(nx_max,3,NSELECT,ny_max,nz_max,wave,wave_array);//chuyen 5D wave thanh 1D wave MPI_Allreduce(wave_array,wave_sum,count2+1,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);// chay 3 section 5x5 thi thoi gian khong dang ke convert_array_to_5Dmatrix(nx_max,3,NSELECT,ny_max,nz_max,wave_sum,wave); // */ /* Se dung cai nay if (rank !=0){// Ta khong chay o master node. Ta chi chay tai rank=1,2,3,4..thoi // Valley pair 1 m1 = mt; m2 = mt; v = 1; for(s=NXMAX*(rank-1)/(size-1); s<=(NXMAX*rank)/(size-1)-1; s++)// Cong thuc khi KHONG DUNG master node { //printf("\n ***********************");//printf("\n The section %d with valley %d are solving",s,v); Schrodinger2D(s,v,m1,m2); } // Valley pair 2 m1 = ml; m2 = mt; v = 2; for(s=NXMAX*(rank-1)/(size-1); s<=(NXMAX*rank)/(size-1)-1; s++) { //printf("\n ***********************"); //printf("\n The section %d with valley %d are solving",s,v); Schrodinger2D(s,v,m1,m2); } // Valley pair 3. // chi can giai khi no khong doi xung. Tinh Sau m1 = mt; m2 = ml; v = 3; for(s=NXMAX*(rank-1)/(size-1); s<=(NXMAX*rank)/(size-1)-1; s++) { //printf("\n ***********************"); //printf("\n The section %d with valley %d are solving",s,v); Schrodinger2D(s,v,m1,m2); } } // End of if (rank !=0){ */ // Free local variables free_dvector(eig_array,0,count1); free_dvector(eig_sum,0,count1); free_dvector(wave_array,0,count2); free_dvector(wave_sum,0,count2); return; } // End of Solved_2D_Schro_Parallel_for_MSMC(int *argc, char ***argv) void convert_3Dmatrix_to_array(int M, int N,int P, double ***mtx, double *a) {//eig = d3matrix(0,nx1,1,3,1,NSELECT); int i,j,p; int k = 0 ; for(p=1; p<=P; p++){ for ( j=1 ; j<=N ; j++ ){ for ( i=0 ; i<=M ; i++ ){ a[k++] = mtx[i][j][p]; } } } } void convert_array_to_3Dmatrix(int M, int N,int P, double *a, double ***mtx) { int i,j,p; int k = 0 ; for(p=1; p<=P; p++){ for ( j=1 ; j<=N ; j++ ){ for ( i=0 ; i<=M ; i++ ){ mtx[i][j][p] = a[k++]; } } } } void convert_5Dmatrix_to_array(int M, int N,int P,int Q,int R, double *****mtx, double *a) {//wave = d5matrix(nx0,nx1,1,3,1,NSELECT,0,ny,0,nz);//cua Loi Silicon; nx0=0;// xem ham initial_variable() int i,j,p,qq,r; int k = 0 ; for(r=0; r<=R; r++){//cho z for(qq=0; qq<=Q; qq++){// cho y for(p=1; p<=P; p++){// subband for ( j=1 ; j<=N ; j++ ){//valley for ( i=0 ; i<=M ; i++ ){//section a[k++] = mtx[i][j][p][qq][r]; } } } } } } void convert_array_to_5Dmatrix(int M, int N,int P,int Q,int R,double *a, double *****mtx) { int i,j,p,qq,r; int k = 0 ; for(r=0; r<=R; r++){//cho z for(qq=0; qq<=Q; qq++){// cho y for(p=1; p<=P; p++){// subband for ( j=1 ; j<=N ; j++ ){//valley for ( i=0 ; i<=M ; i++ ){//section mtx[i][j][p][qq][r]= a[k++]; } } } } } } /* **************************************************************** Ham de thuc hien viec giai 2D Schrodinger cho tat ca cross-section va 3 cap valley pairs. INPUT: + s: s-th section + v: v-th valley pair + m1,m2: la hai tham so cho cac valley pairs. Vi du (m1=0.19, m2=0.916) + potential Phi(i,j,k) tu viec guest potential va sau do tu 3D Poisson OUTPUT: + E_s,v,i (eigen energy for each cross-section, valley pair and subband + Wave_s,v,i(y,z): wave tuong ung Starting date: Feb 23, 2010 Latest update: Feb 24, 2010 Latest update: May 09, 2010 (Them tham so de mapping voi 3D Poisson) ****************************************************************** */ #include <stdio.h> #include <math.h> #include <string.h> #include "nrutil.h" #include "constants.h" void Solved_2D_Schro_for_MSMC(){ // Goi cac ham void Schrodinger2D(int s, int v, double m1, double m2); int Get_nx0(),Get_nx1(); // int Get_nx_max(); double Get_ml(), Get_mt(); // Cac bien local int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; //printf("\n nx0=%d, nx1=%d,nx_max=%d",nx0,nx1,nx_max);// de thay doi it nhat double ml = Get_ml(); double mt = Get_mt(); //printf("\n ml=%f, mt=%f", ml,mt); // Thuc hien int s,v; // s-th section, v-th valley pair double m1, m2; ///* int Get_NSELECT(); int NSELECT = Get_NSELECT(); int Get_nya(),Get_nyb(),Get_nza(),Get_nzb(); int nya = Get_nya(); int nyb = Get_nyb(); int nza = Get_nza(); int nzb = Get_nzb(); int ny_max = nyb - nya; int nz_max = nzb - nza; double ***Get_eig(), *****Get_wave(); double ***eig = Get_eig(); double *****wave = Get_wave(); int i,j,k; // Reset eigen va wave moi lan goi 2D Schrodinger for(s=nx0; s<=nx1; s++){ for(v=1; v<=3; v++){ for(i=1; i<=NSELECT; i++){ eig[s][v][i] = 0.0; for(j=0; j<=ny_max; j++){// Chay tu 0 den ny_max = nyb-nya da the hien so diem chia can cong them 1 for(k=0; k<=nz_max; k++){ wave[s][v][i][j][k] = 0.0; } } } } } // Valley pair 1 m1 = mt; m2 = mt; v = 1; for(s=0; s<=nx_max; s++){ //printf("\n ***********************"); Schrodinger2D(s,v,m1,m2); //printf("\n The section %d with valley %d is solved",s,v); } // Valley pair 2 m1 = ml; m2 = mt; v = 2; for(s=0; s<=nx_max; s++){ //printf("\n ***********************"); Schrodinger2D(s,v,m1,m2); //printf("\n The section %d with valley %d is solved",s,v); } // Valley pair 3 chi can giai khi no khong doi xung. Tinh Sau m1 = mt; m2 = ml; v = 3; for(s=0; s<=nx_max; s++){ //printf("\n ***********************"); Schrodinger2D(s,v,m1,m2); //printf("\n The section %d with valley %d is solved",s,v); } return; } // End of void Solved_2D_Schro_for_MSMC() //**************************************************************************** /* The program is to find eigenfunctions and eigenvalues of 2-dimensional Schroedinger Eq in k-space. Su dung ham DSYEVX Lappack INPUT: + s: s-th section + v: v-th valley pairs + m1,m2: la hai tham so cho cac valley pairs. Vi du (m1=0.19, m2=0.916) m1 ung voi truc y. m2 ung voi truc z + Cac tham so khac OUTPUT: + eigenvalues: eig(1,NSELECT) + eigenvetors: wave(1,NSELECT,1,nz,1,ny); da CHUAN HOA STARTING DATE: January 08, 2010 LASTEST UPDATE: Feb 23, 2010 *************************************************************************************** */ void Schrodinger2D(int s, int v, double m1, double m2){ // Goi cac ham void get_potential(int s, int ny, int nz); void makeh(int ny,int nz,double ly,double lz,double *potential,double **ham,double m1, double m2); double *Get_pot();// Sau khi goi get_potential(int s) thi no se chuyen Phi(i_HANGSO,j,k) thanh 1D pot void diasym(int s, int v,int ny, int nz,double ly,double lz,int NSELECT, double **ham, double ***eig, double *****wave); void normalize_wave(int s,int v,int ny,int nz,int NSELECT, double *****wave); double ***Get_eig(), *****Get_wave(); int Get_nya(),Get_nyb(), Get_nza(),Get_nzb(); double Get_mesh_size_y(), Get_mesh_size_z(); int Get_NSELECT(); int Get_save_eig_wavefuntion(); // Flag chi ra co SAVE hay KHONG? // Cac bien local int nya = Get_nya(); int nyb = Get_nyb(); int nza = Get_nza(); int nzb = Get_nzb(); int ny_max = nyb - nya;// De thay doi it nhat co the int nz_max = nzb - nza; //printf("\n nya=%d, nyb=%d,ny_max=%d, nza=%d,nzb=%d,nz_max=%d",nya,nyb,ny_max,nza,nzb,nz_max); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); int NSELECT = Get_NSELECT(); double ***eig = Get_eig(); double *****wave = Get_wave(); int save_eig_wavefuntion = Get_save_eig_wavefuntion(); // Thuc hien int ny = ny_max + 1; // Do so KHOANG CHIA la ny_max va nz_max NEN SO DIEM CHIA la ny_max+1 va nz_max+1 (May 30, 2010) int nz = nz_max + 1; // int ny = ny_max; int nz = nz_max; int i,j; double **ham; // theo ta xay dung "ham" trong ham Schrodinger la hop ly ham=dmatrix(1,ny*nz,1,ny*nz); // Hamiltonian di tu chi so 1 cho phu hop voi ham makeh. for(i=1; i<=ny*nz; i++){// Noi chung neu khoi tao array thi nen khoi tao gia tri dau cho no. KHONG se co RAT NHIEU LOI for(j=1; j<=ny*nz; j++){ // (June, 03, 2010) ham[i][j] =0.0; } } //printf("\n Get potential"); get_potential(s,ny,nz);// Get potential. Sau ham nay duoc array chua potential double *pot = Get_pot();// Vi sau ham get_potential() thi Get_pot moi thay doi //printf("\n Make Hamiltonian"); double ly = mesh_size_y*ny_max/1.0e-9;// do ly la DOAN nen nhan voi ny_max la HOP LY printf("\n ly =%f",ly);//NOTE: [nm] Kkong phai la m double lz = mesh_size_z*nz_max/1.0e-9; makeh(ny,nz,ly,lz,pot,ham,m1,m2);// To contruct the Hamiltonian //printf("\n Calling diasym"); diasym(s,v,ny,nz,ly,lz,NSELECT,ham,eig,wave);// Call Lapack routine // da check thu roi, eig va wave o dau ra la ok //printf("\n Normalize wave"); normalize_wave(s,v,ny_max,nz_max,NSELECT,wave);// Normalize wave /* Free variables */ free_dmatrix(ham,1,ny*nz,1,ny*nz) ; }// End of void Schrodinger2D(double m1, double m2) //*********************************************************************************** /* ***************************************************************************** De lay potential Phi(i,j,k) Nhung do tai giai cho tung Cross-section nen cai ma ta lay la o dang Phi(0,j,k) roi Phi(1,j,k), ...., Phi(nx_max, j,k) INPUT: + s: s-th section + ny va nz: la so diem chia theo phuong y va z + Phi(i,j,k) OUTPUT: potential[] chuyen tu matrix sang dang array. potential[] la bien global Starting date: April 19,2010 Update: April 19,2010 Latest update: May 09, 2010: Ta tinh theo dung cong thuc tinh potential Ta phai chu y toa do cua Potential ma ta dinh nghia. Ham nay la thay doi mang tinh CO BAN ********************************************************************************* */ //#include <stdio.h> //#include "nrutil.h" void get_potential(int s, int ny, int nz) { // s-th section double ***Phi = GetPot(); double *Get_pot();//chuyen Phi(s-th,j,k) thanh pot 1D (potential 1D) double *pot = Get_pot(); double Get_Eg(); // Band gap double Eg = Get_Eg(); //printf("\n Eg = %f",Eg);// E->c_si = Eg/2.0 //double dEc = 0; // Jun 02, 2010 int Get_nya(),Get_nza(); int nya = Get_nya(); // Ro rang toa do cua potential bi dich 1 doan la nya va nza int nza = Get_nza(); int j_k=0,j,k; for(j=1; j<=ny; j++){// ny = nyb-nya+1; tuong tu cho nz for(k=1; k<=nz; k++){ j_k=j_k+1; pot[j_k]= Eg/2.0 - Phi[s][j+nya-1][k+nza-1];//potential o loi Silicon //pot[j_k]= dEc - Phi[s][j+nya-1][k+nza-1]; } } return; } // End of void get_potential(int s) //********************************************O****************************************************** /* ***************************************************************************** Tinh ma tran Hamiltonian INPUT: + ny va nz: la so diem chia theo phuong y va z + ly va lz: la do dai cua rectangular theo phuong y va z + *potential la mang potential.CO THEM beta; Can sua lai cho hop ly voi potential cua ta + m1,m2: la hai tham so cho cac valley pairs. Vi du (m1=0.19, m2=0.916) m1 ung voi truc y. m2 ung voi truc z OUTPUT: + **ham: Hamiltonia matrix (1,ny*nz,1,ny*nz) Note: Su dung open boundary tuc la dang hard wall. Starting date: December 21, 2009 Latest update: January 15, 2010 ********************************************************************************/ //#include <stdio.h> //#include <math.h> //#include "constants.h" //#include "nrutil.h" void makeh(int ny,int nz,double ly,double lz,double *potential,double **ham,double m1, double m2) { double energy0(int ky,int kz,double ly,double lz,double m1, double m2); void multiply_matrix(int INDEX,double alpha, double **matrixA, double **matrixB, double **matrixC); int nynz = ny*nz; double **U = dmatrix(1,nynz,1,nynz); // Chua Uk double **VU = dmatrix(1,nynz,1,nynz); // Chua V x Uk double **Vk = dmatrix(1,nynz,1,nynz); // la gia tri cua hangso*U_t*VU int i,j; for(i=1; i<=ny*nz; i++){// Noi chung neu khoi tao array thi nen khoi tao gia tri dau cho no. KHONG se co RAT NHIEU LOI for(j=1; j<=ny*nz; j++){ // (June, 03, 2010) U[i][j]=0.0; VU[i][j]=0.0; Vk[i][j]=0.0; } } int m,n,pp,qq; // do q da duoc dinh nghia o constant, p da dinh nghia la bien TOAN CUC roi double ym,zn; // Dau tien tinh thanh phan diagonal for(i=1; i<=nynz; i++){ n=1+(i-1)%nz; // chinh la kz cua ta m=1+(i-1)/nz;// chinh la ky cua ta ham[i][i]= energy0(m,n,ly,lz,m1,m2);// thanh phan diagonal } // Tinh thanh phan Uk va VrUk duoc tao doi potential for(i=1; i<=nynz; i++){ n=1+(i-1)%nz; m=1+(i-1)/nz; for(j=1; j<=nynz; j++){ qq=1+(j-1)%nz; pp=1+(j-1)/nz; ym=(double)(m)/(double)(ny+1); zn=(double)(n)/(double)(nz+1); U[i][j]=sin(pp*pi*ym)*sin(qq*pi*zn); //chinh la Uk //printf(" U[%d][%d]= %le",i,j,U[i][j]); VU[i][j]=beta*potential[i]*U[i][j]; //chinh la V*Uk;/printf("\n potential[%d] = %f",i,potential[i]);//check potential } } //Thuc hien viec nhan double alpha = 4.0/((double)((ny+1)*(nz+1))); multiply_matrix(nynz,alpha,U,VU,Vk);// dau ra Vk chinh la thanh phan Hamiltonian do potential tao ra // Cong 2 thanh phan tao nen ham(i,j) lai voi nhau for(i=1; i<=nynz; i++){ for(j=1; j<=nynz; j++){ ham[i][j] = ham[i][j]+Vk[i][j]; } } // Free_local vector free_dmatrix(U,1,nynz,1,nynz); free_dmatrix(VU,1,nynz,1,nynz); free_dmatrix(Vk,1,nynz,1,nynz); } // End of void makeh(int ny,int nz,double ly,double lz,double *potential,double **ham,double m1, double m2) //********************************************************************************************* /* ***************************************************************************** De tinh gia tri betaEkykz INPUT: + ky va kz la chia theo k-space, ky di tu 1 den ny, kz di tu 1 den nz + ly va lz: la do dai cua rectangular theo phuong y va z + m1,m2: la hai tham so cho cac valley pairs. Vi du (m1=0.19, m2=0.916) m1 ung voi truc y. m2 ung voi truc z OUTPUT:+ Gia tri energy E0 ma ta tim duoc. Don vi beta*E Note: Su dung open boundary tuc la dang hard wall. Starting date: December 28, 2009 Latest update: December 28, 2009 *********************************************************************************/ //#include <stdio.h> //#include "constants.h" double energy0(int ky,int kz,double ly,double lz,double m1, double m2){ double pi2 = (pi*pi)/2.0; double kyly = (double)(ky)/ly; double kzlz = (double)(kz)/lz; double energy; energy = pi2*((1.0/m1)*kyly*kyly +(1.0/m2)* kzlz*kzlz); //printf("\n Energy0 = %le",energy); return energy; } // End of energy0(int ky,int kz,double ly,double lz,double m1, double m2) /* ***************************************************************************** Nhan 2 ma tran su dung dgemm routine tu Lapack INPUT: + Ma tran 2 chieu matrixA va matrixB + INDEX la chi so mang day la ma tran vuong + alpha: la so vo huong OUTPUT: + Ma tra 2 chieu matrixC = alpha*matrixA_t*matrixB (t la transpose)+beta*matrixC nhung beta=0.0 Starting date: January 11, 2010 Latest update: January 15, 2010 ********************************************************************************/ void multiply_matrix(int INDEX,double alpha, double **matrixA, double **matrixB, double **matrixC){ void convert_mtx_to_array(int M, int N, double **mtx, double *a); void convert_array_to_mtx(int M, int N, double *a, double **mt); // **matrixA=dmatrix(1,INDEX,1,INDEX),**matrixB=dmatrix(1,INDEX,1,INDEX), **matrixC=dmatrix(1,INDEX,1,INDEX); double *A=dvector(1,INDEX*INDEX),*B=dvector(1,INDEX*INDEX),*C=dvector(1,INDEX*INDEX); int i,j,n; for(i=1; i<=INDEX*INDEX; i++){// Noi chung neu khoi tao array thi nen khoi tao gia tri dau cho no. KHONG se co RAT NHIEU LOI A[i]=0.0; B[i]=0.0; C[i]=0.0;// (June, 03, 2010) } // Chuyen ma tran A thanh array A de phu hop voi ham dgemm, tuong tu cho ma tran B convert_mtx_to_array(INDEX,INDEX,matrixA,A); convert_mtx_to_array(INDEX,INDEX,matrixB,B); // Ket qua duoc mang C // Matrix-Matrix Multiply n = INDEX; double beta_beta=0.0; // do beta la hang so dinh nghia o constant.h //printf("\n Multiply matrix"); dgemm("t","n",&n,&n,&n,&alpha,A,&n,B,&n,&beta_beta,C,&n); // "t' dau nghia la A la transpose, "n" sau nghia la B la ok // Chuyen ket qua tu array sang ma tran convert_array_to_mtx(INDEX,INDEX,C,matrixC); //Free-local vector free_dvector(A,1,INDEX*INDEX); free_dvector(B,1,INDEX*INDEX); free_dvector(C,1,INDEX*INDEX); return; }// End of void multiply_matrix(double **A, double **B, double **C) //*********************************************************************************** void convert_mtx_to_array(int M, int N, double **mtx, double *a) { int i,j ; int k = 0 ; for ( j=1 ; j<=N ; j++ ) for ( i=1 ; i<=M ; i++ ) a[k++] = mtx[i][j] ; } void convert_array_to_mtx(int M, int N, double *a, double **mtx) { int i,j ; int k = 0 ; for ( j=1 ; j<=N ; j++ ) for ( i=1 ; i<=M ; i++ ) mtx[i][j] = a[k++]; } //**************************************************************************************** /**************************************************************************************** - Su dung ham DSYEVX Lappack INPUT: + s: s-th section + v: v-th valley pair + ny va nz: la so diem chia theo phuong y va z + ly va lz: la do dai cua rectangular theo phuong y va z + Nselect: so subband ta can lay + Hamitonian matrix ham[n][n] OUTPUT: + eigenvalues: eig(1,NSELECT) + eigenvetors: wave(1,NSELECT,1,ny,1,nz); STARTING DATE: January 04, 2010 LASTEST UPDATE: Feb 24, 2010 *************************************************************************************** */ //#include <stdio.h> //#include <string.h> //#include "nrutil.h" void diasym(int s, int v,int ny, int nz,double ly,double lz,int NSELECT, double **ham, double ***eig, double *****wave){ double psirealspace(double y,double z,int ny,int nz,double ly,double lz,double **vec, int index); void convert_mtx_to_array(int M, int N, double **mtx, double *a); void print_matrix( char* desc, int m, int n, double* a, int lda ); int i,j; // SUBROUTINE DSYEVX( JOBZ, RANGE, UPLO, N, A, LDA, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, LWORK, IWORK,IFAIL, INFO ) int N = ny*nz; // la bien trung gian de tranh bi thay doi khi vao ham dsyevx int LDA = N, LDZ = N; // NSELECT = 10 (for example);// global variable khai bao tu ham main /* Locals */ int n = N, il, iu, m, lda = LDA, ldz = LDZ, info, lwork; double abstol, vl, vu; double wkopt; double* work; /* Local arrays */ int *iwork = ivector(0,5*N-1); for(i=0; i<=5*N-1; i++){ iwork[i] = 0;} // iwork dimension should be at least 5*n int *ifail = ivector(0,N-1); for(i=0; i<=N-1; i++){ ifail[i] = 0; } double *w = dvector(0,N-1); for(i=0; i<=N-1; i++){ w[i]=0.0; } //chinh la eigvalues ta tim duoc double *z = dvector(0,LDZ*NSELECT-1); for(i=0; i<= LDZ*NSELECT-1; i++){ z[i]=0.0;} // chua eigenvectors ma ta can tim double *a = dvector(0,LDA*N-1); for(i=0; i<=LDA*N-1; i++){ a[i]=0.0;}// chinh la array de chua ma tran Hamiltonian convert_mtx_to_array(LDA,N,ham,a); // do LDA=N=ny*nz /* Executable statements */ //printf( "\n Running DSYEVX " ); abstol = -1.0; /* negative abstol means using the default value */ il = 1; /* Set il, iu to compute NSELECT smallest eigenvalues */ iu = NSELECT; // Query and allocate the optimal workspace lwork = -1; dsyevx("Vectors","Indices","Upper", &n, a, &lda, &vl, &vu, &il, &iu,&abstol, &m, w, z, &ldz, &wkopt, &lwork, iwork, ifail, &info); lwork = (int)wkopt; // Chu y goi dsyevx o tren la &wkopt day nhe ! work = dvector(0,lwork-1); /* Solve eigenproblem */ dsyevx("Vectors","Indices","Upper", &n, a, &lda, &vl, &vu, &il, &iu,&abstol, &m, w, z, &ldz, work, &lwork, iwork, ifail, &info ); /* Check for convergence */ if( info > 0 ) { printf( "The algorithm dsyevx failed to compute eigenvalues.\n" ); exit( 1 ); } /* Print the number of eigenvalues found */ //printf( "\n Number of subbands for each valley: %2i", m );// m=iu-il+1 = NSELECT // Print eigenvalues // print_matrix( "Selected eigenvalues from DSYEVX", 1, m, w, 1 ); // Tinh eigen_value tuong ung voi so NSELECT ma ta chon int k=0; // w chinh la mang chua eigen value for( i = 0; i <1; i++ ) {// chay theo 0. for( j = 0; j < m; j++ ) { // m chinh la so NSELECT k=k+1; eig[s][v][k]= w[i+j*1];//eigvalue o day la tu DSYEVX ma ra. Ta se di tu chi so 1 cho lowest eigenvalue eig[s][v][k]=eig[s][v][k]/beta; // [eV] theo cong thuc tinh toan Schrodinger cua ta } } // Tinh eigenvectors. //print_matrix( "Selected eigenvectors (stored columnwise)", n, m, z, ldz ); double **vec=dmatrix(1,N,1,NSELECT); // n cung chinh bang N for( i = 0; i < N; i++ ) {// di tu 1 den ny*nz for( j = 0; j < m; j++ ) {//m = NSELECT so luong tran thai state can luu. vec[i+1][j+1]= z[i+j*ldz] ; // vec lay cot cua mang z; do chi so mang vec la di tu 1 } } // To store state psi to wave array de su dung tinh scattering int index; double y_point, z_point; // Gia tri de xac dinh so diem chia thi khong quan trong nhung no can matching voi index o wave int ny_max = ny -1; // (May 30, 2010) int nz_max = nz -1;// do ny=nyb-nya+1; nen ny_max moi la index chinh xac o wave, no di tu 0 den ny_max for(i=0;i<=ny_max;i++){ // so diem chia theo phuong y. vi du chia thanh 100 diem y_point=ly*(double)(i)/(double)(ny_max); // diem chia theo y di tu 0 den ly for(j=0;j<=nz_max;j++){ // so diem chia theo phuong z. vi du chia thanh 100 diem z_point=lz*(double)(j)/(double)(nz_max); // diem chia theo z di tu 0 den lz for(index=1; index<=NSELECT; index++){ wave[s][v][index][i][j]= psirealspace( y_point,z_point,ny,nz,ly,lz,vec,index); }// End of for(index=1; index<=NSELECT; index++) } // End of for(i=0;i<=ny_max;i++){ }// End of for(j=0;j<=nz_max;j++){ // Free local variables free_dvector(work,0,lwork-1); free_ivector(iwork,0,5*N-1), free_ivector(ifail,0,N-1); free_dvector(w,0,N-1);//chinh la eigvalues ta tim duoc free_dvector(z,0,LDZ*NSELECT-1);// chua eigenvectors ma ta can tim free_dvector(a,0,LDA*N-1); // chinh la array de chua ma tran Hamiltonian free_dmatrix(vec,1,N,1,NSELECT); //printf("\n Ket thuc ham diasym"); } // End of void diasym(double **ham, double *eig, double ***wave) /**************************************************************************************** */ /* ***************************************************************************** To calculate the wavefunction in real space psi = Sum(Ck*|k>) INPUT: + y,z la diem vao de tinh gia tri psi Hai bien nay chi can luc ve psi thoi. Thuc ra lay ny va nz de ve cung ok. Nhung co the ta can nhieu diem chia hon + ny va nz: la so diem chia theo phuong y va z + ly va lz: la do dai cua rectanggular theo phuong y va z + vec[][] la he so Ck day. Chu y he so thek la tong hop cua kx va ky + index: la chi so mang thu 2 cua vec de chi viec ta dinh lay psi ung voi eigen thu may nen index se di tu 1 den NSELECT OUTPUT:+ psirealspace: gia tri psi trong real space Note: Su dung open boundary tuc la dang hard wall. Starting date: December 29, 2009 Latest update: December 31, 2009 **************************************************************************************************/ //#include <stdio.h> //#include <math.h> //#include "constants.h" double psirealspace(double y,double z,int ny,int nz,double ly,double lz,double **vec, int index){ int i,j,ky,kz; double psi,phiy,phiz; psi=0.0; for(i=1; i<=ny*nz; i++){// la gia tri k chay tu 1 den N=ny*nz //printf( "\n %6.8f",vec[i] ); kz = 1+(i-1)%nz; // chay theo phuong ky ky = 1+(i-1)/nz; // roi chay theo phuong kz phiy = sin((double)(ky)*pi*y/ly); // la ham sin theo ky phiz = sin((double)(kz)*pi*z/lz); // la ham sin theo kz psi = psi + vec[i][index]*phiy*phiz; // Xem cong thuc tren } // End of for psi = 2.0*psi/(sqrt(ly*lz)); // Tai sao thieu so 2 nhi ? //psi = psi/(sqrt(ly*lz));// Thie so 2 thi co nghia chua normalized. Sau do se normalized. Nhung nhan 2 o day van hay hon //printf( "\n psi = %6.8f",psi ); return psi; } // End of double psirealspace(double y,double z,int ny,int nz,double ly,double lz,vec[]){ // Chon kieu nay thi n chinh la NSELECT void print_matrix( char* desc, int m, int n, double* a, int lda ) { int i, j; printf( "\n %s\n", desc ); for( i = 0; i < m; i++ ) { for( j = 0; j < n; j++ ) { printf( " %6.8f", a[i+j*lda] ); } printf( "\n" ); } } //******************************************************************************* /**************************************************************************************** - To normalize wave function su dung trapezoidal INPUT: + s: s-th section + v: v-th valley pairs + ny,nz la so diem chia tren 2 truc ly va lz + Nselect: so subband ta can lay + trapezoidal_weights[][] Truoc (April 08, 2010) su dung cach don gian hon + wave(1,NSELECT,0,ny,0,nz) CHUA normalize OUTPUT: + wave(1,NSELECT,0,ny,0,nz) DA DUOC normalize STARTING DATE: April 08, 2010 LASTEST UPDATE: April 08, 2010 *************************************************************************************** */ void normalize_wave(int s,int v,int ny,int nz,int NSELECT, double *****wave){ // Goi ham double **Get_trap_weights();// Lay phan cong thuc 1 va hang so cua cong thuc 2 trang 92 // Local bien double **trap_weights = Get_trap_weights(); // Thuc hien double mag_psi; int index,i,j; for(index=1; index<=NSELECT; index++){// Chay cho tung subband mag_psi = 0.0; for(i=0; i<=ny; i++){ for(j=0; j<=nz; j++){ mag_psi += trap_weights[i][j]*wave[s][v][index][i][j]* wave[s][v][index][i][j]; } } mag_psi = 1.0/sqrt(mag_psi); //printf("\n Trapzoidal Tham so A can tim de normalization = %le", mag_psi); for(i=0; i<=ny; i++){ for(j=0; j<=nz; j++){ wave[s][v][index][i][j]= mag_psi*wave[s][v][index][i][j];// Normalize wave } } }// End of for( index=1; index<=NSELECT; index++){// Chay cho tung subband }// End of void normalize_wave(){ //************************************************************************************* /**************************************************************************************** INPUT: + s: s-th section + v: v-th valley pair + ny va nz: la so diem chia theo phuong y va z + ly va lz: la do dai cua rectangular theo phuong y va z + Nselect: so subband ta can lay + eigenvalues: eig(1,NSELECT) + eigenvetors: wave(1,NSELECT,1,ny,1,nz); OUTPUT: + eig.dat chua eigen energy + wave.dat chua psi da duoc CHUAN HOA STARTING DATE: January 08, 2010 LASTEST UPDATE: Feb 24, 2010 *************************************************************************************** */ //#include <stdio.h> //#include "nrutil.h" void save_eig_wave(int s,int v, char *fneigen, char *fnwave){ double ***Get_eig(), *****Get_wave(); double ***eig = Get_eig(); double *****wave = Get_wave(); int Get_NSELECT(); int NSELECT = Get_NSELECT(); int Get_nya(),Get_nyb(),Get_nza(),Get_nzb(); int nya = Get_nya(); int nyb = Get_nyb(); int nza = Get_nza(); int nzb = Get_nzb(); int ny = nyb - nya; // int ny = ny_max = nyb - nya; int nz = nzb - nza; // int nz = nz_max = nzb - nza; double Get_mesh_size_y(), Get_mesh_size_z(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); double ly = mesh_size_y*ny/1.0e-9;//Do ly la DOAN printf("\n ly =%f",ly);//NOTE: [nm] Kkong phai la m double lz = mesh_size_z*nz/1.0e-9; // Thuc hien int index,i,j; // To store eigen value FILE *f; f = fopen(fneigen,"a"); // "w" neu tep ton tai no se bi xoa if(f == NULL) { printf("\n Cannot open file at save_eig_wave.c"); return ; } fprintf(f,"\n # s_th v_th i_subband eigen_value[eV] \n"); for( i=1; i<=NSELECT; i++){ // do m o ham dsyevx tu diasym la bang NSELECT fprintf(f,"%d %d %d %le \n",s,v,i, eig[s][v][i]); } fclose(f); // To store wave (psi) FILE *f1; f1 = fopen(fnwave,"a"); if(f1== NULL) { printf("\n Cannot open file save_eig_wave.c"); return;} fprintf(f1,"\n # s-th v_th y_point z_point psi_square \n"); double y_point, z_point; // Chi in ra file wave khi NSELECT = 10 if(NSELECT ==10){ for(index=1; index<=NSELECT; index++){// chay thu tu tung wave for(i=0;i<=ny;i++){ // so diem chia theo phuong y. y_point=ly*(double)(i)/(double)(ny); // diem chia theo y di tu 0 den ly for(j=0;j<=nz;j++){ // so diem chia theo phuong z. z_point=lz*(double)(j)/(double)(nz); // diem chia theo z di tu 0 den lz fprintf(f1,"%d %d %le %le %le %le %le %le %le %le %le %le %le %le \n", s,v,z_point,y_point, wave[s][v][1][i][j]*wave[s][v][1][i][j], wave[s][v][2][i][j]*wave[s][v][2][i][j], wave[s][v][3][i][j]*wave[s][v][3][i][j], wave[s][v][4][i][j]*wave[s][v][4][i][j], wave[s][v][5][i][j]*wave[s][v][5][i][j], wave[s][v][6][i][j]*wave[s][v][6][i][j], wave[s][v][7][i][j]*wave[s][v][7][i][j], wave[s][v][8][i][j]*wave[s][v][8][i][j], wave[s][v][9][i][j]*wave[s][v][9][i][j], wave[s][v][10][i][j]*wave[s][v][10][i][j]); // Binh phuong wave }// End of for(j=0;j<=nz;j++){ } // End of for(i=0;i<=ny;i++){ }// End of for(index=1; index<=NSELECT; index++) }// End of if(NSELECT ==10) fclose(f1); }// End of void save_eig_wave( double *eig, double ***wave){ /**************************************************************************************** INPUT: + nx_max: so diem theo phuong x + ny va nz: la so diem chia theo phuong y va z + ly va lz: la do dai cua rectangular theo phuong y va z + Nselect: so subband ta can lay + eigenvalues: eig(1,NSELECT) OUTPUT: + subband.dat chua eigen energy STARTING DATE: May 26, 2010 LASTEST UPDATE: May 27, 2010 *************************************************************************************** */ void save_subband_energy(char *fnsubband){// con cho theory thi can gi doi ten double ***Get_eig(); double ***eig = Get_eig(); int Get_NSELECT(); int NSELECT = Get_NSELECT(); int Get_nx0(),Get_nx1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; int s; // E_s,v,i if(NSELECT >= 4){// Chi save khi so subband lon hon 4 tro len FILE *f; f = fopen(fnsubband,"w"); // "w" neu tep ton tai no se bi xoa if(f == NULL) { printf("\n Cannot open file subband.dat"); return ; } fprintf(f,"\n # s_th Es_1_1 E_s_1_2 E_s_1_3 E_s_1_4 Es_2_1 E_s_2_2 E_s_2_3 E_s_2_4 Es_3_1 E_s_3_2 E_s_3_3 E_s_3_4 \n"); double Get_mesh_size_x(); double mesh_size_x = Get_mesh_size_x(); for( s=0; s<=nx_max; s++){ fprintf(f,"%le %le %le %le %le %le %le %le %le %le %le %le %le\n", (double)(s)*mesh_size_x/1.0e-9, eig[s][1][1], eig[s][1][2], eig[s][1][3], eig[s][1][4], eig[s][2][1], eig[s][2][2], eig[s][2][3], eig[s][2][4], eig[s][3][1], eig[s][3][2], eig[s][3][3], eig[s][3][4]); }// End of for( s=0; s<=nx_max; s++) fclose(f); }// End of if(NSELECT >= 4){ // Tinh energy spacing theo ly thuyet int Get_nya(),Get_nyb(),Get_nza(),Get_nzb(); int nya = Get_nya(); int nyb = Get_nyb(); int nza = Get_nza(); int nzb = Get_nzb(); double Get_mesh_size_y(), Get_mesh_size_z(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); double Tsi = (double)(nyb - nya)*mesh_size_z; // chu y la theo phuong nhe double Wsi = (double)(nzb - nza)*mesh_size_y; double Get_ml(), Get_mt(); double ml = Get_ml(); double mt = Get_mt(); int y_interger = 5 , z_interger = 5; // integer number for y and z direction. Chon tuy y // ta chon bang 5 la du roi double my, mz, **E1, **E2, **E3; E1=dmatrix(1,y_interger,1,z_interger), E2=dmatrix(1,y_interger,1,z_interger), E3=dmatrix(1,y_interger,1,z_interger); int i,j; for (i=1; i<=y_interger; i++){ for(j=1; j<=z_interger; j++){ E1[i][j]=0.0; E2[i][j]=0.0; E3[i][j]=0.0; } } //Valley pair 1: my=mt, mz=mt my = mt, mz=mt; for (i=1; i<=y_interger; i++){ for(j=1; j<=z_interger; j++){ E1[i][j] = ((double)(i*i)*pi*pi*hbar*hbar)/(2.0*my*m0*Tsi*Tsi) + ((double)(j*j)*pi*pi*hbar*hbar)/(2.0*mz*m0*Wsi*Wsi); } } // Valley pair 2: my = ml, mz = mt; for (i=1; i<=y_interger; i++){ for(j=1; j<=z_interger; j++){ E2[i][j] = ((double)(i*i)*pi*pi*hbar*hbar)/(2.0*my*m0*Tsi*Tsi) + ((double)(j*j)*pi*pi*hbar*hbar)/(2.0*mz*m0*Wsi*Wsi); } } // Valley pair 3 my = mt, mz = ml; for(j=1; j<=z_interger; j++){// Muon chung to giong valley 2 khi doi xung thi can nhu the nay for (i=1; i<=y_interger; i++){ //for(j=1; j<=z_interger; j++){ E3[j][i] = ((double)(i*i)*pi*pi*hbar*hbar)/(2.0*my*m0*Tsi*Tsi) + ((double)(j*j)*pi*pi*hbar*hbar)/(2.0*mz*m0*Wsi*Wsi); } } FILE *f1; f1 = fopen("subband_spacing_theory.dat","w"); // "w" neu tep ton tai no se bi xoa if(f1 == NULL) { printf("\n Cannot open file subband__spacing_theory.dat"); return ; } fprintf(f1,"\n # Valley1_spacing[ev] Valley2_spacing[eV] Valley3_spacing[eV] NOT shown in the ascending order \n"); fprintf(f1,"%f %f %f \n",(E1[1][2]-E1[1][1])/q,(E2[1][2]-E2[1][1])/q,(E3[1][2]-E3[1][1])/q); // first spacing if my=mz fprintf(f1,"%f %f %f \n",(E1[2][2]-E1[1][2])/q,(E2[2][2]-E2[1][2])/q,(E3[2][2]-E3[1][2])/q); // second spacing if my=mz fprintf(f1,"%f %f %f \n",(E1[1][3]-E1[2][2])/q,(E2[1][3]-E2[2][2])/q,(E3[1][3]-E3[2][2])/q); // thirsd spacing if my=mz fprintf(f1,"%f %f %f \n",(E1[2][3]-E1[1][3])/q,(E2[2][3]-E2[1][3])/q,(E3[2][3]-E3[1][3])/q); // forth spacing if my=mz fprintf(f1,"%f %f %f \n",(E1[1][4]-E1[2][3])/q,(E2[1][4]-E2[2][3])/q,(E3[1][4]-E3[2][3])/q); // 5th spacing if my=mz fclose(f1); FILE *f2; f2 = fopen("subband_theory.dat","w"); // "w" neu tep ton tai no se bi xoa if(f2 == NULL) { printf("\n Cannot open file subband__theory.dat"); return ; } fprintf(f2,"\n # i j Valley1[ev] Valley2[eV] Valley3[eV] \n"); for (i=1; i<=y_interger; i++){ for(j=1; j<=z_interger; j++){ fprintf(f2," %d %d %f %f %f \n",i,j, E1[i][j]/q, E2[i][j]/q, E3[i][j]/q); } } fclose(f2); // Free local free_dmatrix(E1,1,y_interger,1,z_interger), free_dmatrix(E2,1,y_interger,1,z_interger), free_dmatrix(E3,1,y_interger,1,z_interger); return; }// End of void save_subband_energy(char *fnsubband) //********************************************************************************************** /* ************************************************************************************************* Save tai midpoint cua cac phuong x or ( y va z) Chi save o phan loi Silicon Starting date: May 25, 2010 Latest update: May 27, 2010: ************************************************************************************************* */ void save_potential_used_for_2D_Schrodinger(char *fn_x, char *fn_yz){//For checking only (May 25, 2010) double ***Phi = GetPot(); double Get_Eg(); // Band gap double Eg = Get_Eg(); //double dEc = 0.0; int Get_nx0(),Get_nx1(),Get_nya(),Get_nyb(), Get_nza(),Get_nzb(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; int nya = Get_nya(); int nyb = Get_nyb(); int nza = Get_nza(); int nzb = Get_nzb(); int ny = nyb - nya +1;// (May 30, 2010) // int ny = nyb - nya; int nz = nzb - nza +1; // int nz = nzb - nza; double Get_mesh_size_x(),Get_mesh_size_y(),Get_mesh_size_z(); double mesh_size_x = Get_mesh_size_x(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); int j,k; double x_pos = 0.0, y_pos = 0.0, z_pos = 0.0; int midpoint_x = (int)(nx_max/2.0 + 0.5); int s = midpoint_x; FILE *ff; ff = fopen(fn_yz,"w"); //ff = fopen("potential_yz_at_midpoint_x_in2DSchrodinger.dat","w"); if(ff==NULL){ printf("\n Cannot open file at save_potential_used_for_2D_Schrodinger.c ");return; } fprintf(ff,"\n # y[nm] z[nm] pot_yz[eV] \n"); for(j=1; j<=ny; j++){ y_pos = (double)(j-1)*mesh_size_y/1.0e-9;// [m] -> [nm]; vi tri se di tu 0 den nyb-nya for(k=1; k<=nz; k++){ z_pos = (double)(k-1)*mesh_size_z/1.0e-9; fprintf(ff," %le %le %le \n",y_pos,z_pos,( Eg/2.0 - Phi[s][j+nya-1][k+nza-1]));// potential[eV] //fprintf(ff," %le %le %le \n",y_pos,z_pos,( dEc - Phi[s][j+nya-1][k+nza-1]));// potential[eV] } }// End of for(j=1; j<=ny; j++){ fclose(ff); // Ve theo phuong x khi dat y va z rai midpoint (May 26, 2010) int Get_ny0(),Get_ny1(),Get_nz0(),Get_nz1(); int ny0 = Get_ny0(); int ny1 = Get_ny1(); int nz0 = Get_nz0(); int nz1 = Get_nz1(); int midpoint_y = (int)((ny1-ny0)/2.0 + 0.5);// lay o giua truc y do tinh doi xung cua oxide int midpoint_z = (int)((nz1-nz0)/2.0 + 0.5); FILE *f1; f1 = fopen(fn_x,"w"); //f1 = fopen("potential_x_at_midpoint_yz_in2DSchrodinger.dat","w"); // "w" neu tep ton tai no se bi xoa if(f1==NULL){ printf("\n Cannot open file at save_potential_used_for_2D_Schrodinger.c"); return ; } fprintf(f1,"\n # x[nm] potential_x[eV] \n"); int i; for(i=nx0; i<=nx1; i++){ fprintf(f1,"%le %le \n",i*mesh_size_x/1.0e-9,Eg/2.0 - Phi[i][midpoint_y][midpoint_z]); // fprintf(f1,"%le %le \n",i*mesh_size_x/1.0e-9,dEc - Phi[i][midpoint_y][midpoint_z]); } fclose(f1); return; } <file_sep>/* **************************************************************** De SAVE ket qua <---KIEM TRA duoc KET QUA DUNG hay SAI Starting date: March 11, 2010 Latest update: March 12, 2010 ****************************************************************** */ #include <stdio.h> #include "nrutil.h" #include "constants.h" void save_results(){ int Get_nx0(),Get_nx1(),Get_NSELECT(); // Cac ham save //void save_eig_wave( NEN de o ham Solved_2D_Schro_for_MSMC() vi no lien quan den so valley can dung, vv void save_doping_potential_initialization(); void save_form_factor_calculation(int s_th); // tai 1 section cu the void save_scattering_table(int s_th); // // tai 1 section cu the // Cac ham flag de SAVE hay KHONG int Get_save_doping_potential_init(); int Get_save_form_factor(); int Get_save_scattering_rate(); // Cac bien local int nx0 = Get_nx0(); int nx1 = Get_nx1(); int NSELECT = Get_NSELECT(); int save_doping_potential_init = Get_save_doping_potential_init(); int save_form_factor = Get_save_form_factor(); int save_scattering_rate = Get_save_scattering_rate(); // Thuc hien int s_th = (int)((nx1-nx0)/2); // chon section o GIUA // 1. Save Doping and Potential Initialization if(save_doping_potential_init==1){ save_initial_potential_doping(); printf("\n Doping and Potential Initialization are Saved"); } // 2. Save Form factor if(save_form_factor==1){ save_form_factor_calculation(s_th); printf("\n Form factor is Saved"); } // 3. SAVE Scattering rate if(save_scattering_rate==1){ save_scattering_table(s_th); printf("\n Scattering rate is Saved"); } return; } // End of void save_results(){ <file_sep>/* **************************************************************************** De initial potential - Yeu cau: dang potential chinh xac - De HOI TU nhanh Gop 2 ham doping_potential_initialization() va apply volgate() lai. NOTE: Cach khoi tao potential da advance RAT NHIEU Starting date: May 30, 2010 Latest update: May 31, 2010 ***************************************************************************** */ #include <stdio.h> #include <math.h> #include <string.h> #include "petscksp.h" #include "nanowire.h" #include "region.h" #include "mpi.h" #include "nrutil.h" #include "constants.h" void initial_potential_doping(){ double ***Get_doping(); double ***doping = Get_doping();// la donor thi dau + ; con acceptor thi dau tru // Toa do int Get_nx0(),Get_nxa(),Get_nxb(),Get_nx1(); int Get_ny0(),Get_nya(),Get_nyb(),Get_ny1(); int Get_nz0(),Get_nza(),Get_nzb(),Get_nz1(); int Get_nxgate0(),Get_nxgate1(); int nx0 = Get_nx0(); int nxa = Get_nxa(); int nxb = Get_nxb(); int nx1 = Get_nx1(); int ny0 = Get_ny0(); int nya = Get_nya(); int nyb = Get_nyb(); int ny1 = Get_ny1(); int nz0 = Get_nz0(); int nza = Get_nza(); int nzb = Get_nzb(); int nz1 = Get_nz1(); int nxgate0 = Get_nxgate0();// gate int nxgate1 = Get_nxgate1();// gate double Get_mesh_size_x(),Get_mesh_size_y(), Get_mesh_size_z(); double mesh_size_x = Get_mesh_size_x(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); /* ************ For Doping part ********************************** */ int find_region(int i,int j,int k); double *Get_doping_density(); double *dop_term = Get_doping_density();//1,2 or 3 ->S,D or Channel //printf("\n Source doping </cm3> = %5.1le",dop_term[1]); printf("\n Drain doping </cm3> = %5.1le",dop_term[2]); printf("\n Channel doping </cm3>= %5.2le",dop_term[3]); int i,j,k,n=0; for(i=nx0; i<=nx1; i++){ for(j=ny0; j<=ny1; j++){ for(k=nz0; k<=nz1; k++){ n = find_region(i,j,k); // n=1,2,3 or 0 ->o region nao S,D,Channel or outside (Oxide) if((n==1)||(n==2)||(n==3)){// S,D,Channel; //printf("\n n = %d",n); doping[i][j][k] = dop_term[n]; // [1/m3] } else { // n=0 Oxide region doping[i][j][k] =1.0; //1.0e+10; // ;/1.0;// 1.0e+5;// Cho 1 gia tri rat nho. Ho cho la 1.0e+5 cho cm3 } } // End of for(k=nz0; k<=nz1; k++){ }// End of for(j=ny0; j<=ny1; j++){ }// End of for(i=nx0; i<=nx1; i++){ /* ************************End of For Doping part****************** */ return; }// End of void initial_potential() //******************************************************************************* // <NAME> #include <math.h> double Fermihalf (double x){ // Fermi Dirac integral of order 1/2. Cong thuc (10) in Notes on Fermi-Dirac Integrals - Lundstrom double a = x*x*x*x + 33.6*x*(1.0-0.68*exp(-0.17*(x+1.0)*(x+1.0)))+50; double y = 1.0/( 0.75*sqrt(3.14159)*pow(a,-3.0/8.0) + exp(-x)); return y; } //************************************************************************************ void save_initial_potential_doping(){ int Get_nx0(),Get_nx1(),Get_ny0(),Get_ny1(),Get_nz0(),Get_nz1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int ny0 = Get_ny0(); int ny1 = Get_ny1(); int nz0 = Get_nz0(); int nz1 = Get_nz1(); double Get_mesh_size_x(),Get_mesh_size_y(),Get_mesh_size_z(); double mesh_size_x = Get_mesh_size_x(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); double ***Get_doping(); double ***doping = Get_doping(); double ***Phi = GetPot(); int i,j,k; int myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); if(myrank ==0){ FILE *f; f = fopen("potential_doping_initial_yz_at_midpoint_x.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL){ printf("\n Cannot open file potential_doping_initial_yz_at_midpoint_x.dat"); return ; } fprintf(f,"\n # y[nm] z[nm] doping[1/m3] potential[eV] \n"); i=(int)((nx1-nx0)/2.0 + 0.5);// lay o giua truc x for(j=ny0; j<=ny1; j++){ for(k=nz0; k<=nz1; k++){ fprintf(f,"%le %le %le %le \n",j*mesh_size_y/1.0e-9,k*mesh_size_z/1.0e-9,doping[i][j][k],-Phi[i][j][k]); } // NOTE: ta bieu dien o dang -Phi nhe } fclose(f); // Thu va tuong duong voi mpot.r0 cua GS FILE *f1; f1 = fopen("potential_initial_x_at_midpoint_yz.dat","w"); // "w" neu tep ton tai no se bi xoa if(f1==NULL){ printf("\n Cannot open file potential_initial_x_at_midpoint_yz.dat"); return ; } fprintf(f1,"\n # x[nm] potential_x[eV] \n"); j=(int)((ny1-ny0)/2.0 + 0.5);// lay o giua truc z k=(int)((nz1-nz0)/2.0 + 0.5);// lay o giua truc z for(i=nx0; i<=nx1; i++){ fprintf(f1,"%le %le \n",i*mesh_size_x/1.0e-9,-Phi[i][j][k]);// NOTE: ta bieu dien o dang -Phi nhe } fclose(f1); FILE *f2; f2 = fopen("potential_doping_initial_xy_at_midpoint_z.dat","w"); // "w" neu tep ton tai no se bi xoa if(f2==NULL){ printf("\n Cannot open file potential_doping_initial_xy_at_midpoint_z.dat "); return ; } fprintf(f2,"\n # x[nm] y[nm] doping[1/m3] potential[eV] \n"); k=(int)((nz1-nz0)/2.0 + 0.5);// lay o giua truc z for(i=nx0; i<=nx1; i++){ for(j=ny0; j<=ny1; j++){ fprintf(f2,"%le %le %le %le \n",i*mesh_size_x/1.0e-9,j*mesh_size_y/1.0e-9,doping[i][j][k],-Phi[i][j][k]); } // NOTE: ta bieu dien o dang -Phi nhe } fclose(f2); FILE *f3; f3 = fopen("potential_initial_y_at_midpoint_xz.dat","w"); // "w" neu tep ton tai no se bi xoa if(f3==NULL){ printf("\n Cannot open file potential_initial_y_at_midpoint_xz.dat"); return ; } fprintf(f3,"\n # y[nm] potential_y[eV] \n"); i=(int)((nx1-nx0)/2.0 + 0.5);// lay o giua truc x k=(int)((nz1-nz0)/2.0 + 0.5);// lay o giua truc z for(j=ny0; j<=ny1; j++){ fprintf(f3,"%le %le \n",j*mesh_size_y/1.0e-9,-Phi[i][j][k]);// NOTE: ta bieu dien o dang -Phi nhe } fclose(f3); FILE *f4; f4 = fopen("potential_initial_z_at_midpoint_xy.dat","w"); // "w" neu tep ton tai no se bi xoa if(f4==NULL){ printf("\n Cannot open file potential_initial_z_at_midpoint_xy.dat"); return ; } fprintf(f4,"\n # z[nm] potential_z[eV] \n"); i=(int)((nx1-nx0)/2.0 + 0.5);// lay o giua truc x j=(int)((ny1-ny0)/2.0 + 0.5);// lay o giua truc y for(k=nz0; k<=nz1; k++){ fprintf(f4,"%le %le \n",k*mesh_size_z/1.0e-9,-Phi[i][j][k]);// NOTE: ta bieu dien o dang -Phi nhe } fclose(f4); }// End of if(myrank ==0) return; } // End of void initial_potential_doping() //************************************************************************************************************************ void save_initial_charge_density_for_Poisson(){ int Get_nx0(),Get_nx1(),Get_ny0(),Get_ny1(),Get_nz0(),Get_nz1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int ny0 = Get_ny0(); int ny1 = Get_ny1(); int nz0 = Get_nz0(); int nz1 = Get_nz1(); double Get_mesh_size_x(),Get_mesh_size_y(),Get_mesh_size_z(); double mesh_size_x = Get_mesh_size_x(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); double ***Get_electron_density(); double ***electron_density = Get_electron_density(); int i,j,k; int myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); if(myrank ==0){ FILE *f; f = fopen("charge_initial_for_Poisson_yz_at_midpoint_x.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL){ printf("\n Cannot open file charge_initial_for_Poisson_yz_at_midpoint_x.dat "); return ; } fprintf(f,"\n # y[nm] z[nm] electron[1/m3] hole[1/m3] \n"); i=(int)((nx1-nx0)/2.0 + 0.5);// lay o giua truc x for(j=ny0; j<=ny1; j++){ for(k=nz0; k<=nz1; k++){ fprintf(f,"%le %le %le \n",j*mesh_size_y/1.0e-9,k*mesh_size_z/1.0e-9,electron_density[i][j][k]); } } fclose(f); FILE *f1; f1 = fopen("charge_initial_for_Poisson_x_at_midpoint_yz.dat","w"); // "w" neu tep ton tai no se bi xoa if(f1==NULL){ printf("\n Cannot open file charge_initial_for_Poisson_x_at_midpoint_yz.dat "); return ; } fprintf(f1,"\n # x[nm] electron[1/m3] \n"); j=(int)((ny1-ny0)/2.0 + 0.5);// lay o giua truc z k=(int)((nz1-nz0)/2.0 + 0.5);// lay o giua truc z for(i=nx0; i<=nx1; i++){ fprintf(f1,"%le %le \n",i*mesh_size_x/1.0e-9,electron_density[i][j][k]); } fclose(f1); FILE *f2; f2 = fopen("charge_initial_for_Poisson_xy_at_midpoint_z.dat","w"); // "w" neu tep ton tai no se bi xoa if(f2==NULL){ printf("\n Cannot open file charge_initial_for_Poisson_xy_at_midpoint_z.dat "); return ; } fprintf(f2,"\n # x[nm] y[nm] electron[1/m3] \n"); k=(int)((nz1-nz0)/2.0 + 0.5);// lay o giua truc z for(i=nx0; i<=nx1; i++){ for(j=ny0; j<=ny1; j++){ fprintf(f2,"%le %le %le \n",i*mesh_size_x/1.0e-9,j*mesh_size_y/1.0e-9,electron_density[i][j][k]); } } fclose(f2); FILE *f3; f3 = fopen("charge_initial_for_Poisson_y_at_midpoint_xz.dat","w"); // "w" neu tep ton tai no se bi xoa if(f3==NULL){ printf("\n Cannot open file charge_initial_for_Poisson_y_at_midpoint_xz.dat"); return ; } fprintf(f3,"\n # y[nm] electron[1/m3] \n"); i=(int)((nx1-nx0)/2.0 + 0.5);// lay o giua truc x k=(int)((nz1-nz0)/2.0 + 0.5);// lay o giua truc z for(j=ny0; j<=ny1; j++){ fprintf(f3,"%le %le \n",j*mesh_size_y/1.0e-9,electron_density[i][j][k]); } fclose(f3); FILE *f4; f4 = fopen("charge_initial_for_Poisson_z_at_midpoint_xy.dat","w"); // "w" neu tep ton tai no se bi xoa if(f4==NULL){ printf("\n Cannot open file charge_initial_for_Poisson_z_at_midpoint_xy.dat"); return ; } fprintf(f4,"\n # z[nm] electron[1/m3] \n"); i=(int)((nx1-nx0)/2.0 + 0.5);// lay o giua truc x j=(int)((ny1-ny0)/2.0 + 0.5);// lay o giua truc y for(k=nz0; k<=nz1; k++){ fprintf(f4,"%le %le \n",k*mesh_size_z/1.0e-9,electron_density[i][j][k]); } fclose(f4); }// End of if(myrank ==0) return; } // End of void save_initial_charge_density_for_Poisson() //********************************************************************************************** //************************************************************************************************************************ #include "mpi.h" void save_charge_density_for_Poisson(){ int Get_nx0(),Get_nx1(),Get_ny0(),Get_ny1(),Get_nz0(),Get_nz1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int ny0 = Get_ny0(); int ny1 = Get_ny1(); int nz0 = Get_nz0(); int nz1 = Get_nz1(); double Get_mesh_size_x(),Get_mesh_size_y(),Get_mesh_size_z(); double mesh_size_x = Get_mesh_size_x(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); double ***Get_electron_density(); double ***electron_density = Get_electron_density(); int i,j,k; int myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); if(myrank ==0){ FILE *f; f = fopen("charge_density_for_Poisson_yz_at_midpoint_x.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL){ printf("\n Cannot open file charge_density_for_Poisson_yz_at_midpoint_x.dat "); return ; } fprintf(f,"\n # y[nm] z[nm] electron[1/m3] hole[1/m3] \n"); i=(int)((nx1-nx0)/2.0 + 0.5);// lay o giua truc x for(j=ny0; j<=ny1; j++){ for(k=nz0; k<=nz1; k++){ fprintf(f,"%le %le %le \n",j*mesh_size_y/1.0e-9,k*mesh_size_z/1.0e-9,electron_density[i][j][k]); } } fclose(f); FILE *f1; f1 = fopen("charge_density_for_Poisson_x_at_midpoint_yz.dat","w"); // "w" neu tep ton tai no se bi xoa if(f1==NULL){ printf("\n Cannot open file charge_density_for_Poisson_x_at_midpoint_yz.dat "); return ; } fprintf(f1,"\n # x[nm] electron[1/m3] \n"); j=(int)((ny1-ny0)/2.0 + 0.5);// lay o giua truc z k=(int)((nz1-nz0)/2.0 + 0.5);// lay o giua truc z for(i=nx0; i<=nx1; i++){ fprintf(f1,"%le %le \n",i*mesh_size_x/1.0e-9,electron_density[i][j][k]); } fclose(f1); FILE *f2; f2 = fopen("charge_density_for_Poisson_xy_at_midpoint_z.dat","w"); // "w" neu tep ton tai no se bi xoa if(f2==NULL){ printf("\n Cannot open file charge_density_for_Poisson_xy_at_midpoint_z.dat "); return ; } fprintf(f2,"\n # x[nm] y[nm] electron[1/m3] \n"); k=(int)((nz1-nz0)/2.0 + 0.5);// lay o giua truc z for(i=nx0; i<=nx1; i++){ for(j=ny0; j<=ny1; j++){ fprintf(f2,"%le %le %le \n",i*mesh_size_x/1.0e-9,j*mesh_size_y/1.0e-9,electron_density[i][j][k]); } } fclose(f2); FILE *f3; f3 = fopen("charge_density_for_Poisson_y_at_midpoint_xz.dat","w"); // "w" neu tep ton tai no se bi xoa if(f3==NULL){ printf("\n Cannot open file charge_density_for_Poisson_y_at_midpoint_xz.dat"); return ; } fprintf(f3,"\n # y[nm] electron[1/m3] \n"); i=(int)((nx1-nx0)/2.0 + 0.5);// lay o giua truc x k=(int)((nz1-nz0)/2.0 + 0.5);// lay o giua truc z for(j=ny0; j<=ny1; j++){ fprintf(f3,"%le %le \n",j*mesh_size_y/1.0e-9,electron_density[i][j][k]); } fclose(f3); FILE *f4; f4 = fopen("charge_density_for_Poisson_z_at_midpoint_xy.dat","w"); // "w" neu tep ton tai no se bi xoa if(f4==NULL){ printf("\n Cannot open file charge_density_for_Poisson_z_at_midpoint_xy.dat"); return ; } fprintf(f4,"\n # z[nm] electron[1/m3] \n"); i=(int)((nx1-nx0)/2.0 + 0.5);// lay o giua truc x j=(int)((ny1-ny0)/2.0 + 0.5);// lay o giua truc y for(k=nz0; k<=nz1; k++){ fprintf(f4,"%le %le \n",k*mesh_size_z/1.0e-9,electron_density[i][j][k]); } fclose(f4); }// End of if(myrank ==0) return; } // End of void initial_potential_doping() //********************************************************************************************** /* **************************************************************************** De ve potential tai bat cu time step nao ma ta DAT HAM NAY o do Starting date: June 03, 2010 Latest update: June 03, 2010 ***************************************************************************** */ void save_potential(){ int Get_nx0(),Get_nx1(),Get_ny0(),Get_ny1(),Get_nz0(),Get_nz1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int ny0 = Get_ny0(); int ny1 = Get_ny1(); int nz0 = Get_nz0(); int nz1 = Get_nz1(); double Get_mesh_size_x(),Get_mesh_size_y(),Get_mesh_size_z(); double mesh_size_x = Get_mesh_size_x(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); double ***Phi = GetPot(); int i,j,k; int myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); if(myrank ==0){ FILE *f; f = fopen("potential_yz_at_midpoint_x.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL){ printf("\n Cannot open file potential_yz_at_midpoint_x.dat"); return ; } fprintf(f,"\n # y[nm] z[nm] potential[eV] \n"); i=(int)((nx1-nx0)/2.0 + 0.5);// lay o giua truc x for(j=ny0; j<=ny1; j++){ for(k=nz0; k<=nz1; k++){ fprintf(f,"%le %le %le \n",j*mesh_size_y/1.0e-9,k*mesh_size_z/1.0e-9,-Phi[i][j][k]); } // NOTE: ta bieu dien o dang -Phi nhe } fclose(f); // Thu va tuong duong voi mpot.r0 cua GS FILE *f1; f1 = fopen("potential_x_at_midpoint_yz.dat","w"); // "w" neu tep ton tai no se bi xoa if(f1==NULL){ printf("\n Cannot open file potential_x_at_midpoint_yz.dat"); return ; } fprintf(f1,"\n # x[nm] potential_x[eV] \n"); j=(int)((ny1-ny0)/2.0 + 0.5);// lay o giua truc z k=(int)((nz1-nz0)/2.0 + 0.5);// lay o giua truc z for(i=nx0; i<=nx1; i++){ fprintf(f1,"%le %le \n",i*mesh_size_x/1.0e-9,-Phi[i][j][k]);// NOTE: ta bieu dien o dang -Phi nhe } fclose(f1); FILE *f2; f2 = fopen("potential_xy_at_midpoint_z.dat","w"); // "w" neu tep ton tai no se bi xoa if(f2==NULL){ printf("\n Cannot open file potential_xy_at_midpoint_z.dat "); return ; } fprintf(f2,"\n # x[nm] y[nm] potential[eV] \n"); k=(int)((nz1-nz0)/2.0 + 0.5);// lay o giua truc z for(i=nx0; i<=nx1; i++){ for(j=ny0; j<=ny1; j++){ fprintf(f2,"%le %le %le \n",i*mesh_size_x/1.0e-9,j*mesh_size_y/1.0e-9,-Phi[i][j][k]); } // NOTE: ta bieu dien o dang -Phi nhe } fclose(f2); FILE *f3; f3 = fopen("potential_y_at_midpoint_xz.dat","w"); // "w" neu tep ton tai no se bi xoa if(f3==NULL){ printf("\n Cannot open file potential_y_at_midpoint_xz.dat"); return ; } fprintf(f3,"\n # y[nm] potential_y[eV] \n"); i=(int)((nx1-nx0)/2.0 + 0.5);// lay o giua truc x k=(int)((nz1-nz0)/2.0 + 0.5);// lay o giua truc z for(j=ny0; j<=ny1; j++){ fprintf(f3,"%le %le \n",j*mesh_size_y/1.0e-9,-Phi[i][j][k]);// NOTE: ta bieu dien o dang -Phi nhe } fclose(f3); FILE *f4; f4 = fopen("potential_z_at_midpoint_xy.dat","w"); // "w" neu tep ton tai no se bi xoa if(f4==NULL){ printf("\n Cannot open file potential_z_at_midpoint_xy.dat"); return ; } fprintf(f4,"\n # z[nm] potential_z[eV] \n"); i=(int)((nx1-nx0)/2.0 + 0.5);// lay o giua truc x j=(int)((ny1-ny0)/2.0 + 0.5);// lay o giua truc y for(k=nz0; k<=nz1; k++){ fprintf(f4,"%le %le \n",k*mesh_size_z/1.0e-9,-Phi[i][j][k]);// NOTE: ta bieu dien o dang -Phi nhe } fclose(f4); }// End of if(myrank ==0) return; } // End of void initial_potential_doping() //************************************************************************************************************************ <file_sep>#include "petscksp.h" #include "nanowire.h" #include "region.h" #include "nrutil.h" double Func_Nq(int i,int j,int k) { double nq() ; return(nq(i,j,k)) ; } double Func_DNq(int i,int j,int k) { double Dnq() ; return(Dnq(i,j,k)) ; } double nq(int i,int j,int k) { double exp() ; double kT = GetKT() ; double ***phi = GetPhiKth() ; double ***phi_old = GetPot() ; double ***n3d = GetN3d() ; double ***p3d = GetP3d() ; double exp_beta = exp((phi[i][j][k]-phi_old[i][j][k])/kT) ; double x = n3d[i][j][k]*exp_beta - p3d[i][j][k]/exp_beta ; return(x) ; } double Dnq(int i,int j,int k) { double exp() ; double kT = GetKT() ; double ***phi = GetPhiKth() ; double ***phi_old = GetPot() ; double ***n3d = GetN3d() ; double ***p3d = GetP3d() ; double exp_beta = exp((phi[i][j][k]-phi_old[i][j][k])/kT) ; double x= (n3d[i][j][k]*exp_beta + p3d[i][j][k]/exp_beta)/kT ; return(x) ; } double nq_linearized(int p) { double kT = GetKT() ; double ***n3d = GetN3d() ; double ***p3d = GetP3d() ; int i,j,k ; get_ijk(p,&i,&j,&k) ; return((n3d[i][j][k]+p3d[i][j][k])/kT) ; } double nq_linearized2(int p) { double GetDoping() ; double kT = GetKT() ; double ***n3d = GetN3d() ; double ***p3d = GetP3d() ; double ***phi = GetPot() ; int i,j,k ; get_ijk(p,&i,&j,&k) ; return(-(n3d[i][j][k]+p3d[i][j][k])*phi[i][j][k]/kT+(n3d[i][j][k]-p3d[i][j][k])+GetDoping(p)) ; } /****************************************************************************** Thay doi 1 vai cai de mapping code cua ta voi 3D Poisson INPUT: double ***electron_density = Get_electron_density()cua ta dua vao double ***n3d = GetN3d() cua Poisson De tu day trong ham Poisson thi electron_density la n3d. Co thanh phan Nd va Na la doping o S, D va Channel thi da duoc add Getdoping va tu do goi ham Fnn() cho solve_3d_poisson() hoac nq_linearized2() cho solve_3d_poisson_linearized() INPUT: int flag = 0 : Equilibrium Poisson !=0 : Giai cho Non equilibrium Poisson tuc la qua trinh selfconsistently NOTE: Tuy vay ta TACH rieng ra 2 ham cho do lang nhang Starting date: May 04, 2010 Latest update: May 04, 2010 ******************************************************************************/ void get_charge_density_for_Poisson()// Non equilibrium Poisson { // Goi ham double ***Get_electron_density(); // ham cua ta //int find_region(int i,int j,int k);// neu trong vung S,D,Channel thi tinh duoc charge con neu o Oxide thi minh cho charge=0 chu // Bien local double ***electron_density = Get_electron_density(); int Get_nya(),Get_nza(); int nya = Get_nya();int nza = Get_nza(); int np,node; MPI_Comm_rank(PETSC_COMM_WORLD,&node) ; MPI_Comm_size(PETSC_COMM_WORLD,&np) ; double ***n3d = GetN3d() ; double ***p3d = GetP3d(); if( node==0 ) { int i,j,k; //n=0; PoiNum N = GetPoiNum(); for ( i=N.x0 ; i<=N.x1 ; i++ ){ for ( j=N.y0 ; j<=N.y1 ; j++ ){ for ( k=N.z0 ; k<=N.z1 ; k++ ){ //n = find_region(i,j,k); // if((n==1)||(n==2)||(n==3)){// S,D,Channel; // n3d[i][j][k] = electron_density[i][j-nya][k-nza]; // lay tu ham electron_density_calculation() // CHU Y toa de cua mang n3d va electron_densuty la khac nhau. Can mapping voi nhau // chi so i thi TRUNG NHAU, nhung chi so j va k thi KHAC NHAU do electron_density chi dinh nghia trong loi Silicon // } // else{ // n3d[i][j][k] =0.0; } n3d[i][j][k] = electron_density[i][j][k]; p3d[i][j][k] = 0.0; // do ta KHONG simulate hole } } } }// End of if(node==0) /* // Phan save de check o day if( node==0 ) { int i,j,k; PoiNum N = GetPoiNum(); FILE *f; f = fopen("charge_density_for_Poisson.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL){ printf("\n Cannot open file charge_density_for_Poisson.dat"); return ; } fprintf(f,"\n #i j k n3d[1/m3] p3d[1/m3] \n"); for ( i=N.x0 ; i<=N.x1 ; i++ ){ for ( j=N.y0 ; j<=N.y1 ; j++ ){ for ( k=N.z0 ; k<=N.z1 ; k++ ){ fprintf(f," %d %d %d %le %le \n", i,j,k,n3d[i][j][k], p3d[i][j][k]); } } } fclose(f); } */ void mpi_distribute_nq_from_node0();// goi ham nay thoi mpi_distribute_nq_from_node0(n3d,node,np) ; mpi_distribute_nq_from_node0(p3d,node,np) ; }// End of void get_charge_density_for_Poisson()// Non equilibrium Poisson //************************************************************************************** // Starting date: May 04, 2010 // Latest update: June 10, 2010 void get_initial_charge_density_for_Poisson()// charge density tinh tu initial potential { int find_region(int i,int j,int k);// neu trong vung S,D,Channel thi tinh duoc charge con neu o Oxide thi minh cho charge=0 chu double ***Phi = GetPot(); double Get_Vt(); double Vt = Get_Vt(); // SAI double Get_intrinsic_carrier_density();// double Ni = Get_intrinsic_carrier_density(); double Nc_Si = 3.22*1.0e+25;//[m3] // Tai room temperature Nc cua Silicon la 3.22e+19/cm3.Semiconductor Device Fundamental - F.Pierret (page 51) double Ni = Nc_Si; int np,node; MPI_Comm_rank(PETSC_COMM_WORLD,&node) ; MPI_Comm_size(PETSC_COMM_WORLD,&np) ; double ***n3d = GetN3d(); double ***p3d = GetP3d(); double ***Get_electron_density(); // electron density lan dau tien la tinh tu first guess potential double ***electron_density = Get_electron_density(); double GetDrainVoltage(); double Vd = GetDrainVoltage(); Energy *E = PGetEnergy() ; double Fermihalf (double x); if( node==0 ) {// Tinh tai 1 node roi sau do distribute int i,j,k,n=0; PoiNum N = GetPoiNum(); for ( i=N.x0 ; i<=N.x1 ; i++ ){ for ( j=N.y0 ; j<=N.y1 ; j++ ){ for ( k=N.z0 ; k<=N.z1 ; k++ ){ n = find_region(i,j,k); if(n==1){ //S // Boltzmann statistics n3d[i][j][k] = Ni*exp((-Phi[i][j][k]+E->biS)/Vt);// vi tri toa de cua Phi va n3d la TUONG DUONG NHAU du Phi co them 2 index 2 dau //Fermi-Dirac statistics //n3d[i][j][k] = Ni*Fermihalf((-Phi[i][j][k]+E->biS)/Vt); electron_density[i][j][k] = n3d[i][j][k];// de ve ra } else if (n==2){//D //Boltzmann statistics n3d[i][j][k] = Ni*exp((-Phi[i][j][k]+Vd+ E->biD)/Vt); //Fermi-Dirac statistics //n3d[i][j][k] = Ni*Fermihalf((-Phi[i][j][k]+Vd+ E->biD)/Vt); electron_density[i][j][k] =n3d[i][j][k];// de ve ra } else if (n==3){//Ch //Boltzmann statistics n3d[i][j][k] = Ni*exp((-Phi[i][j][k])/Vt); //Fermi-Dirac statistics //n3d[i][j][k] = Ni*Fermihalf((-Phi[i][j][k])/Vt); electron_density[i][j][k] = n3d[i][j][k] ;// de ve ra } else {// o Oxide n3d[i][j][k] = 0.0;// Khong the gop lai vi e mu 0 bang 1 electron_density[i][j][k]=0.0; } p3d[i][j][k] = 0.0; // do ta KHONG simulate hole } } } }// End of if( node==0 ) void mpi_distribute_nq_from_node0();// goi ham nay thoi mpi_distribute_nq_from_node0(n3d,node,np) ; mpi_distribute_nq_from_node0(p3d,node,np) ; } // End of void get_initial_charge_density_for_Poisson() void mpi_distribute_nq_from_node0(double ***nq, int node, int np) { int x0,y0,z0,x1,y1,z1 ; int n,dest,datasize,ntrans,p0,sum_transmitted,tag ; int trans_size = GetTransSize() ; PoiNum N = GetPoiNum() ; MPI_Status status ; x0 = N.x0 ; x1 = N.x1 ; y0 = N.y0 ; y1 = N.y1 ; z0 = N.z0 ; z1 = N.z1 ; datasize = (x1-x0+1)*(y1-y0+1)*(z1-z0+1) ; ntrans = datasize/trans_size ; if ( node==0 ) { for ( dest=1 ; dest<np ; dest++ ) { p0 = 0 ; sum_transmitted = 0 ; tag = 0 ; for ( n=1 ; n<=ntrans ; n++ ) { MPI_Send(&nq[x0][y0][z0]+p0,trans_size,MPI_DOUBLE,dest,++tag,PETSC_COMM_WORLD) ; p0 += trans_size ; sum_transmitted += trans_size ; } if ( sum_transmitted < datasize ) MPI_Send(&nq[x0][y0][z0]+p0,datasize-sum_transmitted,MPI_DOUBLE,dest,++tag,PETSC_COMM_WORLD) ; } } else { p0 = 0 ; sum_transmitted = 0 ; tag = 0 ; for ( n=1 ; n<=ntrans ; n++ ) { MPI_Recv(&nq[x0][y0][z0]+p0,trans_size,MPI_DOUBLE,0,++tag,PETSC_COMM_WORLD,&status) ; p0 += trans_size ; sum_transmitted += trans_size ; } if ( sum_transmitted < datasize ) MPI_Recv(&nq[x0][y0][z0]+p0,datasize-sum_transmitted,MPI_DOUBLE,0,++tag,PETSC_COMM_WORLD,&status) ; } } <file_sep>/* ***************************************************************************** Module nay la de khoi tao cac BIEN va HAM duoc DUNG DI DUNG LAI trong vong lap for cho (Vg va Vd). Starting date: Feb 21, 2010 Update: March 11, 2010 Latest update: May 03, 2010 (Them tham so de mapping voi 3D Poisson) **************************************************************************** */ #include <stdio.h> #include "nrutil.h" #include "constants.h" #include <time.h> #include <unistd.h> static int n_used; // So hat electron ta khoi tao va sau do su dung de chua so hat // electron dang hoat dong trong device static double **p, *energy; static int *valley,*subband;// Hat co valley[]=9 (tuong duong voi ip[]=9 o Semi Monte Carlo) thi se bi inactive va sau do la deleted static double kx, dtau, x_position, electron_energy; static int iv, subb;// iv: de chi valley pair index va subb de chi subband index // ca bien kx,dtau,x_position,e,iv, subb la de dung o ham emcd() va cac ham duoc goi tu ham do static long idum; // Cho ham random2() static double *****wave, ***eig,***eig_jthSchro; // For 2D Schrodinger Eq. static double ***doping,***fai_jthSchro; static double *pot; // For de chuyen 2D fai(i-hang so,j,k) thanh 1D potential dung cho ham makeh.c trong 2D Schrodinger static double **trap_weights; // weighted matrix cho 2D Trapsoidal integration. Day la gia tri co dinh // nen chi can khoi tao 1 lan static double ****form_factor; // de tinh cho phonon scattering static double *****scat_table; // 5D array de luu scattering table. (March 12, 2010 CHUA xet region) static double *max_gm;// la max cua gamma cho tung section. static int iss_out,iss_eli,iss_cre,idd_out,idd_eli,idd_cre;//Tinh so hat VAO/RA de tu do tinh DONG DIEN static int particle_i_th; // Chi hat THU may 26/03/10 15:13 static double ***electron_density;// la electron density tinh o void electron_density_caculation() static double *velocity_x_sum, *energy_sum, *current_sum;// Tinh tong cac gia tri cho all time steps static double *velocity_x_sum_after_transient, *energy_sum_after_transient, *current_sum_after_transient; static double *pot_x_avg, **pot_yz_avg;// potential average theo phuong x khi y va z CO DINH, va trong mat cross-section yz khi x CO DINH void initial_variables(){ // Khoi tao gia tri cho tat ca cac bien o define_functions.c // Goi ham int Get_nx0(),Get_nx1(),Get_ny0(),Get_ny1(),Get_nz0(),Get_nz1(); int Get_nya(),Get_nyb(),Get_nza(),Get_nzb(); int Get_NSELECT(); // Cac bien local int nx0 = Get_nx0(); int nx1 = Get_nx1(); int ny0 = Get_ny0(); int ny1 = Get_ny1(); int nya = Get_nya(); int nyb = Get_nyb(); int nz0 = Get_nz0(); int nz1 = Get_nz1(); int nza = Get_nza(); int nzb = Get_nzb(); int NSELECT = Get_NSELECT(); // Thuc hien int i,j,k,s,v,n,m,e_step; n_used = 0; p = dmatrix (1,max_electron_number,1,4); energy = dvector (1,max_electron_number); valley = ivector (1,max_electron_number); subband = ivector (1,max_electron_number); for(i=1; i<=max_electron_number; i++){ energy[i] = 0.0; valley[i] = 0; subband[i] = 0; for(j=1; j<=4; j++){ p[i][j] = 0.0; } } kx = 0.0; dtau =0.0; x_position = 0.0; electron_energy = 0.0; iv =0; subb = 0; //idum = ((long) time(NULL));// * getpid()); //printf("\n idum =%ld", idum); THU KHONG khoi tao xem sao eig = d3matrix(nx0,nx1,1,3,1,NSELECT);//eig = d3matrix(0,nx_max,1,3,1,NSELECT); ok vi nx0=0 va nx1=nx_max eig_jthSchro = d3matrix(nx0,nx1,1,3,1,NSELECT);//d3matrix(0,nx_max,1,3,1,NSELECT); int ny = nyb - nya; int nz = nzb - nza; wave = d5matrix(nx0,nx1,1,3,1,NSELECT,0,ny,0,nz);//cua Loi Silicon. (May 30, 2010) ro rang so diem chia = so khoang +1 for(s=nx0; s<=nx1; s++){ for(v=1; v<=3; v++){ for(i=1; i<=NSELECT; i++){ eig[s][v][i] = 0.0; eig_jthSchro[s][v][i]=0.0; for(j=0; j<=ny; j++){// Chay tu 0 da the hien so diem chia la + 1 roi con gi for(k=0; k<=nz; k++){ wave[s][v][i][j][k] = 0.0; } } } } } doping = d3matrix(nx0,nx1,ny0,ny1,nz0,nz1); for(i=nx0; i<=nx1; i++){ for(j=ny0; j<=ny1; j++){ for(k=nz0; k<=nz1; k++){ doping[i][j][k] = 0.0; } } } fai_jthSchro = d3matrix(nx0-1, nx1+1, ny0-1, ny1+1, nz0-1, nz1+1); //NOTE cua GS thi Phi chi so lai them dau la -1, duoi la +1 for(i=nx0-1; i<=nx1+1; i++){ for(j=ny0-1; j<=ny1+1; j++){ for(k=nz0-1; k<=nz1+1; k++){ fai_jthSchro[i][j][k] = 0.0; } } } pot = dvector(1,(ny+1)*(nz+1));//Do so diem chia o loi silicon se la nyb-nya+1 va nzb-nza+1 for(i=1; i<=(ny+1)*(nz+1); i++){ pot[i] = 0.0; } trap_weights = dmatrix (ny0,ny1,nz0,nz1); // Khoi tao bien trap_weights lan dau tien for(i=ny0; i<=ny1; i++){ for(j=nz0; j<=nz1; j++){ trap_weights[i][j] = 0.0; } } form_factor = d4matrix(nx0,nx1,1,NSELECT,1,NSELECT,1,9); for(s=nx0; s<=nx1; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(v=1; v<=9; v++){ form_factor[s][n][m][v] = 0.0; } } } } scat_table = d5matrix(nx0,nx1,1,NSELECT,1,NSELECT,1,n_lev,1,21); for(s=nx0; s<=nx1; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(e_step=1; e_step<=n_lev; e_step++){ for(v=1; v<=21; v++){ scat_table[s][n][m][e_step][v]=0.0; } } } } } max_gm = dvector(nx0,nx1); for(s=nx0; s<=nx1; s++){ max_gm[s] = 0.0; } iss_out = 0; iss_eli = 0; iss_cre = 0; idd_out = 0; idd_eli = 0; idd_cre = 0; particle_i_th = 0; electron_density = d3matrix(nx0,nx1,ny0,ny1,nz0,nz1); // ny = nyb - nya; nz = nzb - nza;SO KHOANG CHIA trong loi Silicon, nen so diem chia phai tang them 1 for(i=nx0; i<=nx1; i++){ for(j=ny0; j<=ny1; j++){// CHay tu da the hien so diem chia la +1 roi con gi for(k=nz0; k<=nz1; k++){ electron_density[i][j][k] = 0.0; } } } velocity_x_sum = dvector(nx0,nx1); energy_sum = dvector(nx0,nx1); current_sum = dvector(nx0,nx1); velocity_x_sum_after_transient = dvector(nx0,nx1); energy_sum_after_transient = dvector(nx0,nx1); current_sum_after_transient = dvector(nx0,nx1); for(i=nx0; i<=nx1; i++){ velocity_x_sum[i]=0.0; energy_sum[i]=0.0; current_sum[i]=0.0; velocity_x_sum_after_transient[i]=0.0; energy_sum_after_transient[i]=0.0; current_sum_after_transient[i]=0.0; } pot_x_avg = dvector(nx0,nx1); for(i=nx0; i<=nx1; i++){ pot_x_avg[i] = 0.0; } pot_yz_avg = dmatrix (ny0,ny1,nz0,nz1); for(i=ny0; i<=ny1; i++){ for(j=nz0; j<=nz1; j++){ pot_yz_avg[i][j] = 0.0; } } return; } // End of void initial_variables(){ // Khoi tao gia tri cho tat ca cac bien o define_functions.c // For n_used, khoi tao LAN DAU tai void electrons_initialization() void Set_n_used( int n){ n_used = n; } int Get_n_used(){ return n_used; }// End of for n_used // The parameters for paticles double **Get_p(){ return (p); } double *Get_energy(){ return (energy); } int *Get_valley(){ return (valley); } int *Get_subband(){ return (subband); } void Set_kx(double k_momen_x){ kx = k_momen_x; } double Get_kx(){ return kx; } void Set_dtau(double flight_time){ dtau = flight_time; } double Get_dtau(){ return dtau; } void Set_x_position(double position_in_x){ x_position = position_in_x; } double Get_x_position(){ return x_position; } void Set_electron_energy(double ener){ electron_energy = ener; } double Get_electron_energy(){ return electron_energy; } void Set_iv(int valley_pair_index){ iv = valley_pair_index; } int Get_iv(){ return iv; } void Set_subb(int subband_index){ subb = subband_index; } int Get_subb(){ return subb; } // End of The parameters for paticles // For random2 long Get_idum(){ return idum; } double *****Get_wave(){ return (wave); } double ***Get_eig(){ return (eig); } double ***Get_eig_jthSchro(){ return (eig_jthSchro); } double ***Get_doping(){ return (doping); } double ***Get_fai_jthSchro(){ return (fai_jthSchro); } double *Get_pot(){ return (pot); } double **Get_trap_weights(){ return (trap_weights); } double ****Get_form_factor(){ return (form_factor); } double *****Get_scat_table(){ return (scat_table); } double *Get_max_gm(){ return (max_gm); } void Set_iss_out(int out_p){ // out_p nghia la HAT RA trong tieng Anh iss_out = out_p; } int Get_iss_out(){ return iss_out; } void Set_iss_eli(int eli_p){ // eli_p nghia la LOAI BO HAT trong tieng Anh iss_eli = eli_p; } int Get_iss_eli(){ return iss_eli; } void Set_iss_cre(int cre_p){ // cre_p nghia la TAO HAT MOI trong tieng Anh iss_cre = cre_p; } int Get_iss_cre(){ return iss_cre; } void Set_idd_out(int out_p){ idd_out = out_p; } int Get_idd_out(){ return idd_out; } void Set_idd_eli(int eli_p){ idd_eli = eli_p; } int Get_idd_eli(){ return idd_eli; } void Set_idd_cre(int cre_p){ // cre_p nghia la TAO HAT MOI trong tieng Anh idd_cre = cre_p; } int Get_idd_cre(){ return idd_cre; } void Set_particle_i_th( int i){ // i la thu tu hat i_th o emcd() For checking particle_i_th = i; } int Get_particle_i_th(){ return particle_i_th; } double ***Get_electron_density(){ return (electron_density); } double *Get_velocity_x_sum(){ return (velocity_x_sum); } double *Get_energy_sum(){ return (energy_sum); } double *Get_current_sum(){ return (current_sum); } double *Get_velocity_x_sum_after_transient(){ return (velocity_x_sum_after_transient); } double *Get_energy_sum_after_transient(){ return (energy_sum_after_transient); } double *Get_current_sum_after_transient(){ return (current_sum_after_transient); } double *Get_pot_x_avg(){ return( pot_x_avg); } double **Get_pot_yz_avg(){ return ( pot_yz_avg); } <file_sep>typedef struct { double Temp ; double e_si ; double e_ox ; double offset_gate ; int poi_lin ; int trans_size ; } Param ; typedef struct { double Lsrc ; double Lchannel ; double Lgate ; double Tox ; double Tsi ; double Tbox ; double Tgate ; double Wox ; double Wsi ; double Wgate ; } Dimen ; typedef struct { double kT ; double g_si ; double g_ox ; double c_si ; double c_ox ; double F ; double FnS ; double FnD ; double biS ; double biD ; } Energy ; typedef struct { double A_zero ; double D_zero ; } Density ; Param *PGetParam() ; Param GetParam() ; Dimen *PGetDimen() ; Dimen GetDimen() ; Density *PGetDensity() ; Density GetDensity() ; Energy *PGetEnergy() ; Energy GetEnergy() ; FILE *GetFout() ; void SetFout() ; void SetDrainVoltage() ; double GetDrainVoltage() ; double GetGateVoltage() ; void SetPhi_Contact() ; double GetPhi_Source() ; double GetPhi_Drain() ; double GetPhi_Gate() ; void SetEF() ; void SetEFn() ; void SetEFnS() ; void SetEFnD() ; double GetEF() ; double GetEFnS() ; double GetEFnD() ; double GetESi() ; double GetEOx() ; double GetEc_si() ; double GetEc_ox() ; double GetEc() ; double GetKT() ; double GetN0() ; double GetP0() ; int GetTransSize() ; void GetLocalN() ; void SetDrainVoltage() ; void SetGateVoltage() ; double GetDrainVoltage() ; double GetGateVoltage() ; // Poisson Linearized void SetPoissonLinearized() ; int GetPoissonLinearized() ; // Doping Density void SetDopingDensityFor() ; double GetDopingDensityFor() ; <file_sep>#include "nanowire.h" #include "region.h" static Param P ; static Dimen D ; static Energy E ; static Density n ; Param *PGetParam() { return(&P) ; } Param GetParam() { return(P) ; } Dimen *PGetDimen() { return(&D) ; } Dimen GetDimen() { return(D) ; } Energy *PGetEnergy() { return(&E) ; } Energy GetEnergy() { return(E) ; } Density *PGetDensity() { return(&n) ; } Density GetDensity() { return(n) ; } // EFs double GetEF() { E.F = 0.0 ; // Default return(E.F) ; } double GetEFnS() { return(E.FnS) ; // To be set } double GetEFnD() { return(E.FnD) ; // To be set } double GetESi() { return(P.e_si) ; } double GetEOx() { return(P.e_ox) ; } double GetEc_si() { return(E.c_si) ; } double GetEc_ox() { return(E.c_ox) ; } double GetKT() { return(E.kT) ; } int GetTransSize() { return(P.trans_size) ; } // Phi's static double Phi_Source ; static double Phi_Drain ; static double Phi_Gate ; void SetPhi_Contact() { void assign_built_in_potential() ; assign_built_in_potential() ; //printf("\n ********** From SetPhi_Contact() *********"); double Vd = GetDrainVoltage() ; //printf("\n Drain Voltage Vd = %f", Vd); double Vg = GetGateVoltage() ; //printf("\n Gate Voltage Vg = %f", Vg); Phi_Source = E.biS ; //printf("\n Phi_Source = %f",Phi_Source); Phi_Drain = E.biD + Vd ; //printf("\n Phi_Drain = %f",Phi_Drain); Phi_Gate = Vg - P.offset_gate ; // for n-mos; //Phi_Gate = -Vg + P.offset_gate + Vd ; // for p-mos with CB_PEMT mode //printf("\n Phi_Gate = %f",Phi_Gate); //printf("\n ********** Ket thuc SetPhi_Contact() *********");// getchar(); } double GetPhi_Source() { return(Phi_Source) ; } double GetPhi_Drain() { return(Phi_Drain) ; } double GetPhi_Gate() { return(Phi_Gate) ; } // Ec double GetEc(int i, double y, double z) { PoiNum N = GetPoiNum() ; double *Y = GetPY() ; double *Z = GetPZ() ; double ya = Y[N.ya]-tiny_06 ; double yb = Y[N.yb]+tiny_06 ; double za = Z[N.za]-tiny_06 ; double zb = Z[N.zb]+tiny_06 ; if ( y<ya || y>yb || z<za || z>zb ) return(E.c_ox) ; else return(E.c_si) ; return(0.0) ; // dummy } // Poisson Linearized void SetPoissonLinearized(int n) { P.poi_lin = n ; } int GetPoissonLinearized() { return(P.poi_lin) ; } <file_sep>/* **************************************************************** Tu 1 diem (i,j,k) la toa do cua x,y va z tuong ung -> ta biet duoc diem nay nam o region nao (S, D or Channel) To find a doping region based on node location Region = 1 -> Source Region = 2 -> Drain Region = 3 -> Channel Starting date: Feb 11, 2010 Latest update: Feb 11, 2010 ****************************************************************** */ #include <stdio.h> int find_region(int i,int j,int k){ // Goi cac ham int Get_nx0(),Get_nxa(),Get_nxb(),Get_nx1(); int Get_ny0(),Get_nya(),Get_nyb(),Get_ny1(); int Get_nz0(),Get_nza(),Get_nzb(),Get_nz1(); // Cac bien local int nx0 = Get_nx0(); int nxa = Get_nxa(); int nxb = Get_nxb(); int nx1 = Get_nx1(); int ny0 = Get_ny0(); int nya = Get_nya(); int nyb = Get_nyb(); int ny1 = Get_ny1(); int nz0 = Get_nz0(); int nza = Get_nza(); int nzb = Get_nzb(); int nz1 = Get_nz1(); // Thuc hien int i_reg = 0; if((i>=nx0)&&(i<=nxa)&&(j>=nya)&&(j<=nyb)&&(k>=nza)&&(k<=nzb)) { i_reg = 1; } // Source else if((i>nxa)&&(i<nxb)&&(j>=nya)&&(j<=nyb)&&(k>=nza)&&(k<=nzb)) { i_reg = 3; } // Channel. RAT CHU Y else if((i>=nxb)&&(i<=nx1)&&(j>=nya)&&(j<=nyb)&&(k>=nza)&&(k<=nzb)) { i_reg = 2; } // Drain else { i_reg = 0; } // Outside the regions we consider return i_reg ; //Tuc la ham nay se dua ra duoc o vi tri [i,j] thi la region so may } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <mpi.h> #include "my_util.h" #include "constantsPoisson.h" #include "main.h" #include "poisson3d.h" #include "outs.h" <file_sep>/* ***************************************************************************** To calculate cumulative velocities, energies and current density (su dung average velocity) of the particles INPUT:+ time: - Neu khong co dieu kien gi: tinh tu first dt cho den total time - Neu co DIEU KIEN time > transient_time: chi tinh sau transient time NOTE: chi bang cach tinh nhu the nay thi moi BIET chon transient time bao nhieu la vua + n_time_steps_average=(tot_time-transient_time)/dt -> so lan tinh trung binh + iteration_reference: =1: tinh tong cac gia tri theo tung khoang thoi gian dt =0: luc dt da chay den diem cuoi cung cua total_time ->trung binh cac gia tri OUTPUT: + Write averages in a file (1 file cho all time, 1 file cho after transient time) x-position, velocity_x_average, energy_average, current_sum Starting date: April 1, 2010 Latest update: June 15, 2010 ****************************************************************************** */ #include <stdio.h> #include <math.h> #include "mpi.h" #include "nrutil.h" #include "constants.h" void velocity_energy_cumulative(FILE *f1, FILE *f2, double time,int iteration_reference){//f1 cho All, f2 cho Transient // Goi cac ham int Get_n_used(),*Get_valley();// lay so hat dang co trong device co iv=1,2,3 va co the 9 double **Get_p(),*Get_energy();// tham so hat double Get_nonparabolicity_factor(),Get_ml(), Get_mt(); double Get_dt(),Get_tot_time(),Get_transient_time(); // Xac dinh tu Input.d double Get_mesh_size_x(); double *Get_velocity_x_sum(); double *Get_energy_sum(); double *Get_current_sum(); double *Get_velocity_x_sum_after_transient(); double *Get_energy_sum_after_transient(); double *Get_current_sum_after_transient(); int Get_save_VelEnerCurr_all_time_steps(); // ca velocity, energy va current int Get_save_VelEnerCurr_after_transient();// ca velocity, energy va current void save_VeloEnerCurrent_all_time_steps(FILE *f1, double *velo,double *ener,double *curr,int steps,int nx_max,double mesh_size_x); void save_VeloEnerCurrent_after_transient(FILE *f2,double *velo,double *ener,double *curr,int n_ti,int nx_max,double mesh_size_x); // Cac bien local int n_used = Get_n_used(); //printf("\n n_used at velocity_energy_cumulative() = %d",n_used); int *valley = Get_valley(); double **p = Get_p(); double *energy= Get_energy(); double af = Get_nonparabolicity_factor();//[1/eV] double ml = Get_ml(); // chi la gia tri ml, CHUA nhan voi m0 double mt = Get_mt(); double dt = Get_dt(); // Observation time step double tot_time = Get_tot_time(); // Tong thoi gian chay Simulation double transient_time = Get_transient_time(); // Chon bang BAO NHIEU can KINH NGHIEM int Get_nx0(),Get_nx1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; // int nx_max = Get_nx_max(); double mesh_size_x = Get_mesh_size_x(); double *velocity_x_sum = Get_velocity_x_sum(); double *energy_sum = Get_energy_sum(); double *current_sum = Get_current_sum(); double *velocity_x_sum_after_transient = Get_velocity_x_sum_after_transient(); double *energy_sum_after_transient = Get_energy_sum_after_transient(); double *current_sum_after_transient = Get_current_sum_after_transient(); int save_velo_ener_current_all_time_steps = Get_save_VelEnerCurr_all_time_steps(); int save_velo_ener_current_after_transient = Get_save_VelEnerCurr_after_transient(); // Thuc hien int total_time_steps = (int)(tot_time/dt); // tong so khoang thoi gian dt int n_time_steps_after_transient = (int)((tot_time-transient_time)/dt);//so khoang step cho dt tinh tu sau transient_time double x_position = 0.0; int n_valley = 3;// number of valley pairs = 3 double **velx_sum,**sum_ener,*el_number; // Bien temperary luc tinh TAT CA time steps double **velx_sum_after_transient,**sum_ener_after_transient,*el_number_after_transient; // neu chon chi tinh sau transient time velx_sum = dmatrix(0,nx_max,1,n_valley);// Van toc_x o vi tri i va valley index j sum_ener = dmatrix(0,nx_max,1,n_valley);// Nang luong cua electron o vi tri i va valley index j el_number = dvector(0,nx_max); // So luong electron o vi tri i (chinh la cho moi section) velx_sum_after_transient = dmatrix(0,nx_max,1,n_valley);// Chu "sum" nghia la sume cho cac time step sum_ener_after_transient = dmatrix(0,nx_max,1,n_valley);// do vay sau do phai chia cho tong time step el_number_after_transient = dvector(0,nx_max); // ma no sum int i,j; for(i=0; i<=nx_max; i++){ el_number[i]=0.0; el_number_after_transient[i]=0.0; for(j=1; j<=n_valley; j++){ velx_sum[i][j]=0.0; velx_sum_after_transient[i][j]=0.0; sum_ener[i][j]=0.0; sum_ener_after_transient[i][j]=0.0; } }// End of for(i=0; i<=nx_max; i++) // Buoc 1. CALCULATE THE AVERAGE VALUE IF iteration_reference==0 ********* if(iteration_reference==0){ //Ban dau gan iteration_reference=1 sau do neu j_iter=iter_total // thi ta cho iter_reference=0; de tinh trung binh cho tat ca time steps ma ta cong // Buoc 1.1. Co SAVE cho all time steps KHONG? if(save_velo_ener_current_all_time_steps == 1){//=1 co SAVE // Goi ham de save save_VeloEnerCurrent_all_time_steps(f1,velocity_x_sum,energy_sum,current_sum,total_time_steps,nx_max,mesh_size_x); //Sau khi ghi vao file xong thi minh refresh no lai de dung cho lan sau tuc la cap (Vg va Vd khac) for(i=0; i<=nx_max; i++){ velocity_x_sum[i] = 0.0; energy_sum[i] = 0.0; current_sum[i] = 0.0; } // End of for }// End of if( save_velo_ener_curr_cumu_all_time_steps_or_not ==1) // ***** End of Buoc 1.1. // Buoc 1.2. Co SAVE after transient time KHONG? // Can 2 DIEU KIEN: Co save after transient va time > transient time if((save_velo_ener_current_after_transient==1)&&(time > transient_time)){ // =1 co SAVE // Goi ham de SAVE save_VeloEnerCurrent_after_transient(f2, velocity_x_sum_after_transient,energy_sum_after_transient, current_sum_after_transient,n_time_steps_after_transient,nx_max,mesh_size_x); //Sau khi ghi vao file xong thi minh refresh no lai de dung cho lan sau tuc la cap (Vg va Vd khac) for(i=0; i<=nx_max; i++){ velocity_x_sum_after_transient[i] = 0.0; energy_sum_after_transient[i] = 0.0; current_sum_after_transient[i] = 0.0; } // End of for(i=0; i<=nx_max; i++) }// End of if((save_velo_ener_current_after_transient==1)&&(time > transient_time)) // ***** End of Buoc 1.2. }// End of if(iter_reference==0) //**** End of Buoc 1. CALCULATE THE AVERAGE VALUE IF iteration_reference==0 //Buoc 2. CALCULATE TONG velocity, energy, current NEU iter_reference !=0 // thuc hien tinh cac gia tri tren theo tung time step dt, tu dt, 2dt,3dt,... int n=0,valley_index=0; double ee=0.0, velx=0.0, kx=0.0; // Buoc 2.1. **************************************************************** if(save_velo_ener_current_all_time_steps == 1){//=1 co SAVE. Yeu cau SAVE thi moi CAN TINH for(n=1; n<=n_used; n++){ // Chay cho tung hat tu 1 den n_used if(valley[n] != 9){ i = (int)(p[n][2]/mesh_size_x+0.5); if(i <0) { i=0; } if(i >nx_max) { i=nx_max;} valley_index = valley[n]; // co the la 1, 2 hoac 3 ee = energy[n]; // [ev] lay energy cua hat kx = p[n][1]; // [1/m]lay momentum switch (valley_index) { case 1: // valley_index=1: valley pair 1 thi m* la ml velx = (hbar*kx)/(ml*m0*(1.0+2.0*af*ee));//[m/s] break; case 2: // valley_index=2: valley pair 2 thi m* la mt velx = (hbar*kx)/(mt*m0*(1.0+2.0*af*ee));//[m/s] break; case 3: // valley_index=3: valley pair 3 thi m* la mt velx = (hbar*kx)/(mt*m0*(1.0+2.0*af*ee));//[m/s] break; default: printf("\n Something Wrong! CHECK velocity_energy_cumulative.c"); } // End of switch (valley_index) velx_sum[i][valley_index] += velx; // cong cho tat ca cac hat o cung section sum_ener[i][valley_index] += ee; el_number[i] += 1; }//End of if(valley[n] != 9) } // End of for(int n=1;n<=n_used;n++) double temp_velo=0.0, temp_ener=0.0; for(i=0; i<=nx_max; i++){ // Chay theo phuong x chi tung section if(el_number[i]!=0){ temp_velo = velx_sum[i][1]+velx_sum[i][2]+velx_sum[i][3];//tong velocity tren 3 valleys velocity_x_sum[i] += temp_velo/el_number[i]; //[m/s] current_sum[i] += temp_velo*q/mesh_size_x; //[A/m] Tinh theo cach 2 temp_ener = (sum_ener[i][1]+sum_ener[i][2]+sum_ener[i][3])/el_number[i]; energy_sum[i] += temp_ener; }// End of if(el_number[i]!=0) }// End of for(i=0; i<=nx_max; i++) }// End of if(save_velo_ener_current_all_time_steps == 1) // End of Buoc 2.1. ********************************************************** free_dmatrix(velx_sum,0,nx_max,1,n_valley); free_dmatrix(sum_ener,0,nx_max,1,n_valley); free_dvector(el_number,0,nx_max); // Cac bien KHONG CAN DUNG thi nen Free luon tranh nham lan // Buoc 2.2. **************************************************************** // Can 2 DIEU KIEN: Co save after transient va time > transient time if((save_velo_ener_current_after_transient==1)&&(time > transient_time)){// =1 co SAVE for(n=1; n<=n_used; n++){ if(valley[n] != 9){ i = (int)(p[n][2]/mesh_size_x+0.5); if(i <0) { i=0; } if(i >nx_max) { i=nx_max;} valley_index = valley[n]; ee = energy[n]; kx = p[n][1]; switch (valley_index) { case 1: // valley_index=1: ml velx = (hbar*kx)/(ml*m0*(1.0+2.0*af*ee)); break; case 2: // valley_index=2: mt velx = (hbar*kx)/(mt*m0*(1.0+2.0*af*ee)); break; case 3: // valley_index=3: mt velx = (hbar*kx)/(mt*m0*(1.0+2.0*af*ee));//[m/s] break; default: printf("\n Something Wrong! CHECK velocity_energy_cumulative.c"); } // End of switch (valley_index) velx_sum_after_transient[i][valley_index] += velx; sum_ener_after_transient[i][valley_index] += ee; el_number_after_transient[i] += 1; }//End of if(valley[n] != 9) } // End of for(int n=1;n<=n_used;n++) double temp_velo=0.0, temp_ener=0.0; for(i=0; i<=nx_max; i++){ // Chay theo phuong x cho tung section if(el_number_after_transient[i]!=0){ temp_velo=velx_sum_after_transient[i][1]+velx_sum_after_transient[i][2]+velx_sum_after_transient[i][3]; velocity_x_sum_after_transient[i] += temp_velo/el_number_after_transient[i]; //[m/s] current_sum_after_transient[i] += temp_velo*q/mesh_size_x; //[A/m] Tinh theo cach 2 temp_ener = (sum_ener_after_transient[i][1]+sum_ener_after_transient[i][2]+sum_ener_after_transient[i][3])/el_number_after_transient[i]; energy_sum_after_transient[i] += temp_ener; }// End of if(el_number[i]!=0) }// End of for(i=0; i<=nx_max; i++) }//End of if((save_velo_ener_current_after_transient==1)&&(time > transient_time) // End of // Buoc 2.2. ******************************************************* //End of buoc 2 free_dmatrix(velx_sum_after_transient,0,nx_max,1,n_valley); free_dmatrix(sum_ener_after_transient,0,nx_max,1,n_valley); free_dvector(el_number_after_transient,0,nx_max); // Chu y neu cac bien cuc bo ma ta khoi tao trong 1 ham bang phuong phap trong quyen sach phuong phap so thi //thi cuoi ham ta can free no, neu khong no se gay ra loi tran bo nho khi ta dung ham nay lap di lap lai trong vong while //chang han return; } //***************************************************************************** /* ***************************************************************************** De save_velo_ener_current_all_time_steps vao trong 1 file. INPUT: + velocity_x_sum[i]: i chay tu 0 den nx_max + energy_sum[i]: i chay tu 0 den nx_max + current_sum[i]: i chay tu 0 den nx_max + total_time_step + nx_max + mesh_size_x OUTPUT: + velocity_x_sum[i], energy_sum[i] va current_sum[i] da CHIA CHO total_time_steps de lay duoc gia tri trung binh Save vao file ten la Velo_ener_current_averages_all_time_steps.dat Starting date: April 02, 2010 Latest update: April 02, 2010 ****************************************************************************** */ void save_VeloEnerCurrent_all_time_steps(FILE *f1, double *velocity_x_sum,double *energy_sum,double *current_sum,int total_time_steps,int nx_max,double mesh_size_x) { double x_position = 0.0; //FILE *f; //f=fopen("Velo_ener_current_averages_all_time_steps.dat","a"); // Chu y kieu mo la "a" co the GHI THEM //if(f==NULL){ printf("\n Cannot open file Velo_ener_current_averages_all_time_steps.dat");return;} //fprintf(f,"\n #x[nm] velocity_x[m/s] energy[eV] current\n"); int i , myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); if(myrank ==0){ for(i=0; i<=nx_max; i++){ x_position = (double)(i)*mesh_size_x/1.0e-9;// doi tu [m] sang [nm] fprintf(f1,"%f %le %le %le \n", x_position, velocity_x_sum[i]/((double)(total_time_steps)), // [m/s] energy_sum[i]/((double)(total_time_steps)), // [eV] current_sum[i]/((double)(total_time_steps)) ); } // End of for(i=0;i<=nx_max;i++) } //fclose(f); }// End of void save_VeloEnerCurrent_all_time_steps( /* ***************************************************************************** De save_velo_ener_current_after_transient vao trong 1 file. INPUT: + velocity_x_sum_after_transient[i]: i chay tu 0 den nx_max + energy_sum_after_transient[i]: i chay tu 0 den nx_max + current_sum_after_transient[i]: i chay tu 0 den nx_max + n_time_steps_after_transient + nx_max + mesh_size_x OUTPUT: + velocity_x_sum_after_transient[i], energy_sum_after_transient[i] va current_sum_after_transient[i] da CHIA CHO n_time_steps_after_transient de lay duoc gia tri trung binh Save vao file ten la Velo_ener_current_averages_after_transient.dat Starting date: April 02, 2010 Latest update: April 02, 2010 ****************************************************************************** */ void save_VeloEnerCurrent_after_transient(FILE *f2, double *velocity_x_sum_after_transient,double *energy_sum_after_transient, double *current_sum_after_transient,int n_time_steps_after_transient,int nx_max,double mesh_size_x) { //FILE *f; //f=fopen("Velo_ener_current_averages_after_transient.dat","a"); // Chu y kieu mo la "a" //if(f==NULL){ printf("\n Cannot open file Velo_ener_current_averages_after_transient.dat");return;} //fprintf(f,"\n #x[nm] velocity_x[m/s] energy[eV] current\n"); double x_position = 0.0; int i, myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); if(myrank ==0){ for(i=0; i<=nx_max; i++){ x_position = (double)(i)*mesh_size_x/1.0e-9;// doi tu [m] sang [nm] fprintf(f2,"%f %le %le %le \n", x_position, velocity_x_sum_after_transient[i]/((double)(n_time_steps_after_transient)), // [m/s] energy_sum_after_transient[i]/((double)(n_time_steps_after_transient)), // [eV] current_sum_after_transient[i]/((double)(n_time_steps_after_transient)) ); } // End of for(i=0;i<=nx_max;i++) } //fclose(f); }// End of void save_VeloEnerCurrent_after_transient <file_sep>/* ***************************************************************************** First order correction for eigen energy using time-independent perturbation Reference: Applied Quantum Mechanics, <NAME>., 2003. Chapter 10. INPUT: StepsUsedCorrection: buoc j_th time steps ta su dung eigen energy correction OUTPUT: eigen energy da duoc correction qua khoang step thu j-th Starting date: April 19, 2010 Update: April 20, 2010. Latest update: May 17, 2010 ******************************************************************************** */ #include <stdio.h> #include "nrutil.h" #include "petscksp.h" #include "nanowire.h" #include "region.h" void eigen_energy_correction(int StepsUsedCorrection){ void save_eig_correction(int StepsUsedCorrection); double *****Get_wave(); double *****wave = Get_wave(); // de lay wave double ***Get_eig(),***Get_eig_jthSchro(); double ***eig = Get_eig(); //eigen energy se thay doi sau nhung khoang thoi gian dt double ***eig_jthSchro = Get_eig_jthSchro();// giu gia tri eig tai jth Schrodinger solution double ***Phi = GetPot(); double ***Get_fai_jthSchro(),*Get_pot();//chuyen fai(s-th,j,k) thanh pot 1D (potential 1D) double ***fai_jthSchro = Get_fai_jthSchro();// giu gia tri cua potential tai jth Schrodinger solution double *pot = Get_pot(); int Get_nx0(),Get_nx1(),Get_ny0(),Get_nya(),Get_nyb(),Get_ny1(),Get_nz0(),Get_nza(),Get_nzb(),Get_nz1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int ny0 = Get_ny0(); int nya = Get_nya(); int nyb = Get_nyb(); int ny1 = Get_ny1(); int nz0 = Get_nz0(); int nza = Get_nza(); int nzb = Get_nzb(); int nz1 = Get_nz1(); int nx_max = nx1-nx0; // int nx_max = Get_nx_max(); int ny_max = nyb - nya;// De thay doi it nhat co the int nz_max = nzb - nza;// DO sau do ta chay tu 0 den ny_max va nz_max nen do DIEM CHIA ls ok (May 30, 2010) int Get_NSELECT(),Get_NTimeSteps(); int NSELECT = Get_NSELECT(); int NTimeSteps = Get_NTimeSteps(); // Thuc hien int s,v,i,j,k; //double temp = 0.0; //Buoc 1. // Lan dau tien goi ham eigen_energy_correction se phai giu gia tri eigen energy // va potential vi no chinh la gia tri tu j-th Schrodinger solution if(StepsUsedCorrection % NTimeSteps ==1){ // Buoc 1.1. Gan eig tai jth Schrodinger solution cho eig_jthSchro for(s=0; s<=nx_max; s++){ for(v=1; v<=3; v++){ for(i=1; i<=NSELECT; i++){ eig_jthSchro[s][v][i] = eig[s][v][i]; } } }// End of for(s=0; s<=nx_max; s++) // Buoc 1.2. Gan potential tai jth Schrodinger solution cho eig_jthSchro for(s=0; s<=nx_max; s++){ for(j=ny0; j<=ny1; j++){ for(k=nz0; k<=nz1; k++){ fai_jthSchro[s][j][k] = Phi[s][j][k]; } } }// End of for(i=0; i<=nx_max; i++) // Buoc 1.3. Khong can gan wave boi vi minh khong update wave neu khong giai Schrodinger } // End of if(StepsUsedCorrection % NTimeSteps ==1) // Buoc 2. Tinh eigen energy duoc correction // Buoc 2.1. Tinh delta_fai double ***delta_fai=d3matrix(0,nx_max,ny0,ny1,nz0,nz1); for(s=0; s<=nx_max; s++){ for(j=ny0; j<=ny1; j++){ for(k=nz0; k<=nz1; k++){ // CHECK LAI XEM LA DAU - hay +. Check theo bai bao cua ho thi del_fai=Vcu(eV)-Vmoi(eV) delta_fai[s][j][k]= fai_jthSchro[s][j][k]-Phi[s][j][k]; } } }// End of for(i=0; i<=nx_max; i++) // Buoc 2.2 Tinh eigen energy double delta_ener; // CHU Y: index cua wave la o trong vung ma ta giai 2D Schrodinger for(s=0; s<=nx_max; s++){// cung chinh la i o tren for(v=1; v<=3; v++){ for(i=1; i<=NSELECT; i++){ delta_ener = 0.0; for(j=0; j<=ny_max; j++){// chay tu 0 da the hien so diem chia can +1 (May 30, 2010) for(k=0; k<=nz_max; k++){ delta_ener += wave[s][v][i][j][k]*delta_fai[s][j][k]*wave[s][v][i][j][k]; } }// end of for(j=0; j<=ny_max; j++) eig[s][v][i] = eig_jthSchro[s][v][i] + delta_ener; }// End of for(i=1; i<=NSELECT; i++) }//End of for(v=1; v<=3; v++) }// End of for(s=0; s<=nx_max; s++) // Save ca xem sao save_eig_correction(StepsUsedCorrection); // Free local array free_d3matrix(delta_fai,0,nx_max,ny0,ny1,nz0,nz1); }// End of void eigen_energy_correction() //****************************************************************************** /* ***************************************************************************** Starting date: April 21, 2010 Latest update: April 21, 2010. ******************************************************************************** */ void save_eig_correction(int StepsUsedCorrection){ // Goi ham double ***Get_eig(); int Get_NSELECT(); // bien local double ***eig = Get_eig(); int NSELECT = Get_NSELECT(); int Get_nx0(),Get_nx1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; // int nx_max = Get_nx_max(); // Thuc hien int s=(int)(nx_max/2+0.5);// lay section o giua int i,v; FILE *f; f = fopen("eig_correction.dat","a"); // "w" neu tep ton tai no se bi xoa if(f == NULL) { printf("\n Cannot open file eig_correction.dat"); return ; } fprintf(f,"\n # s_th v_th i_subband time eigen_correction[eV] \n"); for(v=1; v<=3; v++){ for(i=1; i<=NSELECT; i++){ // do m o ham dsyevx tu diasym la bang NSELECT fprintf(f,"%d %d %d %d %le \n",s,v,i,StepsUsedCorrection,eig[s][v][i]); } } fclose(f); return; }// End of void void save_eig_correction() <file_sep>/* ***************************************************************************** This functin is to calculate the current based on the charges entering and exiting each terminal contact -> noisy: due to discrete nature of the electrons -> fitting data Starting date: April 6, 2010 Latest update: April 6, 2010 ****************************************************************************** */ #include <stdio.h> #include "constants.h" #include "nrutil.h" void current_calculation(double *cur_av){ // Goi cac ham void linreg(double x[],double y[],double sigma[],int N,double a_fit[],double sig_a[],double yy[],double *chisqr ); double Get_Vd_start(),Get_Vd_end(),Get_Vd_step(); double Get_Vg_start(),Get_Vg_end(),Get_Vg_step(); double Get_dt(),Get_tot_time(),Get_transient_time(); // Bien local double Vd_start = Get_Vd_start(); double Vd_end = Get_Vd_end(); double Vd_step = Get_Vd_step(); double Vg_start = Get_Vg_start(); double Vg_end = Get_Vg_end(); double Vg_step = Get_Vg_step(); double dt = Get_dt(); printf("\n dt=%le",dt); double tot_time = Get_tot_time(); printf("\n total_time =%le",tot_time); double transient_time = Get_transient_time(); printf("\n transient_time=%le",transient_time); // Thuc hien double *rtime,*rtime2,*source,*source2,*drain,*drain2,*sigma,*yy,*a_fit,*sig_a; int i, N=0, N_process=0;//N: is the dimension of the matrix -> to avoid RUNTIME ERROR N_process=((int)((Vg_end-Vg_start)/Vg_step) + 1)*((int)((Vd_end-Vd_start)/Vd_step) + 1); int t1 = (int)(tot_time/1.0e-16);// vi khi doc vao cac gia tri thi neu DO CHINH XAC o input file khac nhau thi gia tri thuc te se khac nhau 1 ti int t2 = (int)(transient_time/1.0e-16); int t3 = (int)(dt/1.0e-16); //printf("\n t1=%d, t2=%d, t3=%d", t1,t2,t3); N = (int)((t1-t2)/t3)*N_process; printf("\n N=%d,N_process=%d",N,N_process);//getchar(); rtime = dvector(1,N); rtime2 = dvector(1,N); source = dvector(1,N); source2 = dvector(1,N); drain = dvector(1,N); drain2 = dvector(1,N); sigma = dvector(1,N); yy = dvector(1,N); a_fit = dvector(1,2); sig_a = dvector(1,2); for(i=1; i<=N; i++){ rtime[i] = 0.0; rtime2[i] = 0.0; source[i] = 0.0; source2[i] = 0.0; drain[i] = 0.0; drain2[i] = 0.0; sigma[i] = 0.0; yy[i] = 0.0; } for(i=1; i<=2; i++){ a_fit[i] = 0.0; sig_a[i] = 0.0; } //double width = device_width*1.0e6; // [micro m] FILE *ff_transient; ff_transient=fopen("charge_source_drain_transient.dat","r"); if(ff_transient==NULL){printf("can't open charge_source_drain_transient.dat\n");return;} int j=1; while (!feof(ff_transient)){ fscanf(ff_transient,"%le %le %le ",&rtime[j],&source[j],&drain[j]); //NOTE: rtime[]: la thoi gian chay -> don vi se la [s] // source[]:la tong so hat vao ra o cuc Source -> don vi se la [C] culong // drain[]: la tong so hat vao ra o cuc Drain -> don vi se la [C] culong j = j + 1;// Ket qua cuoi cung j la tong so dong trong file charge_source_drain_transient.dat } fclose(ff_transient); int j_fix = j - 1; // j_fix la tong so dong trong file charge_source_drain_transient.dat int jskip = (int)(j_fix/2); // la 1/2 so dong trong file charge_source_drain_transient.dat FILE *f; f=fopen("calculated_current_2_txt.dat","a"); // Chua thay co ung dung gi ca if(f==NULL){printf("Can't open calculated_current_2_txt.dat.\n");return;} fprintf(f,"\n # rtime[s] source drain \n"); double sum_source = 0.0; double sum_drain = 0.0; int jj=0; j=0; for(j=1;j<=j_fix;j++){ // di tu dong dau tien den dong cuoi cung trong file charge_source_drain_transient.dat sum_source += source[j]; // tong so hat (o cuc Source) theo tat ca cac dong sum_drain += drain[j]; // tong so hat (o cuc Drain) theo tat ca cac dong if(j >jskip) { // Ta chi dung cac lenh sau cho nhung dong o nua sau cua file charge_source_drain_transient.dat jj = jj + 1; // tinh so dong o nua sau, chu y ban dau jj=0 nhe rtime2[jj] = rtime[j]; sigma[jj] = 1.0; source2[jj] = -sum_source; drain2[jj] = sum_drain; fprintf(f,"%le %le %le \n ",rtime[j],-sum_source,sum_drain); // Xem hinh 15 quyen sach cua GS do }// End of if }// End of for fclose(f); double chisqr = 0.0; linreg(rtime2,source2,sigma,jj,a_fit,sig_a,yy,&chisqr); // min cho Source /* Nhu vay co the thay ta chi lam min o nua sau cua file charge_source_drain_transient.dat thoi */ //double cur_source = 1.602e-19*a_fit[2]/width*1.e6; double cur_source = q*a_fit[2];// Tu ta them vao linreg(rtime2,drain2,sigma,jj,a_fit,sig_a,yy,&chisqr); // min cho Drain //double cur_drain = 1.602e-19*a_fit[2]/width*1.e6; double cur_drain = q*a_fit[2]; //printf("\n Source current = %le",cur_source); //printf("\n Drain_current = %le",cur_drain); *cur_av = 0.5*(cur_source + cur_drain); printf("\n Tai current_calculation(): Average current = %le",0.5*(cur_source + cur_drain)); //getchar(); // Free for local vectors //* Khong hieu tai sao neu dung free_dvector o dat thi lai co loi segmentation fault (29-Jan-2009) free_dvector(rtime,1,N); free_dvector(rtime2,1,N); free_dvector(source,1,N); free_dvector(source2,1,N); free_dvector(drain,1,N); free_dvector(drain2,1,N); free_dvector(sigma,1,N); free_dvector(yy,1,N); free_dvector(a_fit,1,2); free_dvector(sig_a,1,2); // */ return; }// End of current_calculation() /********************************************************************************* Function to perform linear regression (fit a line) Inputs x Independent variable y Dependent variable sigma Estimated error in y N Number of data points Outputs a_fit Fit parameters; a(1) is intercept (phan chan), a(2) is slope sig_a Estimated error in the parameters a() yy Curve fit to the data chisqr Chi squared statistic Reference: fit.c - Numerical Recipes for C - page 665 "Fitting data to a Straight Line" Latest update January 7, 2009 ***********************************************************************************/ // Vi x,y, sigma la cac mang dau vao va khong thay doi nen ta co the them constant dang truoc // vi du: void linreg(constant double x[],constant double y[],constant double sigma[] #include<math.h> void linreg( double x[],double y[],double sigma[],int N ,double a_fit[],double sig_a[],double yy[],double *chisqr ) { int i = 0; double sigmaTerm = 0.0, s = 0.0, sx = 0.0, sy = 0.0; double sxy = 0.0, sxx = 0.0, denom = 0.0, delta = 0.0; // Evaluate various sigma sums s = 0.0; sx = 0.0; sy = 0.0; sxy = 0.0; sxx = 0.0; for(i=1;i<=N;i++){ sigmaTerm = 1.0/sigma[i]*sigma[i]; s = s + sigmaTerm; sx = sx + x[i]*sigmaTerm; sy = sy + y[i]*sigmaTerm; sxy = sxy + x[i]*y[i]*sigmaTerm; sxx = sxx + x[i]*x[i]*sigmaTerm; } denom = s*sxx - sx*sx; // Compute intercept a_fit[1] and slope a_fit[2] a_fit[1] = (sxx*sy - sx*sxy)/denom; a_fit[2] = (s*sxy - sx*sy)/denom; // Compute error bars for intercept and slope sig_a[1] = sqrt(sxx/denom); sig_a[2] = sqrt(s/denom); // Evaluate curve fit at each data point and compute Chi^2 *chisqr = 0.0; for(i=1;i<=N;i++){ yy[i] = a_fit[1]+a_fit[2]*x[i]; // Curve fit to the data delta = (y[i]-yy[i])/sigma[i]; *chisqr = *chisqr + delta*delta; // Chi square } return; }// End of linreg() function <file_sep>/* ************************************************************************ To read parameters from the SCATTERING_LIST and SAVE_LIST in input.dat file Starting date: March 11, 2010 Latest update: March 11, 2010 *************************************************************************** */ #include <stdio.h> #include <string.h> #include "mpi.h" #include "constants.h" #include "nrutil.h" int static num_scat_used =0; // Tinh so luong scattering mechanism su dung // For #SCATTERING_LIST int static flag_ballistic_transport,flag_acoustic,flag_zero_order_optical; int static flag_first_order_optical,flag_Coulomb, flag_Surface_roughness; // For #SAVE_LIST int static save_eig_wavefuntion; int static save_doping_potential_init; int static save_electron_initlization; int static save_form_factor; int static save_scattering_rate; // tuc la scattering table int static save_electron_population; // Save N_s,v,i int static save_electron_density; //[1/m3] int static save_VelEnerCurr_all_time_steps;// ca velocity energy va current int static save_VelEnerCurr_after_transient;// ca velocity energy va current int static save_init_free_flight; //****************************************************************************** void read_scattering_save_list(){ FILE *f; // Read #SCATTERING_LIST f=fopen("Input.d","r"); if(f==NULL){printf("Error: can't open file Input.d.\n"); return;} else { // printf("\n\n Reading #SCATTERING_LIST"); } while(!feof(f)) { char str[180]; fscanf(f,"%s",str); if(strcmp(str,"#SCATTERING_LIST")==0){ fscanf(f,"%*s %*s %d ",&flag_ballistic_transport); fscanf(f,"%*s %*s %d ",&flag_acoustic); fscanf(f,"%*s %*s %d ",&flag_zero_order_optical); fscanf(f,"%*s %*s %d ",&flag_first_order_optical); fscanf(f,"%*s %*s %d ",&flag_Coulomb); fscanf(f,"%*s %*s %d ",&flag_Surface_roughness); } // End of if }// End of while fclose(f); //If flag_ballistic_transport=1 Ballistic; =0: Diffusive; //DEFAULT: Ballistic=0=>Diffusive Model if(flag_ballistic_transport==1) { //=1 Ballistic (NO Scattering) // O ham emcd.c cung phan ra hai truong hop nhu the nay //printf("\n We use BALLISTIC TRANSPORT MODEL"); flag_acoustic = 0; // set lai tat ca cac scattering flags bang 0 het flag_zero_order_optical = 0; flag_first_order_optical = 0; flag_Coulomb = 0; flag_Surface_roughness = 0; } else {// ballistic_transport !=1 -> Diffusive: Chon loai scattering //printf("\n We use DIFFUSIVE TRANSPORT MODEL");// Gia tri cac scattering_flags tu Input.d file if(flag_acoustic==1){ num_scat_used = num_scat_used +1;// so luong scattering mechanims tang len 1 //printf("\n Acoustic phonon scattering is Included"); } else { //printf("\n Acoustic phonon scattering is NOT included"); } if(flag_zero_order_optical==1){ num_scat_used = num_scat_used +1; //printf("\n Zero-order Non-polar Optical phonon is Included"); } else { //printf("\n Zero-order Non-polar Optical phonon is NOT included"); } if(flag_first_order_optical==1){ num_scat_used = num_scat_used +1; //printf("\n First-order Non-polar Optical phonon is Included"); } else { //printf("\n First-order Non-polar Optical phonon is NOT included"); } if(flag_Coulomb==1){ num_scat_used = num_scat_used +1; //printf("\n Coulomb scattering is Included"); } else { //printf("\n Coulomb scattering is NOT included"); } if(flag_Surface_roughness==1){ num_scat_used = num_scat_used +1; //printf("\n Surface roughness scattering is Included"); } else { //printf("\n Surface roughness scattering is NOT included"); } //printf("\n Number of Scattering Mechanims in used = %d",num_scat_used); if(num_scat_used > n_scatt_max){ printf("\n Number of scattering mechanisms exceeds maximum number"); printf("\n You can change n_scatt_max in constants.h file \n"); nrerror("scattering mechanisms exceeds maximum number"); } //else { printf("\n Number of scattering mechanisms using is = %d",i_count);} // }// End of if (doping_density[i_g]!=0.0) }// End of else {// ballistic_transport !=1 -> Diffusive: Chon loai scattering // END of Read SCATTERING_LIST // Read #SAVE_LIST f=fopen("Input.d","r"); if(f==NULL){printf("Error: can't open file Input.d.\n"); return;} else { //printf("\n Reading #SAVE_LIST"); } while(!feof(f)) { char str[180]; fscanf(f,"%s",str); if(strcmp(str,"#SAVE_LIST")==0){ fscanf(f,"%*s %*s %d ",&save_eig_wavefuntion); fscanf(f,"%*s %*s %d ",&save_doping_potential_init); fscanf(f,"%*s %*s %d ",&save_electron_initlization); fscanf(f,"%*s %*s %d ",&save_form_factor); fscanf(f,"%*s %*s %d ",&save_scattering_rate); fscanf(f,"%*s %*s %d ",&save_electron_population); fscanf(f,"%*s %*s %d ",&save_electron_density); fscanf(f,"%*s %*s %d ",&save_VelEnerCurr_all_time_steps); fscanf(f,"%*s %*s %d ",&save_VelEnerCurr_after_transient); fscanf(f,"%*s %*s %d ",&save_init_free_flight); } // End of if }// End of while fclose(f); //printf("\n save_eig_wavefuntion = %d",save_eig_wavefuntion); //printf("\n save_doping_potential_init = %d",save_doping_potential_init); //printf("\n save_electron_initlization = %d",save_electron_initlization); //printf("\n save_form_factor = %d",save_form_factor); //printf("\n save_scattering_rate = %d",save_scattering_rate); //printf("\n save_electron_population = %d",save_electron_population); //printf("\n save_electron_density = %d",save_electron_density); //printf("\n save_VelEnerCurr_all_time_steps = %d",save_VelEnerCurr_all_time_steps); //printf("\n save_VelEnerCurr_after_transient = %d",save_VelEnerCurr_after_transient); //printf("\n save_init_free_flight = %d",save_init_free_flight); //Phan printf ra Monitor o node co rank=0 int myrank, mysize; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); MPI_Comm_size(MPI_COMM_WORLD,&mysize); if(myrank ==0){ printf("\n\n Reading #SCATTERING_LIST"); if(flag_ballistic_transport==1) { printf("\n We use BALLISTIC TRANSPORT MODEL"); } else {// ballistic_transport !=1 -> Diffusive: Chon loai scattering printf("\n We use DIFFUSIVE TRANSPORT MODEL");// Gia tri cac scattering_flags tu Input.d file if(flag_acoustic==1){ printf("\n Acoustic phonon scattering is Included"); } else { printf("\n Acoustic phonon scattering is NOT included");} if(flag_zero_order_optical==1){ printf("\n Zero-order Non-polar Optical phonon is Included"); } else { printf("\n Zero-order Non-polar Optical phonon is NOT included");} if(flag_first_order_optical==1){ printf("\n First-order Non-polar Optical phonon is Included"); } else { printf("\n First-order Non-polar Optical phonon is NOT included");} if(flag_Coulomb==1){ printf("\n Coulomb scattering is Included"); } else { printf("\n Coulomb scattering is NOT included");} if(flag_Surface_roughness==1){ printf("\n Surface roughness scattering is Included"); } else { printf("\n Surface roughness scattering is NOT included");} printf("\n Number of Scattering Mechanims in used = %d",num_scat_used); if(num_scat_used > n_scatt_max){ printf("\n Number of scattering mechanisms exceeds maximum number"); printf("\n You can change n_scatt_max in constants.h file \n"); nrerror("scattering mechanisms exceeds maximum number"); } } }//End of if(myrank ==0) return; // End of Read #SAVE_LIST }// End of void read_scattering_save_list() // ***************************************************************************** int Get_num_scat_used(){ return num_scat_used; } int Get_flag_ballistic_transport(){ return flag_ballistic_transport; } int Get_flag_acoustic(){ return flag_acoustic; } int Get_flag_zero_order_optical(){ return flag_zero_order_optical; } int Get_flag_first_order_optical(){ return flag_first_order_optical; } int Get_flag_Coulomb(){ return flag_Coulomb; } int Get_flag_Surface_roughness(){ return flag_Surface_roughness; } int Get_save_eig_wavefuntion(){ return save_eig_wavefuntion; } int Get_save_doping_potential_init(){ return save_doping_potential_init; } int Get_save_electron_initlization(){ return save_electron_initlization; } int Get_save_form_factor(){ return save_form_factor; } int Get_save_scattering_rate(){ return save_scattering_rate; } int Get_save_electron_population(){ return save_electron_population; } int Get_save_electron_density(){ return save_electron_density; } int Get_save_VelEnerCurr_all_time_steps(){ return save_VelEnerCurr_all_time_steps; } int Get_save_VelEnerCurr_after_transient(){ return save_VelEnerCurr_after_transient; } int Get_save_init_free_flight(){ return save_init_free_flight; } <file_sep>/* ****************************************************************************** To write potential average after transient time NOTE: La tinh trung binh tai 1 gia tri (depth va width) hoac lenght doc tu Input file INPUT: time: thoi gian ma simulation dang chay (tu dt den total_time) iter_reference: if ==0: tinh trung binh cac gia tri (luc dt da chay den diem cuoi cung cua total_time) else: tinh tong cac gia tri. OUTPUT: To write average related parameters NOTE: Tinh toan va chay cho 1 node thoi Starting date: May 24, 2010 Latest Update: June 15, 2010 ****************************************************************************************** */ #include <stdio.h> #include <math.h> #include "mpi.h" #include "petscksp.h" #include "nanowire.h" #include "region.h" #include "nrutil.h" #include "constants.h" void save_potential_average(FILE *f1, FILE *f2, double time, int iter_reference) {//f1 ve cho x, f2 ve cho yz double ***Phi = GetPot(); double *Get_pot_x_avg(); double *pot_x_avg = Get_pot_x_avg(); double **Get_pot_yz_avg(); double **pot_yz_avg = Get_pot_yz_avg(); int Get_nx0(),Get_nx1(), Get_ny0(),Get_ny1(), Get_nz0(),Get_nz1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int ny0 = Get_ny0(); int ny1 = Get_ny1(); int nz0 = Get_nz0(); int nz1 = Get_nz1(); int nx_max = nx1-nx0; int ny_max = ny1-ny0; int nz_max = nz1-nz0; double Get_mesh_size_x(),Get_mesh_size_y(),Get_mesh_size_z(); double mesh_size_x = Get_mesh_size_x(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); double Get_Eg(); // Band gap double Eg = Get_Eg(); double delta_Ec = Eg/2.0;// double delta_Ec = 0.0;// NOTE ta ve dang -Phi(i,j,k) thoi double Get_length_plotted(), Get_depth_plotted(), Get_width_plotted(); double length = Get_length_plotted();// doc vao o read_simulation_list.c da chuyen sang dang [m] double depth = Get_depth_plotted(); double width = Get_width_plotted(); double Get_transient_time(); double transient_time = Get_transient_time(); // Chon bang BAO NHIEU can KINH NGHIEM int i,j,k; int myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); if(myrank ==0){// NOTE chi tinh toan tren 1 node thoi /* *************************************************************************************** time > transient_time: Tinh tong cac gia tri **************************************************************************************** */ if(time > transient_time){// Neu thoi gian time lon hon gia tri transient time duoc doc tu input file thi ta se tinh tong // Tinh trung binh theo phuong x voi gia tri co dinh y va z doc tu input file j = (int)(depth/mesh_size_y + 0.5); k = (int)(width/mesh_size_z + 0.5); for (i=0; i<=nx_max; i++){ pot_x_avg[i] += (delta_Ec - Phi[i][j][k]); } // Tinh trung binh theo yz khi x la co dinh i = (int)(length/mesh_size_x + 0.5); for(j=0; j<=ny_max; j++){ for(k=0; k<=nz_max; k++){ pot_yz_avg[j][k] += (delta_Ec - Phi[i][j][k]); } } } // End of if(time > transient_time) nghia la het phan cong cac gia tri /* *************************************************************************************** End of time > transient_time: Tinh tong cac gia tri **************************************************************************************** */ /* *************************************************************************************** iter_reference ==0: Calculating time averaging excluding initial transient **************************************************************************************** */ // Den phan tinh trung binh cong cac gia tri theo phuong x HOAC mat yz double x_pos = 0.0, y_pos = 0.0, z_pos = 0.0; if(iter_reference == 0){ //iter_reference==0: tinh trung binh cac gia tri (luc time da chay den diem cuoi cung cua total_time) double Get_dt(),Get_tot_time(); double dt = Get_dt(); // Observation time step double tot_time = Get_tot_time(); // Tong thoi gian chay Simulation int n_time_steps_after_transient = (int)((tot_time-transient_time)/dt);//so khoang step cho dt tinh tu sau transient_time //FILE *f; //f = fopen("average_potential_along_x.dat","w");// Do la "w" nen neu chay nhieu cap (Vd,Vg) thi no la CAP CUOI CUNG //if(f == NULL){printf("\n Cannot open file average_potential_along_x.dat");return; } //fprintf(f,"\n #x[nm] Pot_x[eV] \n"); x_pos = 0.0; if(n_time_steps_after_transient > 0){ for(i=0;i<=nx_max;i++){ x_pos = (double)(i)*mesh_size_x/1.0e-9;// [m] -> [nm] pot_x_avg[i] = pot_x_avg[i]/((double)(n_time_steps_after_transient));// Vay ghi vao file la da ghi gia tri trung binh roi nhe ! fprintf(f1, "%le %le \n", x_pos,pot_x_avg[i]); } } // End of if(n_time_steps_after_transient > 0) //fclose(f); //FILE *f_avg_yz; //f_avg_yz = fopen("average_potential_yz_plane.dat","w"); //if(f_avg_yz == NULL){printf("\n Cannot open file average_potential_yz_plane.dat");return; } //fprintf(f_avg_yz,"\n #y[nm] z[nm] Pot_avg_yz[eV] \n"); y_pos = 0.0, z_pos = 0.0; if(n_time_steps_after_transient > 0){ for(j=0;j<=ny_max;j++){ y_pos = (double)(j)*mesh_size_y/1.0e-9;// [m] -> [nm] for(k=0; k<=nz_max; k++){ z_pos = (double)(k)*mesh_size_z/1.0e-9; pot_yz_avg[j][k] = pot_yz_avg[j][k]/((double)(n_time_steps_after_transient)); fprintf(f2," %le %le %le \n",y_pos,z_pos, pot_yz_avg[j][k]);// potential[eV] } //End of for(k=0; k<=nz_max; k++) } // End of for(j=0;j<=ny_max;j++){ }// End of if(n_time_steps_after_transient > 0) //fclose(f_avg_yz); //NOTE: reset; Thuc te thi phan nay chi tinh 1 lan duy nhat khi time da chay den total time Nhung do no chay cho cac gia tri Vd va Vg khac nhau nen can reset for(i=nx0; i<=nx1; i++){ pot_x_avg[i] = 0.0; } for(i=ny0; i<=ny1; i++){ for(j=nz0; j<=nz1; j++){ pot_yz_avg[i][j] = 0.0; } } } // End of if(iter_reference ==0){ /* *************************************************************************************** End of iter_reference ==0: Calculating time averaging excluding initial transient **************************************************************************************** */ }// End of if(myrank ==0){ return; }// End of void save_potential_average(double time, int iter_reference) <file_sep>/* ***************************************************************************** PERFORM THE K-SPACE AND REAL-SPACE MOTION OF THE CARRIERS This function is to calculate the momentums and positions of the particle which drifts during time (tau) + F tinh theo gradient cua eigen energy + The change of the momentum under electric field F in the x-direction is dkx = [(-e*F)/hbar]*tau + The new position is obtained from x(at t+tau)=x(at t)+(hbar/2m*)*[kx(at t)+kx(at t+tau)]*tau = x(at t)+(hbar/m*)*[kx(at t)+0.5*dkx]*tau + NOTE: For spherical non-parabolic conduction band E(1+alpha*E)=(hbar*hbar)*(k*k)/(2m*) =gamma(k) so the group velocity of electron (at x-direction) will be vg=(hbar/m*)*kx/sqrt[1+4*alpha*gamma(k)] that is why in the below code we have the parameter sq = sqrt[1+4*alpha*gamma(k)] Starting date: March 19, 2010 Latest update: March 20, 2010 ***************************************************************************** */ #include <math.h> #include <stdio.h> #include "constants.h" void drift(double tau){ // Goi cac ham void check_boundary(); int Get_iv(),Get_subb(); double Get_kx(),Get_ml(), Get_mt(), Get_nonparabolicity_factor(); double ***Get_eig(), Get_mesh_size_x(),Get_x_position(); void Set_electron_energy(double ener),Set_x_position(double position_in_x),Set_kx(double k_momen_x); //Cac bien local int v = Get_iv(); // v-th valley int i = Get_subb(); // i-th subband double kx = Get_kx(); //printf("\n Before kx=%le",kx); double ml = Get_ml(); double mt = Get_mt(); double af = Get_nonparabolicity_factor();// printf("\n af = %le", af);//xem da o dang 0.5/eV CHUA? double ***eig = Get_eig(); // Thuc hien // Tim hat dang o SECTION nao ? double mesh_size_x = Get_mesh_size_x(); double x_position = Get_x_position(); //printf("\n Before x position=%le",x_position); int s = (int)(round(x_position/mesh_size_x)); // s-th section // Ban dau KHONG cho HAT VUOT QUA vi tri cho phep int Get_nx0(),Get_nx1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; // int nx_max = Get_nx_max(); if(s < 0) { s = 0;} if(s > nx_max) {s = nx_max;} // Tinh electric field theo phuong x double Fx; if(s >= nx_max) { s = nx_max-1; } // Do eig ta chi co den gia tri la nx_max ma thoi Fx = (eig[s+1][v][i]-eig[s][v][i])/mesh_size_x;//KHONG nhan q de doi ra don vi chuan. Xem chu y 1 trang 113 // Cong thuc (2) page 112 // Tinh dkx double dkx; //dkx = -(q/hbar)*Fx*tau;// [don vi chuan] // cong thuc (1) trang 112 dkx = (q/hbar)*Fx*tau;// [don vi chuan] // cong thuc (1) trang 112 // Update energy double E_parab; // energy tinh theo parabolic switch (v) { case 1: // v=1: valley pair 1 thi m* la ml E_parab = (hbar*hbar)*(kx+dkx)*(kx+dkx)/(2.0*ml*m0); // [J] break; case 2: // v=2: valley pair 2 thi m* la mt E_parab = (hbar*hbar)*(kx+dkx)*(kx+dkx)/(2.0*mt*m0); // [J] break; case 3: // v=3: valley pair 3 thi m* la mt E_parab = (hbar*hbar)*(kx+dkx)*(kx+dkx)/(2.0*mt*m0); // [J] break; default: { printf("\n Case iv=9 was considered in emcd(). Wrong! CHECK dritf.c"); exit(1); } } // End of switch (v) // Chuyen E_parab tu [J] sang [eV] E_parab = E_parab/q; // [eV] double E_Nonparab; // energy tinh theo Non-parabolic: TA DUNG E_Nonparab = (sqrt(1+4.0*af*E_parab) -1.0) /(2.0*af); // [eV] Set_electron_energy(E_Nonparab);// [eV] // Update gia tri cho bien energy // Update position switch (v) { case 1: // v=1: valley pair 1 thi m* la ml x_position=x_position+hbar*tau*(kx+0.5*dkx)/((ml*m0)*sqrt(1+4.0*af*E_parab));//[m] break; case 2: // v=2: valley pair 2 thi m* la mt x_position=x_position+hbar*tau*(kx+0.5*dkx)/((mt*m0)*sqrt(1+4.0*af*E_parab));//[m] break; case 3: // v=3: valley pair 3 thi m* la mt x_position=x_position+hbar*tau*(kx+0.5*dkx)/((mt*m0)*sqrt(1+4.0*af*E_parab));//[m] break; default: printf("\n Case iv=9 was considered in emcd(). Wrong! CHECK dritf.c"); } // End of switch (v) Set_x_position(x_position);// [m] // Update gia tri cho bien x_position // Update momentum kx = kx +dkx; // [1/m] Set_kx(kx); // Update gia tri cho bien kx //printf("\n tau=%le dkx = %le",tau,dkx); //printf("\n section=%d Electric field Fx = %le",s, Fx); //printf("\n Energy=%le, x position=%le, kx=%le",E_Nonparab,x_position,kx); // Goi ham check_boundary() DE KIEM TRA dieu kien boundary check_boundary(); // Sau ham nay duoc gia tri iv MOI: Neu iv KHAC 9 thuc hien o day // Neu iv=9 xem o ham emcd() /* Chu thay y nghia cua doan nay int ix; int iv_update = Get_iv(); if (iv_update !=9){ // HAT DUOC DUNG do co iv KHAC 9 ix = (int)(x_position/mesh_size_x); if(ix > nx_max) { ix = nx_max; } if(ix < 0){ ix = 0; } }// End of if (iv_update !=9) */ return; } // End of void drift(double tau) /******************************************************************************* /* ***************************************************************************** + To check boundaries: => Source and drain regions Starting date: March 21, 2010 Latest update: March 21, 2010 *********************************************************************************/ void check_boundary(){ int Get_nx0(),Get_nx1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; double Get_x_position(),Get_mesh_size_x(); double x_position = Get_x_position(); // Lay VI TRI cua HAT double device_length=(double)(nx_max)*Get_mesh_size_x();// printf("\n device_length=%le",device_length);//Lay DO DAI cua Device // Thuc hien int iv_update,iss_out_update,idd_out_update; int Get_iss_out(),Get_idd_out(); void Set_iv(int valley_pair_index),Set_iss_out(int out_p),Set_idd_out(int out_p); // HAT co the OUT neu VUOT QUA GIOI HAN o S va D. luon la Side Contact cho MSMC if(x_position <= 0.0){// Absorption this particle o vung Source contact iv_update = 9; // ngu y rang HAT nay se bi LOAI Set_iv(iv_update);// Update gia tri ve valley index cho bien iv // 3 lenh sau day chi TUONG DUONG voi 1 lenh iss_out = iss_out + 1; neu su dung GLOBAL variable iss_out_update = Get_iss_out();//lay so luong hat iss_out DA CO iss_out_update = iss_out_update + 1;// Them 1 hat nua bi LOAI Set_iss_out(iss_out_update); // Update gia tri ve SO HAT bi LOAI cho bien iss_out //printf("\n Vuot qua Souce Contact iss_out_update=%d",iss_out_update); // return; // KHONG CAN thuc hien cac lenh sau nua NEU da thuc hien cac lenh tren } // End of if(x_position <= 0.0){ if(x_position >= device_length){// Absorption this particle o vung Drain contact iv_update = 9; Set_iv(iv_update); idd_out_update = Get_idd_out(); idd_out_update = idd_out_update + 1; Set_idd_out(idd_out_update); //printf("\n Vuot qua Drain Contact idd_out_update=%d",idd_out_update); }// End of if(x_position >= device_length) return; } <file_sep>#include <stdio.h> #include <time.h> #include <math.h> #include <stdlib.h> #include <string.h> #include "my_util.h" int imax(int a, int b) { if ( a > b ) return(a) ; else return(b) ; } int imin(int a, int b) { if ( a < b ) return(a) ; else return(b) ; } double dmax(double a, double b) { if ( a > b ) return(a) ; else return(b) ; } double dmin(double a, double b) { if ( a < b ) return(a) ; else return(b) ; } char *sword(len) int len ; /* Allocate an char vector with range [nl..nh].*/ { char *v; v=(char *) malloc((unsigned) len*sizeof(char)); if (!v) nrerror("allocation failure in svector()"); return v ; } char **svector(nrl,nrh,len) int nrl,nrh,len ; /*Allocate a char matrix with range [nrl..nrh][ncl..nch].*/ { int i; char **m; /*allocate pointers to rows.*/ m=(char **) malloc((unsigned) (nrh-nrl+1)*sizeof(char*)); if (!m) nrerror("allocation failure 1 in smatrix()"); m -= nrl; /*allocate rows and set pointers to them.*/ for (i=nrl;i<=nrh;i++) { m[i]=(char *) malloc((unsigned) len*sizeof(char)); if (!m[i]) nrerror("allocation failure 2 in smatrix()"); } /*return pointer to array of pointers to rows.*/ return m; } double **dmatrix_mpi(m0,m1,n0,n1) int m0,m1,n0,n1 ; { int i,M,N ; double *v1,**v2 ; M = m1-m0+1 ; N = n1-n0+1 ; v1 = (double *) malloc((unsigned)(M*N)*sizeof(double)) ; v1 -= n0 ; v2 = (double **) malloc((unsigned)M*sizeof(double*)) ; v2 -= m0 ; for ( i=m0 ; i<M+m0 ; i++ ) v2[i] = v1+(i-m0)*N ; return(v2) ; } double ***d3matrix_mpi(l0,l1,m0,m1,n0,n1) int l0,l1,m0,m1,n0,n1 ; { int i,L,M,N ; double *v1,**v2,***v3 ; L = (l1-l0+1) ; M = (m1-m0+1) ; N = (n1-n0+1) ; v1 = (double *) malloc((unsigned)(L*M*N)*sizeof(double)) ; v1 -= n0 ; v2 = (double **) malloc((unsigned)(L*M)*sizeof(double *)) ; v2 -= m0 ; for ( i=m0 ; i<L*M+m0 ; i++ ) v2[i] = v1+(i-m0)*N ; v3 = (double ***) malloc((unsigned)L*sizeof(double **)) ; v3 -= l0 ; for ( i=l0 ; i<L+l0 ; i++ ) v3[i] = v2+(i-l0)*M ; return(v3) ; } void free_sword(v) char *v ; /*Frees a int vector allocated by ivector().*/ { free((char*) v); } void free_svector(m,nrl,nrh) char **m; int nrl,nrh ; /*Frees a matrix allocated with svector.*/ { int i; for (i=nrh;i>=nrl;i--) free((char*) m[i]); free((char*) (m+nrl)); } void free_dmatrix_mpi(double **v, int m0, int m1, int n0, int n1) { free((char*)(v[m0]+n0)) ; free((char*)(v+m0)) ; } void copy_R3mtx(b,a,nx0,nx1,ny0,ny1,nz0,nz1) double ***a,***b ; int nx0,nx1,ny0,ny1,nz0,nz1 ; { int i,j,k ; for ( i=nx0 ; i<=nx1 ; i++ ) for ( j=ny0 ; j<=ny1 ; j++ ) for ( k=nz0 ; k<=nz1 ; k++ ) b[i][j][k] = a[i][j][k] ; } void report_error(error_text) char error_text[]; { void exit(); printf("%s\n",error_text); printf("...now exiting to system...\n"); exit(1); } int nint(x) double x ; { int nx ; nx = (int) x ; if ( x > 0.0 ) { if ( (x - nx) < 0.5 ) return(nx) ; else return(nx+1) ; } else { if ( (nx - x) < 0.5 ) return(nx) ; else return(nx-1) ; } } int ConvertBooleanCharToInt(char c) { if ( c=='y' ) return(1) ; else if ( c=='n' ) return(0) ; else report_error("Should be y or n") ; return 0 ; } int ConvertBooleanToInt(char *data) { if ( !strcmp(data,"yes") ) return(1) ; else return(0) ; } static int c1,c2 ; void get_time(s) char *s ; { clock_t clock() ; static int entry=0 ; c2 = clock() ; printf("%s = %lf\n",s,(c2-c1)/(double)CLOCKS_PER_SEC) ; fflush(stdout) ; c1 = c2 ; } void reset_time() { c1 = clock() ; } <file_sep>/* **************************************************************** Gia dinh la chia tren truc y deu la dy va chia tren truc z deu la dz INPUT: + ny, nz chinh la ny_max va nz_max: intervals tren truc y va z + dy, dz la step tren truc y va z. OUTPUT: + **trap_weights la mang 2 chieu chua gia tri trapezoidal_weights Xem cong thuc 1, trang 91, 92 quyen vo cua ta Starting date: March 05, 2010 Update: March 05, 2010 Latest update: May 07, 2010 de mapping voi 3D Poisson ****************************************************************** */ #include <stdio.h> void trapezoidal_weights(){ // Goi ham double **Get_trap_weights(); double Get_mesh_size_y(),Get_mesh_size_z(); int Get_nya(),Get_nyb(); // int Get_ny_max(), Get_nz_max(); int Get_nza(),Get_nzb(); // Bieb local double **trap_weights = Get_trap_weights(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); int nya = Get_nya(); // Hien nay ny_max=nyb-nya int nyb = Get_nyb(); //int ny_max = Get_ny_max(); int nza = Get_nza(); // nz_max=nzb-nza int nzb = Get_nzb(); //int nz_max = Get_nz_max(); // Thuc hien int ny_max=nyb-nya; int nz_max=nzb-nza; int i,j; double const_area = (mesh_size_y/1.0e-9)*(mesh_size_z/1.0e-9)/4.0; // Xem hang so phan dau cua cong thuc 2 trang 92 //do thuc te cong thuc (2) trang 92 la khong co don vi. Nen ta can chia cho 1.0e-9 <--Khong CO don vi //printf("\n const_area = %f",const_area); double weight; for(i=0; i<=ny_max; i++){// Do chay tu 0 nen da xet DUNG so DIEM CHIA (May 30, 2010) // printf("\n"); // for checking only for(j=0; j<=nz_max; j++){ // Xet 4 goc va 4 canh if (i==0){ // Canh thu nhat I if((j==0)||(j==nz_max)) { weight = 1.0;} else { weight = 2.0;} } else if(i==ny_max){// Canh thu hai II if((j==0)||(j==nz_max)) { weight = 1.0;} else { weight = 2.0;} } else if((j==0)&&((i!=0)||(i!=ny_max))) { weight = 2.0;} // canh thu ba III else if((j==nz_max)&&((i!=0)||(i!=ny_max))){ weight = 2.0;} // canh thu ba III else { // Interior weight = 4.0; } trap_weights[i][j] = weight; // Luu vao mang trap_weights, la mang weight cong thuc 1 trang 92 trap_weights[i][j] = const_area*trap_weights[i][j]; // dua hang so o cong thuc 2 vao trong //printf("\n trap_weights[%d][%d] = %le", i,j,trap_weights[i][j]); // printf(" %le",trap_weights[i][j]); }// End of for(j=0; j<=nz; j++) } // End of for(i=0; i<=ny; i++){ }// End of void trapezoidal_weights <file_sep>/* ***************************************************************************** To solve MSMC Starting date: Feb 8, 2010 Update: April 6, 2010 Latest update: May 14, 2010 ****************************************************************************** */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include "functions.h" #include "constants.h" #include "nanowire.h" #include "petscksp.h" main(int argc, char **argv) { //Buoc 1. Tinh thoi gian bat dau time_t time_start, time_finish; time_start = time(NULL);// Lay gio he thong //printf("The start time is %s\n",asctime(localtime(&time_start)));// xem o buoc 3 // Buoc 2. Initializa MPI MPI_Init(&argc,&argv);// Sau ham MPI_Init thi cac processor BAT DAU Lam viec SONG SONG // Buoc 3. Lay rank va size int myrank, mysize; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); MPI_Comm_size(MPI_COMM_WORLD,&mysize); double time_tic, time_toc; // thoi gian bat dau va ket thuc 1 chu trinh nao do FILE *logfile = fopen("logfile_MSMC.txt","w"); if(myrank ==0){ time_tic = MPI_Wtime(); // void logging(FILE *log,const char *fmt,...); printf("The start time is %s\n",asctime(localtime(&time_start))); } // Buoc 4.Phan chay cho TAT CA cac processor. Ta da check rat nhieu lan roi. Bang cach in ket qua khi rank khac 0 material_param(); device_structure(); read_voltages_input(); read_simulation_list(); read_scattering_save_list(); initial_variables();// Can khoi tao sau ham device_structure() va read_simulation_list(); // va truoc ham doping_potential_initialization(); Initialize(&argc,&argv); // for 3D Poisson . logfile_PoissonInput(); // For checking initial_potential_doping();// Can dat ham nay truoc ham source_drain_carrier_number() de co doping ma thoi. o day do chua set Vs,Vd,Vg nen no bang 0 source_drain_carrier_number(); if(myrank ==0){ logging(logfile,"\n Number of particles for Source and Drain contact"); logging(logfile,"\n nsource_side_carriers = %d",Get_nsource_side_carriers()); logging(logfile,"\n ndrain_side_carriers = %d",Get_ndrain_side_carriers()); printf("\n nsource_side_carriers = %d",Get_nsource_side_carriers()); printf("\n ndrain_side_carriers = %d",Get_ndrain_side_carriers()); } trapezoidal_weights();// tranh chay nhieu lan cho ham nay //save_results(); // Buoc 5. Open Current-Voltage files // Mo kieu nay co nghia o 1 node thoi FILE *f_IdVg, *f_IdVd; if(myrank ==0){ // Mo 2 file chua I-V tai 1 node thoi f_IdVg=fopen("IdVg.dat","a");// Mo ra de ghi de, vi co the se chay nhieu vong lap cho Drain va Gate voltage if(f_IdVg==NULL){printf("\n Cannot open file IdVg.dat");return 0;} fprintf(f_IdVg,"\n #V_drain_input_fixed V_gate_input Id \n"); f_IdVd=fopen("IdVd.dat","a"); if(f_IdVd==NULL){printf("\n Cannot open file IdVd.dat");return 0;} fprintf(f_IdVd,"\n #V_gate_input_fixed V_drain_input Id \n"); } if(myrank ==0){ time_toc = MPI_Wtime(); // void logging(FILE *log,const char *fmt,...); logging(logfile,"\n Time to initialize all functions before Applied Voltage Bias loop =%f [s]",time_toc - time_tic); logging(logfile,"\n ******************************************************************************* "); } // Buoc 6. // ************************* APPLIED VOLTAGE BIAS LOOP ************************* // Solve 1D Multi Subband MC, 2D Schrodinger and 3D Poisson self-consistently for each point Vd and Vg // Lay cac gia tri voltage tu Input file double Vg_start = Get_Vg_start(); double Vg_end = Get_Vg_end(); double Vg_step = Get_Vg_step(); double Vd_start = Get_Vd_start(); double Vd_end = Get_Vd_end(); double Vd_step = Get_Vd_step(); if(myrank ==0){ logging(logfile,"\n Vgate start = %f", Vg_start); logging(logfile,"\n Vgate end = %f", Vg_end ); logging(logfile,"\n Vgate step = %f", Vg_step); logging(logfile,"\n Vdrain start= %f", Vd_start); logging(logfile,"\n Vdrain end = %f", Vd_end); logging(logfile,"\n Vdrain step = %f", Vd_step); logging(logfile,"\n*********************************************************\n\n"); } double Id=0.0,cur_av=0.0,V_gate_input=0.0,V_drain_input=0.0; for(V_gate_input=Vg_start; V_gate_input<=Vg_end; V_gate_input=V_gate_input+Vg_step){ for(V_drain_input=Vd_start; V_drain_input<=Vd_end; V_drain_input=V_drain_input+Vd_step){ // Buoc 6.1. /* ************************************************************************************* Solve Poisson equation LAN DAU TIEN for electron initialization - Do initial state of the system cang gan steady state thi convergence cang nhanh -> Initial guess su dung 1 phuong phap co ve ADVANCE hon -> To achieve a smoother initial potential and electron density, which leads to faster convergence ************************************************************************************* */ SetDrainVoltage(0.0);// NOTE cho Vd=0.0 o day SetGateVoltage(V_gate_input);//printf("\n Vd=%f, Vgate_input=%f",GetDrainVoltage(),GetGateVoltage()); void SetPhi_Contact(); // o definefn.c. No dung ham void assign_built_in_potential(). Ta DA SUA ham nay mot ti roi SetPhi_Contact();//Tat ca cac node. Phai dat ham nay TRUOC ham guess_potential(), void set_initial_potential() Neu khong No chua co gia tri Vs va Vd nen =0 tat ca. void guess_potential();// Da them tham so vao ham guess_potential() de chay tot guess_potential(); //Tat ca cac node. void set_initial_potential();// Duoc Phi(i,j,k) cua GS //set_initial_potential();// Ta khong doc tu file pot.r nen NO SE la guess_potential(); Cai nay la tu GS neu no chuyen truc tiep vao Poisson luon void get_initial_charge_density_for_Poisson();// Tinh cho 1 node va distribute-> Tat ca cac node get_initial_charge_density_for_Poisson();// tinh duoc electron density lan dau tien no cung chinh la n3d lan dau tien //Co save cai charge dua vao Poisson lan dau tien khong ? //save_initial_charge_density_for_Poisson(); if ( myrank==0 ){ printf("\n Solving Poisson the first time to inilialize electrons"); } if (GetPoissonLinearized()) { SolvePoisson = solve_3d_poisson_linearized;} else { SolvePoisson = solve_3d_poisson;} (*SolvePoisson)();// Chon kieu gi o tren thi solve Poisson theo kieu do void mpi_gather_potential_at_node0();// Sau khi giai 3D Poisson xong thi can gather chu potential lai.RAT NOTE day. Vi potential ban dau dang rai rac mpi_gather_potential_at_node0(); // Neu chon Print_Midline_Potential(y/n) = y hoac print_output(); thi no da gather lai cho minh roi. void mpi_distribute_potential_from_node0();//RAT NOTE Sau ham mpi_gather_potential_at_node0() ta duoc 1 potential hoan hao va ta gui no den cac node khac mpi_distribute_potential_from_node0(myrank, mysize);// node = myrank, np = mysize electrons_initialization();// tu potential o Poisson_0 ta initialization cho electrons. Da kiem tra rang cac node da tao ra so electrons giong nhau if(myrank ==0){ logging(logfile,"\n For Equilibrium Vg =%f, Vd = %f",GetGateVoltage(),GetDrainVoltage()); logging(logfile,"\n Number of initialized particles using Equilibrium above = %d",count_used_particles()); logging(logfile,"\n Maximum number of electrons allowed (in constants.h) = %d", max_electron_number); printf("\n Number of particles in use = %d",count_used_particles()); } // Save parameters cua electron lan dau tien khong //char fn[100]; //sprintf(fn,"ElectronInitParameters-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //save_electron_parameters(fn); //char fnSubband[100], fnEnergy[100]; //sprintf(fnSubband,"ElectronInitDistributionSubbands-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //sprintf(fnEnergy,"ElectronInitDistributionEnergy-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //save_electron_distribution(fnSubband,fnEnergy); /*End of solving equilibrium Poisson equation for electron initialization */ /* ***************************************************************************** */ // Buoc 6.2. /* ************************************************************************************** For Non-Equilibrium case Apply all actual biases at the contacts *********************************************************************************** */ SetDrainVoltage(V_drain_input); // Vs=0.0; Vd=Vd_input SetGateVoltage(V_gate_input);// Vg=Vgate_input. Da set o tren roi if(myrank ==0){ logging(logfile,"\n"); logging(logfile,"\n Solving MSMC, Schrodinger and Poisson for the bias"); logging(logfile,"\n Source Voltage [V] = %3.3f", Get_V_source_input()); logging(logfile,"\n Drain Voltage [V] = %3.3f", GetDrainVoltage()); logging(logfile,"\n Gate Voltage [V] = %3.3f", GetGateVoltage()); printf("\n");// Dang in cho node dau tien printf("\n ****************************************************"); printf("\n Solving MSMC, Schrodinger and Poisson for the bias"); printf("\n Source Voltage [V] = %3.3f", Get_V_source_input()); printf("\n Drain Voltage [V] = %3.3f", GetDrainVoltage()); printf("\n Gate Voltage [V] = %3.3f", GetGateVoltage()); printf("\n ****************************************************\n"); } SetPhi_Contact();// Phai dat ham nay TRUOC ham guess_potential(), void set_initial_potential() Neu khong No chua co gia tri Vs va Vd nen =0 tat ca. guess_potential(); get_initial_charge_density_for_Poisson();// tinh duoc electron density lan dau tien no cung chinh la n3d lan dau tien //Co save cai charge dua vao Poisson lan dau tien khong ? //save_initial_charge_density_for_Poisson(); logfile_PoissonInput(); // For checking if (GetPoissonLinearized()) { SolvePoisson = solve_3d_poisson_linearized;} else { SolvePoisson = solve_3d_poisson;} (*SolvePoisson)();// Chon kieu gi o tren thi solve Poisson theo kieu do mpi_gather_potential_at_node0();// DU co print_output() thi van nen de no o dang tuong minh nhu the nay mpi_distribute_potential_from_node0(myrank, mysize);// node = myrank, np = mysize print_output(); if ( myrank==0 ){ printf("\n Solving 2D Schrodinger the first time"); } //Solved_2D_Schro_Parallel_for_MSMC(&argc, &argv);// Su dung parallel Solved_2D_Schro_for_MSMC();// Giai Schrodinger LAN DAU se goi ham get_potential(int s, int ny, int nz); /* //Save potential cai su dung de giai 2D Schrodinger char fn_x_FirstTime[100], fn_yz_FirstTime[100]; sprintf(fn_x_FirstTime,"potential_x_at_midpoint_yz_in2DSchrodingerFirstTime-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); sprintf(fn_yz_FirstTime,"potential_yz_at_midpoint_x_in2DSchrodingerFirstTime-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); save_potential_used_for_2D_Schrodinger(fn_x_FirstTime,fn_yz_FirstTime); //Save subband_energy cho lan dau tien. Neu o get_potential() cho Schrodinger lay pot=-Phi va show ket qua cung chi la -Phi thi TRUNG KHIT char fnsubbandFirstTime[100]; sprintf(fnsubbandFirstTime,"subbandFirstTime-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); save_subband_energy(fnsubbandFirstTime); */ //SAVE wave va eigen neu muon cho lan dau tien //int save_eig_wavefuntion = Get_save_eig_wavefuntion(); //char fneigenFirstTime[100], fnwaveFirstTime[100]; //sprintf(fneigenFirstTime,"eigenFirstTime-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //sprintf(fnwaveFirstTime,"waveFirstTime-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //int NumSections = Get_nx1(); //int s,v; //if ( myrank==0 ){ // if(save_eig_wavefuntion==1){//Save eigen function and wave function ? // for(v=1; v<=3; v++){// 3 valleys ////for(s=0; s<=NumSections;s++){// Tat ca cac sections // s=3; // save_eig_wave(s,v,fneigenFirstTime,fnwaveFirstTime);//neu de file dang "a" thi khi ve wave lai bi chong chap can chu y // } // } // } //}// End of if ( myrank==0 ) form_factor_calculation();// Tinh Form factor LAN DAU. // Tinh o TAT CA cac node // Co save form factor lan dau khong ? //char fnformfactorFirstTime[100]; //sprintf(fnformfactorFirstTime,"FormfactorFirstTime-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //int NumSections = Get_nx1(); //int FormfactoSavedAtsth = (int)(NumSections/2 +0.5);// lay o giua //save_form_factor_calculation(FormfactoSavedAtsth, fnformfactorFirstTime); scattering_table(); //LAN DAU // save_results(); // truoc khi normalized scattering // Tinh o TAT CA cac node // Save scattering lan dau tien khong ? //char fnscatFirstTime[100]; //sprintf(fnscatFirstTime,"ScatTableFirstTime-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //int NumSections = Get_nx1(); //int ScatSavedAtsth = (int)(NumSections/2 +0.5);// lay o giua //save_scattering_table(ScatSavedAtsth,fnscatFirstTime); normalize_table(); //LAN DAU // //save_results(); getchar();// La save sau khi normalize table. KHONG CO Y NGHIA GI cho scattering table ca // Tinh o TAT CA cac node //void save_normalized_table(); //save_normalized_table(); init_free_flight(); //LAN DAU // Tinh o TAT CA cac node multi_subbands_MC(logfile, &argc,&argv);// Vao MSMC o day // Save electron final parameter sau khi chay xong multi_subbands_MC() khong ? //void save_electron_parameters(char *fn);// Dat o dau thi save o day //char fnFinal[100]; //sprintf(fnFinal,"ElectronFinalParameters-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //save_electron_parameters(fnFinal); //void save_electron_distribution(char *fnSubband,char *fnEnergy); // char fnSubbandFinal[100], fnEnergyFinal[100]; //sprintf(fnSubbandFinal,"ElectronFinalDistributionSubbands-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //sprintf(fnEnergyFinal,"ElectronFinalDistributionEnergy-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //save_electron_distribution(fnSubbandFinal,fnEnergyFinal); current_calculation(&cur_av); // Tinh current cho cap (Vd va Vg) nay //if((V_drain_input >= 0)&&(cur_av < 0.0)) { cur_av = 0.0;}// (May 24 2010 <NAME> lenh nay voi de kiem tra xem the nao ) if(myrank ==0){ // ghi file I-V vao 1 node fprintf(f_IdVd,"%f %f %le \n",GetGateVoltage(),GetDrainVoltage(),cur_av); } if(myrank ==0){ logging(logfile,"\n The results for the bias:"); logging(logfile,"\n Vd (V) = %f", GetDrainVoltage()); logging(logfile,"\n Vg (V) = %f", GetGateVoltage()); logging(logfile,"\n Id (A) = %le\n",cur_av); printf("\n The results for the bias:"); printf("\n Vd (V) = %f", GetDrainVoltage()); printf("\n Vg (V) = %f", GetGateVoltage()); printf("\n Id (A) = %le\n",cur_av);// De dua ra micro A thi NHAN voi 1.0e+6 } // For checking //save_potential(0);// 0:xy, yz, xz;//save_potential(1);// 1:xyz save the nay la save cho tung cap Vd va Vg day //save_potential(2);// ve theo x only if(myrank ==0){ time_toc = MPI_Wtime(); // void logging(FILE *log,const char *fmt,...); //logging(logfile,"\n Vg =%f, Vd = %f",GetGateVoltage(),GetDrainVoltage()); //logging(logfile,"\n Time to run =%f [s]",time_toc - time_tic); double time_to_run = time_toc - time_tic; logging(logfile,"\n Time to simulate %d hours %d minutes %d seconds ", (int)(time_to_run/3600), (int)(((int)time_to_run%3600)/60), ((int)time_to_run%3600)%60); logging(logfile,"\n\n *****************************************************"); } }//End of Single bias for(V_drain_input=Vd_start;V_drain_input< n if(myrank ==0){ // ghi file I-V vao 1 node fprintf(f_IdVg,"%f %f %le \n",GetDrainVoltage(),GetGateVoltage(),cur_av); } }// END for ALL BIASES (Gate voltage bias) fclose(f_IdVd); fclose(f_IdVg); // Tinh thoi gian ket thuc chuong trinh time_finish=time(NULL); //printf("\n The finish time is %s",asctime(localtime(&time_finish))); double time_to_simulate = difftime(time_finish,time_start); if(myrank ==0){ printf("\n Time to simulate %d hours %d minutes %d seconds \n", (int)(time_to_simulate/3600), (int)(((int)time_to_simulate%3600)/60), ((int)time_to_simulate%3600)%60); printf("\n The end !"); logging(logfile,"\n The end !"); } fclose(logfile); return 0; } <file_sep>/* ***************************************************************************** + To calculate number of carriers in the source and drain regions based on doping (cua cac cell cuoi 2 dau mut ay). + Do la ohmic contact tai cac dau mut cua S va D nen ta co the xet no la charge neutrality cai luon luon in thermal equilibrium tham chi la khi current is flowing -> Keep number of particles la constant tai cac dau mut do. Starting date: Feb 17, 2010 Update: Feb 18, 2010 Update: March 29, 2010. TAI SAO lai thay doi cach luu tru tu ** thanh dang hang so + Vi thuc te la VI TRI cua particle chi phu thuoc vao x-direction. Nen cho du co UPDATE vi tri cua hat theo phuong y va z thi NO CUNG KHONG THAY DOI trong suot qua trinh simulate Update: May 03, 2010 (Mo rong ra vung Oxide de mapping voi 3D Poisson) Nhung so hat chi tinh o vung contact LOI Silicon Latest update: May 05, 2010 su dung phuong phap artificial_factor_of_cell_volume ****************************************************************************** */ #include <stdio.h> #include <stdlib.h> #include "constants.h" #include "nrutil.h" static int nsource_side_carriers,ndrain_side_carriers; void source_drain_carrier_number(){ // Goi cac ham double Get_artificial_factor_cell_volume(); double Get_mesh_size_x(), Get_mesh_size_y(), Get_mesh_size_z(); int Get_nya(),Get_nyb(),Get_nza(),Get_nzb(); double *Get_doping_density(); // Cac bien local double artificial_factor_cell_volume = Get_artificial_factor_cell_volume(); double mesh_size_x = Get_mesh_size_x(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); int nya = Get_nya(); int nyb = Get_nyb(); int nza = Get_nza(); int nzb = Get_nzb(); double *doping = Get_doping_density();//1,2 or 3 ->S,D or Channel // Khoi tao 2 bien ngoai nsource_side_carriers = 0; ndrain_side_carriers = 0; int n_number = 0;// So hat tai moi adjacent cell thu i day double cell_volume = 0.5*mesh_size_x*mesh_size_y*mesh_size_z; /* Fig 4.10, "Numerical Simulation of Submicron Semiconductor Devices" by Tomizawa */ // Tinh cho 1/2 cell ngay canh Source va Drain artificial_factor_cell_volume = artificial_factor_cell_volume/mesh_size_z; cell_volume = cell_volume*artificial_factor_cell_volume; double denn = 0.0,factor = 0.0; int j,k;// i // Ta xet SIDE CONTACT //i = nx0; // At the Source edge contact phan LOI Silicon for(j = nya; j<=nyb; j++){ for(k=nza; k<=nzb; k++){ denn = doping[1]; //real value of doping if((j==nya)||(j==nyb)||(k==nza)||(k==nzb)) { denn = 0.5*denn; //Left Topmost or Left Bottomost: 1/4 cell only } factor = denn*cell_volume;// printf("\n So hat thuc te = %le",factor); //Number of particles n_number = (int)(factor+0.5);// NOTE no luon rat nho so voi 1 NEU KHONG dung artificial_factor_cell_volumn //if(n_number<1){n_number = 1;}// printf("\n n_number = %d",n_number); nsource_side_carriers += n_number;// Used for check_source_drain_contacts() function } // End of for(k=nza; k<=nzb; k++){ } // End of for(j = nya; j<=nyb; j++){ //i = nx1; // At the Drain edge phan LOI Silicon for(j = nya; j<=nyb; j++){ for(k=nza; k<=nzb; k++){ denn = doping[2]; if((j==nya)||(j==nyb)||(k==nza)||(k==nzb)) { denn = 0.5*denn; //Right Topmost or Right Bottomost: 1/4 cell only } factor = denn*cell_volume; //printf("\n So hat thuc te = %le",factor); //Number of particles n_number = (int)(factor+0.5);// NOTE no luon rat nho so voi 1 //if(n_number<1){n_number = 1;}// printf("\n n_number = %d",n_number); ndrain_side_carriers += n_number;// Used for check_source_drain_contacts() function } // End of for(k=nza; k<=nzb; k++){ } // End of for(j = nya; j<=nyb; j++){ //printf("\n nsource_side_carriers = %d",nsource_side_carriers); //printf("\n ndrain_side_carriers = %d",ndrain_side_carriers); if((nsource_side_carriers==0)||(ndrain_side_carriers==0)){ printf("\n Report error at source_drain_carrier_number()"); system("pause"); } return; } /****** End of void source_drain_carrier_number() ****/ int Get_nsource_side_carriers(){ return (nsource_side_carriers); } int Get_ndrain_side_carriers(){ return (ndrain_side_carriers); } <file_sep>typedef struct { double r ; double i ; } doublecomplex ; doublecomplex *complex_dvector() ; doublecomplex **complex_dmatrix() ; doublecomplex ***complex_d3matrix() ; doublecomplex ***complex_d3matrix_mpi() ; void free_complex_dvector() ; void free_complex_dmatrix() ; void free_complex_d3matrix() ; doublecomplex Complex() ; doublecomplex Czero_() ; doublecomplex Cneg() ; doublecomplex Conj() ; doublecomplex Cadd() ; doublecomplex Csub() ; doublecomplex Cmul() ; doublecomplex Cdiv() ; doublecomplex RCmul() ; doublecomplex CRmul() ; doublecomplex CRdiv() ; doublecomplex RCadd() ; doublecomplex CRadd() ; doublecomplex Csqrt() ; double Re() ; double Cabs() ; double Cabs2() ; void Cmtx_mul() ; void CmtxCj_mul() ; void Cmtx_3mul() ; void CmtxCj_3mul() ; void RCmtx_mul() ; void CRmtx_mul() ; void RtimesCmtx() ; void set_null_Cmtx() ; void Cmtx_add() ; void RCmtx_add() ; void Cmtx_sub() ; void Adjoint_mtx() ; void copy_Cmtx() ; void print_Cmtx() ; void print_Cmtx_condensed() ; void Identity_Cmtx() ; void set_null_Cvec() ; #define ComplexZero Complex(0.0,0.0) <file_sep># Multi-subband-Monte-Carlo. It is my source code of Multi-subband Monte Carlo model for low field mobility calculation in Silicon Nanowire Transistor. The model is to solve 2D Poisson equation and 2D Schrodinger equation in the cross-sectional plane and coupled with 1D Boltzmann equation on the transport direction. All relevant scatterings are included in the model. The documentation (written in 2011) is as below link. [Multi-subband Monte Carlo](https://github.com/tuantla80/Multi-subband-Monte-Carlo/blob/master/Handbook%20for%20MSMS%20code.pdf) <file_sep>/* ***************************************************************************** Ensemble Monte Carlo (EMC) algorithm for a device. - based on the succesive and simultaneous motions of many particles during a small time increment dt - The function drift() and scattering() are used in EMC during dt for all particles. - t-------------t+dt ; ts: free-flight time is determined by a random number. + (1) if (ts>t+dt) means t---------(t+dt)-----ts -> the particle drifts during dt -> call drift(tau) where tau=(t+dt)-t + (2) if (ts<=t+dt) means t--------(ts)------t+dt-> the particle first drifts during (ts-t) and then scattered at ts -> call drift(tau=ts-t) and then scattering(). => Then generates a new scattering time ts (determined by another random number) and we check again ts is larger than t+dt or not -> comes to (1) or (2) -> continue to do so to the end of the simulation Starting date: March 17, 2010 Latest update: March 19, 2010 ***************************************************************************** */ #include <stdio.h> #include <math.h> void emcd(){ //Ensemble Monte Carlo for the Device // Goi cac ham double **Get_p(),*Get_energy(); // THAM SO cua HAT int *Get_valley(),*Get_subband();// THAM SO cua HAT int Get_n_used(); // so hat dang su dung double Get_mesh_size_x(); long Get_idum(); float random2(long *idum); double Get_dt(), *Get_max_gm(); // max_gm: Gamma_max cho tung SECTION int count_used_particles(); // Tinh SO HAT dang SU DUNG int Get_flag_ballistic_transport(); void Set_iss_out(int out_p),Set_iss_eli(int eli_p), Set_iss_cre(int cre_p); void Set_idd_out(int out_p),Set_idd_eli(int eli_p), Set_idd_cre(int cre_p); void Set_kx(double k_momen_x),Set_dtau(double flight_time),Set_x_position(double position_in_x); void Set_electron_energy(double ener),Set_iv(int valley_pair_index),Set_subb(int subband_index); double Get_kx(),Get_dtau(),Get_x_position(),Get_electron_energy(); int Get_iv(),Get_subb(); //void Set_particle_i_th( int i); //Set (Lay) thu tu hat dang simulate For checking void drift(double tau); void scattering(); // Cac bien local double **p = Get_p(); double *energy = Get_energy(); int *valley = Get_valley(); int *subband = Get_subband(); double mesh_size_x = Get_mesh_size_x(); long idum = Get_idum(); double dt = Get_dt();// Time step: observation time Ta TU DINH NGHIA doc tu Input.d double *max_gm = Get_max_gm(); int flag_ballistic_transport; // Thuc hien int i, iv_check; double dte=0.0,dt2=0.0,dte2=0.0,rr=0.0,dt3=0.0,dtp=0.0,tau=0.0; double x_update=0.0; // position update int s_update=0;// section update flag_ballistic_transport = Get_flag_ballistic_transport();//=1 la BALLISTIC // Reset the electron number Set_iss_out(0);// Nghia la iss_out = 0; Set_iss_eli(0); Set_iss_cre(0); Set_idd_out(0); Set_idd_eli(0); Set_idd_cre(0);//printf("\n idd_out=%d, idd_eli=%d, idd_cre=%d",Get_idd_out(),Get_idd_eli(),Get_idd_cre()); getchar(); int n_used = Get_n_used(); // int ne = count_used_particles(); // Tim so hat dang su dung la bao nhieu //printf("\n Truoc khi chay emcd thuc su n_used=%d, ne= %d",n_used,ne);getchar();// Confirm 2 kieu la giong nhau for(i=1; i<=n_used; i++){ // Calculate for each particle (loop for all used particles);//for(i=1; i<=10; i++){ // Thu cho 10 hat thoi // Inverse mapping of particle atributes Set_kx(p[i][1]); // kx = p[i][1] Set_x_position(p[i][2]); // x_position = p[i][2] Set_dtau(p[i][3]); // dtau = p[i][3] // i_region = p[n][4]: Hien tai khong dung tham so nay Set_iv(valley[i]); // iv = valley[i] Set_electron_energy(energy[i]);// electron_energy = energy[i] Set_subb(subband[i]); // subb= subband[i] // Checking iv Neu ==9 thi HAT nay bi LOAI khong can thuc hien nua iv_check = Get_iv(); if(iv_check==9) { goto L403;}// Bat dau 1 vong moi cua chu trinh ma khong thuc hien tiep cac lenh dang sau // BALLISTIC TRANSPORT or DIFFUSIVE TRANSPORT ? if( flag_ballistic_transport==1)//ballistic { drift(dt);// ballistic nen trong khoang thoi gian dt no chi drift thoi iv_check = Get_iv();// Do trong qua trinh Drift no CO THE THAY DOI iv if(iv_check==9) { goto L403;} goto L403; } // Neu khong thi no se la // DIFFUSIVE TRANSPORT case tau = Get_dtau(); //printf("\n Drift DAU TIEN of particle %d with drift time Tau= %le while dt=%le",i,tau,dt); getchar(); dte = tau; if(dte >= dt) { dt2=dt; } else{ // dte < dt dt2=dte; } // -> dt2 is a drift time drift(dt2); // Call drift() function during dt2 iv_check = Get_iv();// Do trong qua trinh Drift no CO THE THAY DOI iv if(iv_check==9) { goto L403;} while(dte <= dt){ // Free-flight and scatter part dte2 = dte; // Da xet drift o tren roi // Lay thu tu hat dang simulate ma se co scattering //Set_particle_i_th(i); // Hat thu i dang simulate se co scattering scattering(); // Goi ham scattering do { rr=random2(&idum); } while ((rr<=1.0e-6)||(rr>=1.0)); // Do no da drift 1 doan nen co the vi tri cua HAT da sang SECTION KHAC x_update = Get_x_position(); s_update = (int)(round(x_update/mesh_size_x)); dt3 = -log(rr)/max_gm[s_update]; // [s] dtp = dt - dte2; // remaining time to scatter in dt-interval if(dt3<=dtp) {dt2 = dt3;} else {dt2 = dtp;} drift(dt2); //printf("\n Drift SAU KHI goi scattering() of particle %d with drift time Tau= %le",i,dt2); iv_check = Get_iv();// Do trong qua trinh Drift no CO THE THAY DOI iv if(iv_check==9) { goto L403;} // Update times dte2 = dte2 + dt3; dte = dte2; } // End of the "while" loop // Meaning dte >= dt // after "while" loops dte = dte - dt; tau = dte; Set_dtau(tau); // tau la gia tri cho khoang thoi gian drift moi L403: /* Note: khong the dung lenh continue vi continue trong C/C++ va trong Fortran co mot vai diem khac nhau. - Trong C/C++ neu gap continue trong vong for thi no se quay tro lai vong lap for voi chi so ke tiep ma khong lam cac lenh sau do - Trong Fortran thi lenh continue la "chi dan rang" lam cac lenh dang sau continue Do do neu o day dung lenh continue thi no se khong lam cac lenh trong doan Map particle atributes -> cac gia tri iss_out, idd_eli, iss_cre, idd_out idd_eli, idd_cre se bang 0 het -> sai */ // Map particle atributes p[i][1] = Get_kx(); p[i][2] = Get_x_position(); p[i][3] = Get_dtau(); valley[i] = Get_iv(); energy[i] = Get_electron_energy(); subband[i] = Get_subb(); } // End of for(i=1; i<=n_used; i++){ // Calculate for each particle return; } // End of void emcd() <file_sep>#include "petscksp.h" #include "nanowire.h" void print_potential_plain(char *fn) { FILE *fout ; int i,j,k ; PoiNum N = GetPoiNum() ; double *X = GetPX() ; double *Y = GetPY() ; double *Z = GetPZ() ; double ***Phi = GetPot() ; void mpi_gather_potential_at_node0() ; mpi_gather_potential_at_node0() ; int node ; MPI_Comm_rank(PETSC_COMM_WORLD,&node) ; if ( node==0 ) { fout = fopen(fn,"w") ; fprintf(fout,"# %d %d %d\n",N.x,N.y,N.z) ; for ( i=N.x0 ; i<=N.x1 ; i++ ) fprintf(fout,"%le\n",X[i]) ; for ( j=N.y0 ; j<=N.y1 ; j++ ) fprintf(fout,"%le\n",Y[j]) ; for ( k=N.z0 ; k<=N.z1 ; k++ ) fprintf(fout,"%le\n",Z[k]) ; for ( i=0 ; i<N.x ; i++ ) for ( j=0 ; j<N.y ; j++ ) for ( k=0 ; k<N.z ; k++ ) fprintf(fout,"%le\n",-Phi[i][j][k]) ; fclose(fout) ; } } // Midline Potential void print_midline_potential_plain(char *fn) { int i ; FILE *fout ; PoiNum N = GetPoiNum() ; double *X = GetPX() ; double ***Phi = GetPot() ; int node ; MPI_Comm_rank(PETSC_COMM_WORLD,&node) ; void mpi_gather_potential_at_node0() ; mpi_gather_potential_at_node0() ; int yc = (N.y0+N.y1)/2 ; int zc = (N.z0+N.z1)/2 ; if ( node==0 ) { fout = fopen(fn,"w") ; fprintf(fout,"# %d %d %d\n",N.x,N.y,N.z) ; fprintf(fout,"# Vd = %lf Vg = %lf\n",GetDrainVoltage(),GetGateVoltage()) ; for ( i=0 ; i<N.x ; i++ ) fprintf(fout,"%le %le\n",X[i],-Phi[i][yc][zc]) ; fprintf(fout,"\n") ; fflush(fout) ; } } // MPI void mpi_gather_potential_at_node0() { int node,np ; int trans_size = GetTransSize() ; MPI_Status status ; MPI_Comm_rank(PETSC_COMM_WORLD,&node) ; MPI_Comm_size(PETSC_COMM_WORLD,&np) ; double ***Pot = GetPot() ; PoiNum N = GetPoiNum() ; int x0 = GetPx0() ; int y0 = N.y0-1 ; int y1 = N.y1+1 ; int z0 = N.z0-1 ; int z1 = N.z1+1 ; int n, n0, n1, data_size, ntrans, sum_transmitted, source, p0, tag ; void GetLocalN() ; if ( node>0 ) { GetLocalN(node,&n0,&n1) ; n0 += x0 - 1 ; n1 += x0 - 1 ; data_size = (n1-n0+1)*(y1-y0+1)*(z1-z0+1) ; ntrans = data_size/trans_size ; sum_transmitted = 0 ; p0 = 0 ; tag = 0 ; for ( n=1 ; n<=ntrans ; n++ ) { MPI_Send(&Pot[n0][y0][z0]+p0, trans_size, MPI_DOUBLE, 0, ++tag, PETSC_COMM_WORLD) ; p0 += trans_size ; sum_transmitted += trans_size ; } if ( sum_transmitted < data_size ) MPI_Send(&Pot[n0][y0][z0]+p0, data_size-sum_transmitted, MPI_DOUBLE, 0, ++tag, PETSC_COMM_WORLD) ; } else { for ( source=1 ; source<np ; source++ ) { GetLocalN(source,&n0,&n1) ; n0 += x0 - 1 ; n1 += x0 - 1 ; data_size = (n1-n0+1)*(y1-y0+1)*(z1-z0+1) ; ntrans = data_size/trans_size ; sum_transmitted = 0 ; p0 = 0 ; tag = 0 ; for ( n=1 ; n<=ntrans ; n++ ) { MPI_Recv(&Pot[n0][y0][z0]+p0, trans_size, MPI_DOUBLE, source, ++tag, PETSC_COMM_WORLD, &status) ; p0 += trans_size ; sum_transmitted += trans_size ; } if ( sum_transmitted < data_size ) MPI_Recv(&Pot[n0][y0][z0]+p0, data_size-sum_transmitted, MPI_DOUBLE, source, ++tag, PETSC_COMM_WORLD, &status) ; } } } <file_sep>void SetPRINT_MidPotFlag(); void SetPRINT_Pot3dFlag(); int GetPRINT_MidPotFlag(); int GetPRINT_Pot3dFlag(); <file_sep>#include "nrutil.h" #include "petscksp.h" #include "nanowire.h" static PoiNum N ; static PoiMem M ; static PoiParam CP ; static Region R ; PoiNum *PGetPoiNum() { return(&N) ; } PoiNum GetPoiNum() { return(N) ; } PoiMem *PGetPoiMem() { return(&M) ; } PoiParam *PGetPoiParam() { return(&CP) ; } PoiParam GetPoiParam() { return(CP) ; } Region *PGetR_() { return(&R) ; } Region GetR_() { return(R) ; } double ***GetPot() { return(M.Phi) ; } double ***GetPhiKth() { return(M.phi) ; } double *GetPX() { return(M.X) ; } double *GetPY() { return(M.Y) ; } double *GetPZ() { return(M.Z) ; } double *GetHx() { return(M.hx) ; } double *GetHy() { return(M.hy) ; } double *GetHz() { return(M.hz) ; } int GetPx0() { return(N.x0) ; } int GetPx1() { return(N.x1) ; } int GetPy0() { return(N.y0) ; } int GetPy1() { return(N.y1) ; } int GetPz0() { return(N.z0) ; } int GetPz1() { return(N.z1) ; } int GetPya() { return(N.ya) ; } int GetPyb() { return(N.yb) ; } int GetPza() { return(N.za) ; } int GetPzb() { return(N.zb) ; } double ***GetN3d() { return(M.n3d) ; } double ***GetP3d() { return(M.p3d) ; } static int *n0s,*n1s ; void SetLocalN(int np, int *I0s, int *I1s) { int i ; int x0 = GetPx0() ; n0s = ivector(0,np-1) ; n1s = ivector(0,np-1) ; for ( i=0 ; i<np ; i++ ) { n0s[i] = I0s[i] - x0 + 1 ; n1s[i] = I1s[i] - x0 + 1 ; } } void GetLocalN(int node,int *n0, int *n1) { *n0 = n0s[node] ; *n1 = n1s[node] ; } PCType GetPCType() { if ( !strcmp(CP.pctype,"Jacobi") ) return(PCJACOBI) ; else if ( !strcmp(CP.pctype,"Block_Jacobi") ) return(PCBJACOBI) ; else if ( !strcmp(CP.pctype,"SOR") ) return(PCSOR) ; else if ( !strcmp(CP.pctype,"SOR_Eis") ) return(PCEISENSTAT) ; else if ( !strcmp(CP.pctype,"ICC") ) return(PCICC) ; else if ( !strcmp(CP.pctype,"ILU") ) return(PCILU) ; else if ( !strcmp(CP.pctype,"ASM") ) return(PCASM) ; else if ( !strcmp(CP.pctype,"LinearSolv") ) return(PCKSP) ; else if ( !strcmp(CP.pctype,"Combinations") ) return(PCCOMPOSITE) ; else { report_error("PCType Pattern Does Not Match...") ; return(PCBJACOBI) ; } } KSPType GetKSPType() { if ( !strcmp(CP.ksptype,"Richardson") ) return(KSPRICHARDSON) ; else if ( !strcmp(CP.ksptype,"Chebychev") ) return(KSPCHEBYCHEV) ; else if ( !strcmp(CP.ksptype,"CG") ) return(KSPCG) ; else if ( !strcmp(CP.ksptype,"BiCG") ) return(KSPBICG) ; else if ( !strcmp(CP.ksptype,"GMRES") ) return(KSPGMRES) ; else if ( !strcmp(CP.ksptype,"BiCGSTAB") ) return(KSPBCGS) ; else if ( !strcmp(CP.ksptype,"CGS") ) return(KSPCGS) ; else if ( !strcmp(CP.ksptype,"QMR1") ) return(KSPTFQMR) ; else if ( !strcmp(CP.ksptype,"QMR2") ) return(KSPTCQMR) ; else if ( !strcmp(CP.ksptype,"CR") ) return(KSPCR) ; else if ( !strcmp(CP.ksptype,"LSQR") ) return(KSPLSQR) ; else if ( !strcmp(CP.ksptype,"PreOnly") ) return(KSPPREONLY) ; else { report_error("KSPType Pattern Does Not Match...") ; return(KSPGMRES) ; } } <file_sep>/* *********************************************************************** To initialize free flight time for each electron dua vao tham so x-direction cua hat thi se biet no o SECTION nao -> Su dung max_gm[s] tai SECTION do Matrix p[][] (parameters for particle) p[n][1] = kx (is stored kx) p[n][2] = x p[n][3] = is to store ts (ts or tc is free flight time) p[n][4] = i_region (which region we are considering?) NOTE: Phai dat ham nay SAU ham normalize_table() Starting date: March 17, 2010 Update: March 17, 2010 Latest update: May 19, 2010 ************************************************************************** */ #include <math.h> #include <stdio.h> #include "mpi.h" #include "constants.h" void init_free_flight(){ // Goi cac ham double **Get_p(); // THAM SO cua HAT double *Get_max_gm(); // Gamma_max cho tung SECTION int count_used_particles(); // Tinh SO HAT dang SU DUNG double Get_mesh_size_x(); long Get_idum(); float random2(long *idum); // Cac bien local long idum = Get_idum(); double **p = Get_p(); double *max_gm = Get_max_gm(); // printf("\n Maximum scatering rate at 0 section is %le",max_gm[0]); int ne = count_used_particles(); double mesh_size_x = Get_mesh_size_x(); // Thuc hien //printf("\n Number of electrons using before init_free_flight() = %d ",ne); getchar(); int i,s; // s la chi so cho SECTION double x_position; for(i=1;i<=ne;i++){ // Calculate for each particle x_position = p[i][2]; // lay POSITION cua HAT // Tim duoc vi tri SECTION cua HAT s = (int)(round(x_position/mesh_size_x)); //printf("\n Hat thu %d co vi tri SECTION %d",i,s); getchar(); // Tinh free-flight time cho HAT o SECTION s-th p[i][3] = -log(random2(&idum))/max_gm[s]; // [s] //printf("\n Free-flight time la %le[s] cho HAT tai SECTION %d",p[i][3],s); getchar(); } // Phan save vao file int myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); int Get_save_init_free_flight(); int save_init_free_flight_or_not = Get_save_init_free_flight(); FILE *f; if(myrank ==0){ if(save_init_free_flight_or_not==1){ // Co save f = fopen("init_free_flight.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL){printf("\n Cannot open file init_free_flight.dat"); return ; } fprintf(f,"\n #particle_i_th InSection free_flight_time \n"); for(i=1;i<=ne;i++){ x_position = p[i][2]; // lay POSITION cua HAT s = (int)(round(x_position/mesh_size_x)); fprintf(f," %d %d %le\n",i,s,p[i][3]); } fclose(f); } } return; } // End of void init_free_flight() <file_sep>#include "nrutil.h" #include "nanowire.h" #include "petscksp.h" void initialize_general_constants() { //printf("\n\n At initialize_general_constants()"); Param *P = PGetParam() ; Energy *E = PGetEnergy() ; P->e_si *= e_0 ; //printf("\n Dielectric of Si (exact value)P->e_si = %le",P->e_si); P->e_ox *= e_0 ; //printf("\n Dielectric of Oxide (exact value)P->e_ox = %le",P->e_ox); E->kT = kB*(P->Temp)/q0 ; //printf("\n Thermal energy E->kT = %f", E->kT); E->c_si = 0.5*E->g_si ; //printf("\n Conduction band of Si E->c_si = %f",E->c_si); E->c_ox = 0.5*E->g_ox ; //printf("\n Conduction band of Oxide E->c_ox = %f",E->c_ox); } #define TINY 1.0e-10 void set_position_x_direction() { //printf("\n\n At set_position_x_direction()"); double x1,x2,x3,hx1,hx2,hx3,x,*X,*hx ; int k,K,N1,N2,N3,Nx ; Dimen D ; PoiNum *N ; PoiMem *M ; Param P ; void divide_region() ; void SetHamilNx() ; D = GetDimen() ; N = PGetPoiNum() ; M = PGetPoiMem() ; P = GetParam() ; x1 = D.Lsrc ; x2 = x1 + D.Lchannel ; x3 = x2 + D.Lsrc ; N1 = N->Mx_src ; N2 = N->Mx_channel ; N3 = N->Mx_src ; Nx = N1+N2+N3+1 ; X = M->X = dvector(0,Nx-1) ; hx = M->hx = dvector(-1,Nx-2) ; N->x0 = 0 ; N->xa = N->x0+N1 ; N->xb = N->xa+N2 ; N->x1 = N->xb+N3 ; N->x = Nx ; //printf("\n N->x0 =%d, N->xa =%d, N->xb =%d, N->x1 =%d, N->x =%d",N->x0,N->xa,N->xb,N->x1,N->x); hx1 = x1/(double)N1 ; hx2 = (x2-x1)/(double)N2 ; hx3 = (x3-x2)/(double)N3 ; //printf("\n hx1 = %f, hx2 = %f, hx3 = %f",hx1,hx2,hx3); X[0] = x = 0.0 ; K = 1 ; divide_region(hx1,x1,X,&K,&x) ; divide_region(hx2,x2,X,&K,&x) ; divide_region(hx3,x3,X,&K,&x) ; for ( k=1 ; k<Nx ; k++ ) hx[k-1] = X[k]-X[k-1] ; hx[-1] = hx[0] ; // Gate for ( k=1 ; k<Nx ; k++ ) if ( X[k] > 0.5*(x3-D.Lgate)-TINY ) break ; N->xgate0 = k ; for ( k=1 ; k<Nx ; k++ ) if ( X[k] > 0.5*(x3+D.Lgate)+TINY ) break ; N->xgate1 = k-1 ; } void set_position_y_direction() { //printf("\n\n At set_position_y_direction()"); double y1,y2,y3,hy1,hy2,hy3,y,*Y,*hy ; int k,K,N1,N2,N3,Ny ; Dimen D = GetDimen() ; Dimen *PD = PGetDimen() ; Param P = GetParam() ; PoiNum *N = PGetPoiNum() ; PoiMem *M = PGetPoiMem() ; void divide_region() ; double dev_len_y = 2*D.Wox + D.Wsi ; double dev_len_z = D.Tox + D.Tsi + D.Tbox ; y1 = D.Wox ; y2 = y1 + D.Wsi ; y3 = y2 + D.Wox ; N1 = N->My_ox ; N2 = N->My_si ; N3 = N->My_ox ; Ny = N1+N2+N3+1 ; Y = M->Y = dvector(0,Ny-1) ; hy = M->hy = dvector(-1,Ny-2) ; N->y0 = 0 ; N->ya = N->y0+N1 ; N->yb = N->ya+N2 ; N->y1 = N->yb+N3 ; N->y = Ny ; //printf("\n N->y0 =%d, N->ya =%d, N->yb =%d, N->y1 =%d, N->y =%d",N->y0,N->ya,N->yb,N->y1,N->y); hy1 = y1/(double)N1 ; hy2 = (y2-y1)/(double)N2 ; hy3 = (y3-y2)/(double)N3 ; //printf("\n hy1 = %f, hy2 = %f, hy3 = %f",hy1,hy2,hy3); Y[0] = y = 0.0 ; K = 1 ; divide_region(hy1,y1,Y,&K,&y) ; divide_region(hy2,y2,Y,&K,&y) ; divide_region(hy3,y3,Y,&K,&y) ; for ( k=1 ; k<Ny ; k++ ) hy[k-1] = Y[k]-Y[k-1] ; // Determine the location of the gate extended in the y direction for ( k=1 ; k<Ny ; k++ ) if ( fabs(Y[k]-D.Wgate)<0.1*hy[k] ) break ; N->ygate0 = k ; N->ygate1 = N->y0+N->y1-N->ygate0 ; } void set_position_z_direction() { //printf("\n\n At set_position_z_direction()"); double z1,z2,z3,hz1,hz2,hz3,z,R1,R2,*Z,*hz ; int k,K,N1,N2,N3,Nz ; Dimen D ; PoiNum *N ; PoiMem *M ; void divide_region() ; D = GetDimen() ; N = PGetPoiNum() ; M = PGetPoiMem() ; z1 = D.Tox ; z2 = z1 + D.Tsi ; z3 = z2 + D.Tbox ; N1 = N->Mz_ox ; N2 = N->Mz_si ; N3 = N->Mz_box ; Nz = N1+N2+N3+1 ; Z = M->Z = dvector(0,Nz-1) ; hz = M->hz = dvector(-1,Nz-2) ; N->z0 = 0 ; N->za = N->z0+N1 ; N->zb = N->za+N2 ; N->z1 = N->zb+N3 ; N->z = Nz ; //printf("\n N->z0 =%d, N->za =%d, N->zb =%d, N->z1 =%d, N->z =%d",N->z0,N->za,N->zb,N->z1,N->z); hz1 = z1/(double)N1 ; hz2 = (z2-z1)/(double)N2 ; hz3 = (z3-z2)/(double)N3 ; //printf("\n hz1 = %f, hz2 = %f, hz3 = %f",hz1,hz2,hz3); Z[0] = z = 0.0 ; K = 1 ; divide_region(hz1,z1,Z,&K,&z) ; divide_region(hz2,z2,Z,&K,&z) ; divide_region(hz3,z3,Z,&K,&z) ; for ( k=1 ; k<Nz ; k++ ) hz[k-1] = Z[k]-Z[k-1] ; // Determine the location of the gate extended in the z direction for ( k=1 ; k<Nz ; k++ ) if ( Z[k] > D.Tgate+TINY ) break ; N->zgate = k-1 ; } void set_regions() { int count ; Region *R ; R = PGetR_() ; count = 0 ; R->_CHANNEL_SILICON = ++count ; R->_JUNCTION_SILICON = ++count ; R->_OXIDE = ++count ; R->_SOURCE_CONTACT = ++count ; R->_DRAIN_CONTACT = ++count ; R->_GATE_CONTACT = ++count ; R->_SOURCE_WALL = ++count ; R->_DRAIN_WALL = ++count ; R->_LEFT_WALL = ++count ; R->_RIGHT_WALL = ++count ; R->_TOP_WALL = ++count ; R->_BOTT_WALL = ++count ; R->_LEFT_INTERFACE = ++count ; R->_RIGHT_INTERFACE = ++count ; R->_TOP_INTERFACE = ++count ; R->_BOTT_INTERFACE = ++count ; R->_CORNERS = ++count ; } #define DIV_REG_EPS 1.0e-09 void divide_region(h,xlimit,Pos,K,xv) int *K ; double h,xlimit,*xv,*Pos ; { int k,k0 ; double x ; x = *xv ; k0 = *K ; for ( k=k0 ; ; k++ ) { x += h ; if ( x < xlimit*(1.0+DIV_REG_EPS) ) Pos[k] = x ; else break ; } x -= h ; *K = k ; *xv = x ; } #undef DIV_REG_EPS <file_sep>#if defined(__STDC__) || defined(ANSI) || defined(NRANSI) /* ANSI */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #define NR_END 1 #define FREE_ARG char* #define FSLIOERR(x) { fprintf(stderr,"Error:: %s\n",(x)); fflush(stderr); exit(EXIT_FAILURE); }//8-Dec.2009 for d4matrix void nrerror(char error_text[]) /* Numerical Recipes standard error handler */ { fprintf(stderr," run-time error...\n"); fprintf(stderr,"%s\n",error_text); fprintf(stderr,"...now exiting to system...\n"); exit(1); } float *vector(long nl, long nh) /* allocate a float vector with subscript range v[nl..nh] */ { float *v; v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float))); if (!v) nrerror("allocation failure in vector()"); return v-nl+NR_END; } int *ivector(long nl, long nh) /* allocate an int vector with subscript range v[nl..nh] */ { int *v; v=(int *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(int))); if (!v) nrerror("allocation failure in ivector()"); return v-nl+NR_END; } unsigned char *cvector(long nl, long nh) /* allocate an unsigned char vector with subscript range v[nl..nh] */ { unsigned char *v; v=(unsigned char *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(unsigned char))); if (!v) nrerror("allocation failure in cvector()"); return v-nl+NR_END; } unsigned long *lvector(long nl, long nh) /* allocate an unsigned long vector with subscript range v[nl..nh] */ { unsigned long *v; v=(unsigned long *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(long))); if (!v) nrerror("allocation failure in lvector()"); return v-nl+NR_END; } double *dvector(long nl, long nh) /* allocate a double vector with subscript range v[nl..nh] */ { double *v; v=(double *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(double))); if (!v) nrerror("allocation failure in dvector()"); return v-nl+NR_END; } float **matrix(long nrl, long nrh, long ncl, long nch) /* allocate a float matrix with subscript range m[nrl..nrh][ncl..nch] */ { long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; float **m; /* allocate pointers to rows */ m=(float **) malloc((size_t)((nrow+NR_END)*sizeof(float*))); if (!m) nrerror("allocation failure 1 in matrix()"); m += NR_END; m -= nrl; /* allocate rows and set pointers to them */ m[nrl]=(float *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(float))); if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); m[nrl] += NR_END; m[nrl] -= ncl; for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; /* return pointer to array of pointers to rows */ return m; } double **dmatrix(long nrl, long nrh, long ncl, long nch) /* allocate a double matrix with subscript range m[nrl..nrh][ncl..nch] */ { long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; double **m; /* allocate pointers to rows */ m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*))); if (!m) nrerror("allocation failure 1 in matrix()"); m += NR_END; m -= nrl; /* allocate rows and set pointers to them */ m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double))); if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); m[nrl] += NR_END; m[nrl] -= ncl; for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; /* return pointer to array of pointers to rows */ return m; } int **imatrix(long nrl, long nrh, long ncl, long nch) /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ { long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; int **m; /* allocate pointers to rows */ m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); if (!m) nrerror("allocation failure 1 in matrix()"); m += NR_END; m -= nrl; /* allocate rows and set pointers to them */ m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); m[nrl] += NR_END; m[nrl] -= ncl; for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; /* return pointer to array of pointers to rows */ return m; } float **submatrix(float **a, long oldrl, long oldrh, long oldcl, long oldch, long newrl, long newcl) /* point a submatrix [newrl..][newcl..] to a[oldrl..oldrh][oldcl..oldch] */ { long i,j,nrow=oldrh-oldrl+1,ncol=oldcl-newcl; float **m; /* allocate array of pointers to rows */ m=(float **) malloc((size_t) ((nrow+NR_END)*sizeof(float*))); if (!m) nrerror("allocation failure in submatrix()"); m += NR_END; m -= newrl; /* set pointers to rows */ for(i=oldrl,j=newrl;i<=oldrh;i++,j++) m[j]=a[i]+ncol; /* return pointer to array of pointers to rows */ return m; } float **convert_matrix(float *a, long nrl, long nrh, long ncl, long nch) /* allocate a float matrix m[nrl..nrh][ncl..nch] that points to the matrix declared in the standard C manner as a[nrow][ncol], where nrow=nrh-nrl+1 and ncol=nch-ncl+1. The routine should be called with the address &a[0][0] as the first argument. */ { long i,j,nrow=nrh-nrl+1,ncol=nch-ncl+1; float **m; /* allocate pointers to rows */ m=(float **) malloc((size_t) ((nrow+NR_END)*sizeof(float*))); if (!m) nrerror("allocation failure in convert_matrix()"); m += NR_END; m -= nrl; /* set pointers to rows */ m[nrl]=a-ncl; for(i=1,j=nrl+1;i<nrow;i++,j++) m[j]=m[j-1]+ncol; /* return pointer to array of pointers to rows */ return m; } float ***f3tensor(long nrl, long nrh, long ncl, long nch, long ndl, long ndh) /* allocate a float 3tensor with range t[nrl..nrh][ncl..nch][ndl..ndh] */ { long i,j,nrow=nrh-nrl+1,ncol=nch-ncl+1,ndep=ndh-ndl+1; float ***t; /* allocate pointers to pointers to rows */ t=(float ***) malloc((size_t)((nrow+NR_END)*sizeof(float**))); if (!t) nrerror("allocation failure 1 in f3tensor()"); t += NR_END; t -= nrl; /* allocate pointers to rows and set pointers to them */ t[nrl]=(float **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(float*))); if (!t[nrl]) nrerror("allocation failure 2 in f3tensor()"); t[nrl] += NR_END; t[nrl] -= ncl; /* allocate rows and set pointers to them */ t[nrl][ncl]=(float *) malloc((size_t)((nrow*ncol*ndep+NR_END)*sizeof(float))); if (!t[nrl][ncl]) nrerror("allocation failure 3 in f3tensor()"); t[nrl][ncl] += NR_END; t[nrl][ncl] -= ndl; for(j=ncl+1;j<=nch;j++) t[nrl][j]=t[nrl][j-1]+ndep; for(i=nrl+1;i<=nrh;i++) { t[i]=t[i-1]+ncol; t[i][ncl]=t[i-1][ncl]+ncol*ndep; for(j=ncl+1;j<=nch;j++) t[i][j]=t[i][j-1]+ndep; } /* return pointer to array of pointers to rows */ return t; } double ***d3matrix(int nl,int nh,int nrl,int nrh,int ncl,int nch) { int i ; double ***m ; m = (double ***) malloc((unsigned)(nh-nl+1)*sizeof(double**)) ; if (!m) { printf("allocation failure 1 in d3matrix()"); exit(1); } m -= nl ; for ( i=nl ; i<=nh ; i++ ) m[i] = dmatrix(nrl,nrh,ncl,nch) ; return m ; } //30/03/10 16:41 Tuan made i3matrix int ***i3matrix(int nl,int nh,int nrl,int nrh,int ncl,int nch) { int i ; int ***m ; m = (int ***) malloc((unsigned)(nh-nl+1)*sizeof(int**)) ; if (!m) { printf("allocation failure 1 in i3matrix()"); exit(1); } m -= nl ; for ( i=nl ; i<=nh ; i++ ) m[i] = imatrix(nrl,nrh,ncl,nch) ; return m ; } /*n4matrix allocates space for a four dimensional matrix*/ double ****n4matrix(int nl,int nr,int ml,int mr, int kl,int kr,int jl,int jr) { int i,j,k; double ****m; m=(double ****) calloc((unsigned) (nr-nl+1),(unsigned) sizeof(double***)); if (!m) nrerror("allocation failure 1 in n4matrix"); m -= nl; for (i=nl; i<=nr; i++) { m[i]=(double ***) calloc((unsigned) (mr-ml+1),(unsigned) sizeof(double**)); if (!m[i]) nrerror("allocation failure 2 in n4matrix"); m[i] -= ml; for (j=ml; j<=mr;j++) { m[i][j]=(double **) calloc((unsigned) (kr-kl+1),(unsigned) sizeof(double*)); if (!m[i][j]) nrerror("allocation failure 3 in n4matrix"); m[i][j] -= kl; for(k=jl;k<=jr;k++) { m[i][j][k]=(double *) calloc((unsigned) (jr-jl+1),(unsigned) sizeof(double)); if (!m[i][j]) nrerror("allocation failure 4 in n4matrix"); m[i][j][k] -= jl; } } } return m; } /*free_n4matrix free allocated space for n4matrix*/ void free_n4matrix(double ****m, int nl,int nr,int ml,int mr,int kl,int kr,int jl,int jr) { int i,j,k; for (i=nl;i>=nr;i--) { for (j=ml;j>=mr;j--) { for (k=jl;k>=jr;k--) free((char *) (m[i][j][k]+jl)); free((char *) (m[i][j]+kl)); } free((char*) (m[i]+ml)); } free((char *) (m+nl)); } void free_vector(float *v, long nl, long nh) /* free a float vector allocated with vector() */ { free((FREE_ARG) (v+nl-NR_END)); } void free_ivector(int *v, long nl, long nh) /* free an int vector allocated with ivector() */ { free((FREE_ARG) (v+nl-NR_END)); } void free_cvector(unsigned char *v, long nl, long nh) /* free an unsigned char vector allocated with cvector() */ { free((FREE_ARG) (v+nl-NR_END)); } void free_lvector(unsigned long *v, long nl, long nh) /* free an unsigned long vector allocated with lvector() */ { free((FREE_ARG) (v+nl-NR_END)); } void free_dvector(double *v, long nl, long nh) /* free a double vector allocated with dvector() */ { free((FREE_ARG) (v+nl-NR_END)); } void free_matrix(float **m, long nrl, long nrh, long ncl, long nch) /* free a float matrix allocated by matrix() */ { free((FREE_ARG) (m[nrl]+ncl-NR_END)); free((FREE_ARG) (m+nrl-NR_END)); } void free_dmatrix(double **m, long nrl, long nrh, long ncl, long nch) /* free a double matrix allocated by dmatrix() */ { free((FREE_ARG) (m[nrl]+ncl-NR_END)); free((FREE_ARG) (m+nrl-NR_END)); } void free_imatrix(int **m, long nrl, long nrh, long ncl, long nch) /* free an int matrix allocated by imatrix() */ { free((FREE_ARG) (m[nrl]+ncl-NR_END)); free((FREE_ARG) (m+nrl-NR_END)); } void free_submatrix(float **b, long nrl, long nrh, long ncl, long nch) /* free a submatrix allocated by submatrix() */ { free((FREE_ARG) (b+nrl-NR_END)); } void free_convert_matrix(float **b, long nrl, long nrh, long ncl, long nch) /* free a matrix allocated by convert_matrix() */ { free((FREE_ARG) (b+nrl-NR_END)); } void free_f3tensor(float ***t, long nrl, long nrh, long ncl, long nch, long ndl, long ndh) /* free a float f3tensor allocated by f3tensor() */ { free((FREE_ARG) (t[nrl][ncl]+ndl-NR_END)); free((FREE_ARG) (t[nrl]+ncl-NR_END)); free((FREE_ARG) (t+nrl-NR_END)); } void free_d3matrix(double ***m ,int nl,int nh,int nrl,int nrh,int ncl,int nch) { int i ; for ( i=nh ; i>=nl ; i-- ) free_dmatrix(m[i],nrl,nrh,ncl,nch) ; free((char*)(m+nl)) ; } //30/03/10 16:44 Tuan made free_i3matrix void free_i3matrix(int ***m ,int nl,int nh,int nrl,int nrh,int ncl,int nch) { int i ; for ( i=nh ; i>=nl ; i-- ) free_imatrix(m[i],nrl,nrh,ncl,nch) ; free((char*)(m+nl)) ; } /* Cac ham minh tu lam (Feb 23 and 24, 2010 // Tuan made */ ///* Khong dung cach nay //d4matrix allocates space for a four dimensional matrix double ****d4matrix(int nl,int nh,int nrl,int nrh,int ncl,int nch,int nkl,int nkh) { int i; double ****m; m=(double ****) malloc((unsigned) (nh-nl+1)* sizeof(double***)); if (!m){ printf("allocation failure 1 in d4matrix()"); exit(1); } m -= nl; for (i=nl; i<=nh; i++) { m[i] = d3matrix(nrl,nrh,ncl,nch,nkl,nkh); } return m; } /*free_d4matrix free allocated space for ndmatrix*/ void free_d4matrix(double ****m,int nl,int nh,int nrl,int nrh,int ncl,int nch,int nkl,int nkh) { int i; for ( i=nh ; i>=nl ; i-- ){ free_d3matrix(m[i],nrl,nrh,ncl,nch,nkl,nkh); } free((char*)(m+nl)) ; } double *****d5matrix(int nl,int nh,int nrl,int nrh,int ncl,int nch,int nkl,int nkh,int nml,int nmh) { int i; double *****m; m=(double *****) malloc((unsigned) (nh-nl+1)* sizeof(double****)); if (!m){ printf("allocation failure 1 in d5matrix()"); exit(1); } m -= nl; for (i=nl; i<=nh; i++) { m[i] = d4matrix(nrl,nrh,ncl,nch,nkl,nkh,nml,nmh); } return m; } void free_d5matrix(double *****m,int nl,int nh,int nrl,int nrh,int ncl,int nch,int nkl,int nkh,int nml,int nmh) { int i; for ( i=nh ; i>=nl ; i-- ){ free_d4matrix(m[i],nrl,nrh,ncl,nch,nkl,nkh,nml,nmh); } free((char*)(m+nl)) ; } // Tuan included: March 08, 2010 double ******d6matrix(int nl,int nh,int nrl,int nrh,int ncl,int nch,int nkl,int nkh,int nml,int nmh,int nql, int nqh) { int i; double ******m; m=(double ******) malloc((unsigned) (nh-nl+1)* sizeof(double*****)); if (!m){ printf("allocation failure 1 in d6matrix()"); exit(1); } m -= nl; for (i=nl; i<=nh; i++) { m[i] = d5matrix(nrl,nrh,ncl,nch,nkl,nkh,nml,nmh,nql,nqh); } return m; } void free_d6matrix(double ******m,int nl,int nh,int nrl,int nrh,int ncl,int nch,int nkl,int nkh,int nml,int nmh,int nql, int nqh) { int i; for ( i=nh ; i>=nl ; i-- ){ free_d5matrix(m[i],nrl,nrh,ncl,nch,nkl,nkh,nml,nmh,nql,nqh); } free((char*)(m+nl)) ; } /**************************************************************** * FUNCTION: d5matrix -- dynamically allocate space in memory * * for a 5-dimensional matrix * * INPUTS: dem1 = the first dimension dem2 = the second dimension dem3 = the third dimension dem4 = the fourth dimension dem5 = the fifth dimension * OUTPUT: A = dem1 x dem2 x dem3 x dem4 x dem5 matrix Made by Tuan - 11-Jun-2008 *****************************************************************/ /* double *****d5matrix(int dem1,int dem2,int dem3,int dem4,int dem5) { int i, j, k,l; double *****A; A = (double *****) calloc(dem1, sizeof(double ****)); for (i =1; i <=dem1; i++) { A[i] = (double ****) calloc(dem2, sizeof(double ***)); for (j = 1; j <= dem2; j++){ A[i][j] = (double ***) calloc(dem3, sizeof(double **)); for(k=1;k<=dem3;k++){ A[i][j][k] = (double **) calloc(dem4, sizeof(double *)); for(l=1;l<=dem4;l++){ A[i][j][k][l] = (double *) calloc(dem5, sizeof(double )); }// End of for(l=1 }// End of for(k=1 } // End of for(j=1 } // End of for(i=1 return(A); } ///* end of function d5matrix */ //*/ // <NAME> (8 December 2009) /*************************************************************** * d4matrix ***************************************************************/ /*! \fn double ****d4matrix(int th, int zh, int yh, int xh) \brief allocate a 4D buffer, use 1 contiguous buffer for the data Array is indexed as buf[0..th][0..zh][0..yh][0..xh]. <br>To access all elements as a vector, use buf[0][0][0][i] where i can range from 0 to th*zh*yh*xh - 1. Adaptation of Numerical Recipes in C nrutil.c allocation routines. \param th slowest changing dimension \param zh 2nd slowest changing dimension \param yh 2nd fastest changing dimension \param xh fastest changing dimension \return Pointer to 4D double array */ /* double ****d4matrix(int th, int zh, int yh, int xh) { int j; int nvol = th+1; int nslice = zh+1; int nrow = yh+1; int ncol = xh+1; double ****t; ///** allocate pointers to vols t=(double ****) malloc((size_t)((nvol)*sizeof(double***))); if (!t) FSLIOERR("d4matrix: allocation failure"); //** allocate pointers to slices t[0]=(double ***) malloc((size_t)((nvol*nslice)*sizeof(double**))); if (!t[0]) FSLIOERR("d4matrix: allocation failure"); // /** allocate pointers for ydim t[0][0]=(double **) malloc((size_t)((nvol*nslice*nrow)*sizeof(double*))); if (!t[0][0]) FSLIOERR("d4matrix: allocation failure"); ///** allocate the data blob t[0][0][0]=(double *) malloc((size_t)((nvol*nslice*nrow*ncol)*sizeof(double))); if (!t[0][0][0]) FSLIOERR("d4matrix: allocation failure"); ///** point everything to the data blob for(j=1;j<nrow*nslice*nvol;j++) t[0][0][j]=t[0][0][j-1]+ncol; for(j=1;j<nslice*nvol;j++) t[0][j]=t[0][j-1]+nrow; for(j=1;j<nvol;j++) t[j]=t[j-1]+nslice; return t; } */ #else /* ANSI */ /* traditional - K&R */ #include <stdio.h> #define NR_END 1 #define FREE_ARG char* void nrerror(error_text) char error_text[]; /* Numerical Recipes standard error handler */ { void exit(); fprintf(stderr,"Numerical Recipes run-time error...\n"); fprintf(stderr,"%s\n",error_text); fprintf(stderr,"...now exiting to system...\n"); exit(1); } float *vector(nl,nh) long nh,nl; /* allocate a float vector with subscript range v[nl..nh] */ { float *v; v=(float *)malloc((unsigned int) ((nh-nl+1+NR_END)*sizeof(float))); if (!v) nrerror("allocation failure in vector()"); return v-nl+NR_END; } int *ivector(nl,nh) long nh,nl; /* allocate an int vector with subscript range v[nl..nh] */ { int *v; v=(int *)malloc((unsigned int) ((nh-nl+1+NR_END)*sizeof(int))); if (!v) nrerror("allocation failure in ivector()"); return v-nl+NR_END; } unsigned char *cvector(nl,nh) long nh,nl; /* allocate an unsigned char vector with subscript range v[nl..nh] */ { unsigned char *v; v=(unsigned char *)malloc((unsigned int) ((nh-nl+1+NR_END)*sizeof(unsigned char))); if (!v) nrerror("allocation failure in cvector()"); return v-nl+NR_END; } unsigned long *lvector(nl,nh) long nh,nl; /* allocate an unsigned long vector with subscript range v[nl..nh] */ { unsigned long *v; v=(unsigned long *)malloc((unsigned int) ((nh-nl+1+NR_END)*sizeof(long))); if (!v) nrerror("allocation failure in lvector()"); return v-nl+NR_END; } double *dvector(nl,nh) long nh,nl; /* allocate a double vector with subscript range v[nl..nh] */ { double *v; v=(double *)malloc((unsigned int) ((nh-nl+1+NR_END)*sizeof(double))); if (!v) nrerror("allocation failure in dvector()"); return v-nl+NR_END; } float **matrix(nrl,nrh,ncl,nch) long nch,ncl,nrh,nrl; /* allocate a float matrix with subscript range m[nrl..nrh][ncl..nch] */ { long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; float **m; /* allocate pointers to rows */ m=(float **) malloc((unsigned int)((nrow+NR_END)*sizeof(float*))); if (!m) nrerror("allocation failure 1 in matrix()"); m += NR_END; m -= nrl; /* allocate rows and set pointers to them */ m[nrl]=(float *) malloc((unsigned int)((nrow*ncol+NR_END)*sizeof(float))); if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); m[nrl] += NR_END; m[nrl] -= ncl; for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; /* return pointer to array of pointers to rows */ return m; } double **dmatrix(nrl,nrh,ncl,nch) long nch,ncl,nrh,nrl; /* allocate a double matrix with subscript range m[nrl..nrh][ncl..nch] */ { long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; double **m; /* allocate pointers to rows */ m=(double **) malloc((unsigned int)((nrow+NR_END)*sizeof(double*))); if (!m) nrerror("allocation failure 1 in matrix()"); m += NR_END; m -= nrl; /* allocate rows and set pointers to them */ m[nrl]=(double *) malloc((unsigned int)((nrow*ncol+NR_END)*sizeof(double))); if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); m[nrl] += NR_END; m[nrl] -= ncl; for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; /* return pointer to array of pointers to rows */ return m; } int **imatrix(nrl,nrh,ncl,nch) long nch,ncl,nrh,nrl; /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ { long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; int **m; /* allocate pointers to rows */ m=(int **) malloc((unsigned int)((nrow+NR_END)*sizeof(int*))); if (!m) nrerror("allocation failure 1 in matrix()"); m += NR_END; m -= nrl; /* allocate rows and set pointers to them */ m[nrl]=(int *) malloc((unsigned int)((nrow*ncol+NR_END)*sizeof(int))); if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); m[nrl] += NR_END; m[nrl] -= ncl; for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; /* return pointer to array of pointers to rows */ return m; } float **submatrix(a,oldrl,oldrh,oldcl,oldch,newrl,newcl) float **a; long newcl,newrl,oldch,oldcl,oldrh,oldrl; /* point a submatrix [newrl..][newcl..] to a[oldrl..oldrh][oldcl..oldch] */ { long i,j,nrow=oldrh-oldrl+1,ncol=oldcl-newcl; float **m; /* allocate array of pointers to rows */ m=(float **) malloc((unsigned int) ((nrow+NR_END)*sizeof(float*))); if (!m) nrerror("allocation failure in submatrix()"); m += NR_END; m -= newrl; /* set pointers to rows */ for(i=oldrl,j=newrl;i<=oldrh;i++,j++) m[j]=a[i]+ncol; /* return pointer to array of pointers to rows */ return m; } float **convert_matrix(a,nrl,nrh,ncl,nch) float *a; long nch,ncl,nrh,nrl; /* allocate a float matrix m[nrl..nrh][ncl..nch] that points to the matrix declared in the standard C manner as a[nrow][ncol], where nrow=nrh-nrl+1 and ncol=nch-ncl+1. The routine should be called with the address &a[0][0] as the first argument. */ { long i,j,nrow=nrh-nrl+1,ncol=nch-ncl+1; float **m; /* allocate pointers to rows */ m=(float **) malloc((unsigned int) ((nrow+NR_END)*sizeof(float*))); if (!m) nrerror("allocation failure in convert_matrix()"); m += NR_END; m -= nrl; /* set pointers to rows */ m[nrl]=a-ncl; for(i=1,j=nrl+1;i<nrow;i++,j++) m[j]=m[j-1]+ncol; /* return pointer to array of pointers to rows */ return m; } float ***f3tensor(nrl,nrh,ncl,nch,ndl,ndh) long nch,ncl,ndh,ndl,nrh,nrl; /* allocate a float 3tensor with range t[nrl..nrh][ncl..nch][ndl..ndh] */ { long i,j,nrow=nrh-nrl+1,ncol=nch-ncl+1,ndep=ndh-ndl+1; float ***t; /* allocate pointers to pointers to rows */ t=(float ***) malloc((unsigned int)((nrow+NR_END)*sizeof(float**))); if (!t) nrerror("allocation failure 1 in f3tensor()"); t += NR_END; t -= nrl; /* allocate pointers to rows and set pointers to them */ t[nrl]=(float **) malloc((unsigned int)((nrow*ncol+NR_END)*sizeof(float*))); if (!t[nrl]) nrerror("allocation failure 2 in f3tensor()"); t[nrl] += NR_END; t[nrl] -= ncl; /* allocate rows and set pointers to them */ t[nrl][ncl]=(float *) malloc((unsigned int)((nrow*ncol*ndep+NR_END)*sizeof(float))); if (!t[nrl][ncl]) nrerror("allocation failure 3 in f3tensor()"); t[nrl][ncl] += NR_END; t[nrl][ncl] -= ndl; for(j=ncl+1;j<=nch;j++) t[nrl][j]=t[nrl][j-1]+ndep; for(i=nrl+1;i<=nrh;i++) { t[i]=t[i-1]+ncol; t[i][ncl]=t[i-1][ncl]+ncol*ndep; for(j=ncl+1;j<=nch;j++) t[i][j]=t[i][j-1]+ndep; } /* return pointer to array of pointers to rows */ return t; } void free_vector(v,nl,nh) float *v; long nh,nl; /* free a float vector allocated with vector() */ { free((FREE_ARG) (v+nl-NR_END)); } void free_ivector(v,nl,nh) int *v; long nh,nl; /* free an int vector allocated with ivector() */ { free((FREE_ARG) (v+nl-NR_END)); } void free_cvector(v,nl,nh) long nh,nl; unsigned char *v; /* free an unsigned char vector allocated with cvector() */ { free((FREE_ARG) (v+nl-NR_END)); } void free_lvector(v,nl,nh) long nh,nl; unsigned long *v; /* free an unsigned long vector allocated with lvector() */ { free((FREE_ARG) (v+nl-NR_END)); } void free_dvector(v,nl,nh) double *v; long nh,nl; /* free a double vector allocated with dvector() */ { free((FREE_ARG) (v+nl-NR_END)); } void free_matrix(m,nrl,nrh,ncl,nch) float **m; long nch,ncl,nrh,nrl; /* free a float matrix allocated by matrix() */ { free((FREE_ARG) (m[nrl]+ncl-NR_END)); free((FREE_ARG) (m+nrl-NR_END)); } void free_dmatrix(m,nrl,nrh,ncl,nch) double **m; long nch,ncl,nrh,nrl; /* free a double matrix allocated by dmatrix() */ { free((FREE_ARG) (m[nrl]+ncl-NR_END)); free((FREE_ARG) (m+nrl-NR_END)); } void free_imatrix(m,nrl,nrh,ncl,nch) int **m; long nch,ncl,nrh,nrl; /* free an int matrix allocated by imatrix() */ { free((FREE_ARG) (m[nrl]+ncl-NR_END)); free((FREE_ARG) (m+nrl-NR_END)); } void free_submatrix(b,nrl,nrh,ncl,nch) float **b; long nch,ncl,nrh,nrl; /* free a submatrix allocated by submatrix() */ { free((FREE_ARG) (b+nrl-NR_END)); } void free_convert_matrix(b,nrl,nrh,ncl,nch) float **b; long nch,ncl,nrh,nrl; /* free a matrix allocated by convert_matrix() */ { free((FREE_ARG) (b+nrl-NR_END)); } void free_f3tensor(t,nrl,nrh,ncl,nch,ndl,ndh) float ***t; long nch,ncl,ndh,ndl,nrh,nrl; /* free a float f3tensor allocated by f3tensor() */ { free((FREE_ARG) (t[nrl][ncl]+ndl-NR_END)); free((FREE_ARG) (t[nrl]+ncl-NR_END)); free((FREE_ARG) (t+nrl-NR_END)); } #endif /* ANSI */ <file_sep>/* *********************************************************************** - To calculate the number of initial electrons - Co 2 cach + Cach 1: <NAME>. <NAME> CHE la TAO RA SO HAT RAT LON + Cach 2: neu guest potential ma ok thi se dung Initialises parameters for each particle (electron) - Initial electron energy - Initial position and momentum of electrons - Initial valley and subband where the particle is residing for the first time Starting date: Feb 19, 2010 Update: Feb 19, 2010 Update: May 05, 2010 (Giai 3D Poisson at equilibrium roi sau do moi khoi tao electron) Latest update: June 02, 2010: <NAME> ************************************************************************* */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "mpi.h" #include "petscksp.h" #include "nanowire.h" #include "region.h" #include "nrutil.h" #include "constants.h" // ******************* Cach 2: Dung khi guest potential la NGON *************** void electrons_initialization(){ // Goi cac ham void init_kspace(int ne,int i); void init_realspace(int ne,int i); void Set_n_used( int n); int Get_n_used(); int find_region(int i,int j,int k); double Get_artificial_factor_cell_volume(); double artificial_factor_cell_volume = Get_artificial_factor_cell_volume(); int Get_save_electron_initlization(); int save_electron_initlization_or_not = Get_save_electron_initlization(); double Get_mesh_size_x(), Get_mesh_size_y(), Get_mesh_size_z(); double mesh_size_x = Get_mesh_size_x(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); int Get_nx0(),Get_nxa(),Get_nxb(),Get_nx1(), Get_nya(),Get_nyb(),Get_nza(),Get_nzb(); int nx0 = Get_nx0(); int nxa = Get_nxa(); int nxb = Get_nxb(); int nx1 = Get_nx1(); int nya = Get_nya(); int nyb = Get_nyb(); int nza = Get_nza(); int nzb = Get_nzb(); double ***Phi = GetPot(); double Get_intrinsic_carrier_density(),Get_Vt(); double intrinsic_carrier_density = Get_intrinsic_carrier_density(); double Vt = Get_Vt(); int *Get_valley(); int *valley = Get_valley(); // Thuc hien int i,j,k; double cell_volume = mesh_size_x*mesh_size_y*mesh_size_z; //volume of a cell artificial_factor_cell_volume = artificial_factor_cell_volume/mesh_size_z;// Do ngay xua ta lay device width la 1.0e-6 m cell_volume = cell_volume*artificial_factor_cell_volume; // Neu khong thi cell_volume qua nho dan den so hat trong cell luon bang 0 int np_ijk = 0; // number of electrons in a cell(i,j,k) double denn = 0.0; int ne = 0; // Number of electrons which we initialize int myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); FILE *f; if(myrank ==0){ if(save_electron_initlization_or_not==1){ // Co save f = fopen("electron_init.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL){printf("\n Cannot open file electron_init.dat"); return ; } fprintf(f,"\n #i j k Electron_number \n"); } } double Fermihalf (double x); double Nc_Si = 3.22*1.0e+25;//[m3] // Tai room temperature Nc cua Silicon la 3.22e+19/cm3.Semiconductor Device Fundamental - F.Pierret (page 51) //Can GIONG VOI void get_initial_charge_density_for_Poisson() double Ni = Nc_Si; double GetDrainVoltage(); double Vd = GetDrainVoltage(); //printf("\n Vd = %f", Vd); getchar(); Energy *E; E= PGetEnergy(); int n =0; for(i=nx0; i<=nx1; i++){ for(j=nya; j<=nyb; j++){ // chi doan co the khoi tao thoi. Tuc la LOI Silicon for(k=nza; k<=nzb; k++){ n = find_region(i,j,k); if(n==1){ //S // Boltzmann statistics denn = Ni*exp((-Phi[i][j][k]+E->biS)/Vt);// vi tri toa de cua Phi va n3d la TUONG DUONG NHAU mac du Phi co trai rong index re 1 ti //Fermi-Dirac statistics //denn = Ni*Fermihalf((-Phi[i][j][k]+E->biS)/Vt); } else if (n==2){//D //Boltzmann statistics denn = Ni*exp((-Phi[i][j][k]+Vd+ E->biD)/Vt); //Fermi-Dirac statistics //n3d[i][j][k] = Ni*Fermihalf((-Phi[i][j][k]+Vd+ E->biD)/Vt); } else if (n==3){//Ch //Boltzmann statistics denn = Ni*exp((-Phi[i][j][k])/Vt); //Fermi-Dirac statistics //n3d[i][j][k] = Ni*Fermihalf((-Phi[i][j][k])/Vt); } if(i==nx0||i==nx1) { denn = denn/2.0; } // at the boundary the denn is only 1/2 if(j==nya||j==nyb) { denn = denn/2.0; } if(k==nza||k==nzb) { denn = denn/2.0; } np_ijk = (int)(denn*cell_volume+0.5); // number of electrons in a cell(i,j,k) // tai vi int(0.7)=0 nen ta CAN cong them 0.5 thi chinh xac hon if(myrank ==0){ if ((np_ijk >=1)&&(save_electron_initlization_or_not==1)){// thi save fprintf(f,"%d %d %d %d \n",i,j,k, np_ijk); } } if (np_ijk==0) { goto L20; } // comeback to the loops //else: np_ij is different 0 -> initialize the parameters for each particle (electron) while( np_ijk > 0){ ne = ne + 1; if(ne > max_electron_number) { printf("\n Number of initial electrons = %d",ne); printf("\n Problem at electrons_initialization.c"); printf("\n You can change max_electron_number in constants.h Xem denn o Tren \n"); nrerror("Number of particles exceed max_electron_number");//Dung ham thong bao loi trong nr.h } init_kspace(ne,i); //initial momentum and energy init_realspace(ne,i); // Initial position np_ijk = np_ijk - 1; }// End of while( np_ijk > 0) L20: continue; } // End of for(k=nza; k<=nzb; k++) }// End of for(j=nya; j<=nyb; j++){ }//End of for(i=nx0; i<=nx1; i++) Set_n_used(ne); // Tuong duong voi cau lenh int n_used = ne; int n_used = Get_n_used(); if(myrank ==0){ printf("\n Maximum number of electrons allowed = %d",max_electron_number); printf("\n Number of electrons initialized = %d",n_used); if (n_used < 5000){// initial co so hat nho hon 5,000 hat. Can them so hat printf("\n In electrons_initialization()"); printf("\n Need change something"); nrerror("Number of particles initialized quite small"); } } for(i=n_used+1; i<=max_electron_number; i++){ valley[i] = 9; // inactive these particles, nhung hat ma vuot ngoai gia tri n_used thi phai inactive } if(myrank ==0){ // close file da mo if(save_electron_initlization_or_not==1){ // Co save fclose(f); } } return; } // Cach 1 xem phan cuoi cua ham //*********************************************************************************************************** /* *********************************************************************** De save cac tham so cua electron de kiem tra Starting date: June 06, 2010 Latest update: June 06, 2010) NOTE: for checking only. Dat o dau thi kiem tra o day ************************************************************************* */ #include "mpi.h" void save_electron_parameters(char *fn){ int Get_n_used();// lay so hat dang su dung int n_used = Get_n_used(); double **Get_p(),*Get_energy(); int *Get_valley(),*Get_subband();// lay kx,x,ts, valley, subband va energy cua hat thu i double *energy = Get_energy(); double **p = Get_p(); int *valley = Get_valley(); int *subband = Get_subband(); int myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); int i; FILE *f; if(myrank ==0){ f = fopen(fn,"w"); // "w" neu tep ton tai no se bi xoa //f = fopen("electron_parameters.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL){printf("\n Cannot open file save_electron_parameters.c"); return ; } fprintf(f,"\n# ne_thPaticle x_position[nm] kx[1/m] FreeFlightTime[fs] Valley Subband Energy[eV] \n"); for (i=1; i<=n_used; i++){ fprintf(f," %d %3.5f %le %3.5f %d %d %3.5f \n",i, p[i][2]/1.0e-9, p[i][1], p[i][3]/1.0e-15, valley[i], subband[i], energy[i]); } }// End of if(myrank ==0){ return; }// End of void save_electron_parameters(){ //*************************************************************************************** /* *********************************************************************** De save cac tham so cua electron de kiem tra Gom 2 phan Starting date: June 07, 2010 Latest update: June 07, 2010 NOTE: for checking only. Dat o dau thi kiem tra o day ************************************************************************* */ #include "mpi.h" void save_electron_distribution(char *fnSubband,char *fnEnergy){ int Get_n_used();// lay so hat dang su dung int n_used = Get_n_used(); double **Get_p(),*Get_energy(); int *Get_valley(),*Get_subband();// lay kx,x,ts, valley, subband va energy cua hat thu i double *energy = Get_energy(); double **p = Get_p(); int *valley = Get_valley(); int *subband = Get_subband(); int Get_NSELECT(); int NSELECT = Get_NSELECT(); //************************************************************************************ // Phan 1. Electron distribution theo Valley va Subband // Cac bien local int i, j; int *ElectronDistributionValley1, *ElectronDistributionValley2,*ElectronDistributionValley3;// Tinh so electron o Valley va subband tuong ung ElectronDistributionValley1 = ivector(1, NSELECT); ElectronDistributionValley2 = ivector(1, NSELECT); ElectronDistributionValley3 = ivector(1, NSELECT); for(i=1; i<=NSELECT; i++){ ElectronDistributionValley1[i]=0; ElectronDistributionValley2[i]=0;ElectronDistributionValley3[i]=0; } int myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); FILE *f, *f1; // Tinh electron dictribution in each valley and subbands if(myrank ==0){ for (i=1; i<=n_used; i++){// Chay cho tat ca cac hat if(valley[i]==1){// Valley 1 for(j=1; j<=NSELECT; j++){ if(subband[i]==j){// Chu y la subband tai hat thu i nhe ElectronDistributionValley1[j] += 1; // tang them 1 hat } } }// end of if(valley[i]==1) else if (valley[i]==2){// Valley 2 for(j=1; j<=NSELECT; j++){ if(subband[i]==j){// Chu y la subband tai hat thu i nhe ElectronDistributionValley2[j] += 1; // tang them 1 hat } } }//end of else if (valley[i]==2) else if (valley[i]==3){// Valley 3 for(j=1; j<=NSELECT; j++){ if(subband[i]==j){// Chu y la subband tai hat thu i nhe ElectronDistributionValley3[j] += 1; // tang them 1 hat } } }//end of else if (valley[i]==3) }// End of for (i=1; i<=n_used; i++){ f = fopen(fnSubband,"w"); // "w" neu tep ton tai no se bi xoa //f = fopen("electron_distributionSubbands.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL){printf("\n Cannot open file at save_electron_distribution for Subband "); return ; } fprintf(f,"\n# Subband Valley1 Valley2 Valley3 \n"); for(j=1; j<=NSELECT; j++){// chay cho NSELECT subband fprintf(f," %d %d %d %d \n",j, ElectronDistributionValley1[j],ElectronDistributionValley2[j],ElectronDistributionValley3[j]); } fclose(f); }// End of if(myrank ==0){ //************************************************************************************ // KET THUC Phan 1. Electron distribution theo Valley va Subband //************************************************************************************ // Phan 2. Electron distribution theo Valley va Energy // Tinh electron distribution in energy range double Get_emax(); double emax = Get_emax(); double de=emax/(double)(n_lev); // energy interval double *E; E=dvector(0,n_lev); // [eV] Dinh nghia dai nang luong E di tu 1*de den "emax" // Neu di tu 0 thi se co loi neu tinh scattering. The hien phan kinetic cua electron for(i=0; i<=n_lev; i++){ E[i] = i*de; } int *ElecDistributionEnergyValley1, *ElecDistributionEnergyValley2,*ElecDistributionEnergyValley3, *ElecDistributionEnergyAllValley; ElecDistributionEnergyValley1 = ivector(0,n_lev); ElecDistributionEnergyValley2 = ivector(0,n_lev); ElecDistributionEnergyValley3 = ivector(0,n_lev); ElecDistributionEnergyAllValley = ivector(0,n_lev); for(i=0; i<=n_lev; i++){ ElecDistributionEnergyValley1[i]=0; ElecDistributionEnergyValley2[i]=0; ElecDistributionEnergyValley3[i]=0; ElecDistributionEnergyAllValley[i]=0; } if(myrank ==0){ for (i=1; i<=n_used; i++){// Chay cho tat ca cac hat if(valley[i]==1){// Valley 1 for(j=0; j<=n_lev; j++){ if ( (energy[i]>= E[j]) && (energy[i]<=E[j+1])){ // Chu y chi so cua energy la i cua E la j ElecDistributionEnergyValley1[j] += 1;// Tang them 1 hat } } } // end of if(valley[i]==1) else if(valley[i]==2){// Valley 2 for(j=0; j<=n_lev; j++){ if ( (energy[i]>= E[j]) && (energy[i]<=E[j+1])){ // Chu y chi so cua energy la i cua E la j ElecDistributionEnergyValley2[j] += 1;// Tang them 1 hat } } } // end of if(valley[i]==2) else if(valley[i]==3){// Valley 3 for(j=0; j<=n_lev; j++){ if ( (energy[i]>= E[j]) && (energy[i]<=E[j+1])){ // Chu y chi so cua energy la i cua E la j ElecDistributionEnergyValley3[j] += 1;// Tang them 1 hat } } } // end of if(valley[i]==3) }// end of for (i=1; i<=n_used; i++) // For all valleys for (i=1; i<=n_used; i++){// Chay cho tat ca cac hat for(j=0; j<=n_lev; j++){ if ( (energy[i]>= E[j]) && (energy[i]<=E[j+1])){ // Chu y chi so cua energy la i cua E la j ElecDistributionEnergyAllValley[j] += 1;// Tang them 1 hat } } } f1 = fopen(fnEnergy,"w"); // "w" neu tep ton tai no se bi xoa //f1 = fopen("electron_distributionEnergyrange.dat","w"); // "w" neu tep ton tai no se bi xoa if(f1==NULL){printf("\n Cannot open file Cannot open file at save_electron_distribution for Energy.dat"); return ; } fprintf(f1,"\n# EnergyStep Valley1 Valley2 Valley3 \n"); for(j=1; j<=n_lev; j++){// chay cho tung energy step fprintf(f1," %f %d %d %d %d \n",j*de,ElecDistributionEnergyValley1[j],ElecDistributionEnergyValley2[j], ElecDistributionEnergyValley3[j],ElecDistributionEnergyAllValley[j]); } fclose(f1); }// End of if(myrank ==0){ // Free local variables free_ivector(ElectronDistributionValley1, 1, NSELECT); free_ivector(ElectronDistributionValley2, 1, NSELECT); free_ivector(ElectronDistributionValley3, 1, NSELECT); free_dvector(E,0,n_lev); free_ivector(ElecDistributionEnergyValley1, 0,n_lev); free_ivector(ElecDistributionEnergyValley2, 0,n_lev); free_ivector(ElecDistributionEnergyValley3, 0,n_lev); free_ivector(ElecDistributionEnergyAllValley, 0,n_lev); return; }// /* // Cach 1: <NAME> dung Feb 19, 2010 void electrons_initialization(){ // Goi cac ham void init_kspace(int ne,int i); void init_realspace(int ne,int i); void Set_n_used( int n); int Get_n_used(); int Get_nx_max(), Get_ny_max(), Get_nz_max(),Get_n_s(),Get_n_d(); int *Get_valley(); // Cac bien local int nx_max = Get_nx_max(); int ny_max = Get_ny_max(); int nz_max = Get_nz_max(); int n_s = Get_n_s(); int n_d = Get_n_d(); int *valley = Get_valley(); // Thuc hien int i,j,k; int ne = 0; // Number of electrons which we initialize // Tai Source for(i=0; i<=n_s; i++){ for(j=0; j<=ny_max; j++){ for(k=0; k<=nz_max; k++){ ne = ne+1; if(ne > max_electron_number){ printf("\n Number of initial electrons = %d",ne); printf("You can change max_electron_number in constants.h file \n"); nrerror("Number of particles exceed max_electron_number"); } //Khoi tao position, valley, subband, momentum, energy cho hat do init_kspace(ne,i); //initial momentum and energy init_realspace(ne,i); // Initial position } } } // Tai Drain for(i=n_d+1; i<=nx_max; i++){ for(j=0; j<=ny_max; j++){ for(k=0; k<=nz_max; k++){ ne = ne+1; if(ne > max_electron_number){ printf("\n Number of initial electrons = %d",ne); printf("You can change max_electron_number in constants.h file \n"); nrerror("Number of particles exceed max_electron_number"); } //Khoi tao position, valley, subband, momentum, energy cho hat do init_kspace(ne,i); //initial momentum and energy init_realspace(ne,i); // Initial position } } } Set_n_used(ne); // Tuong duong voi cau lenh int n_used = ne; int n_used = Get_n_used(); printf("\n Number of electrons initialized = %d",n_used); printf("\n Maximum number of electrons allowed = %d",max_electron_number); for(i=n_used+1; i<=max_electron_number; i++){ valley[i] = 9; // inactive these particles, nhung hat ma vuot ngoai gia tri n_used thi phai inactive } return; } // End of void electrons_initialization() */ <file_sep>/* *********************************************************************** To read voltages from an input file Latest update January 19, 2009 ************************************************************************* */ #include <stdio.h> #include <string.h> #include "mpi.h" static double V_source_input,Vd_start,Vd_end,Vd_step,Vg_start,Vg_end,Vg_step; static double DrainVoltage, GateVoltage; //static double Vd,Vg;Dung ten bien kieu GS void read_voltages_input(){ /* ******** Read voltages from an input file ********* */ FILE *f; char s[180]; f=fopen("Input.d","r"); //rewind(f); // Dua co tro ve dau tep if(f==NULL){printf("Error:can't open file Input.d \n");return;} //printf("\n\n Reading VOLTAGES_INPUT "); while (!feof(f)) { char str[180]; fscanf(f,"%s",str); //fgets(str, 180, f); if(strcmp(str,"#VOLTAGES_INPUT")==0){ fscanf(f,"%*s %*s %lf",&V_source_input); //printf("\n V_source_input[V]= %5.2lf",V_source_input); fscanf(f,"%*s %*s %lf %*s %lf %*s %lf ",&Vd_start,&Vd_end,&Vd_step); //printf("\n Vd_start[V]= %3.2lf Vd_end[V]= %3.2lf Vd_step= %3.2lf",Vd_start,Vd_end,Vd_step); fscanf(f,"%*s %*s %lf %*s %lf %*s %lf ",&Vg_start,&Vg_end,&Vg_step); //printf("\n Vg_start[V]= %3.2lf Vg_end[V]= %3.2lf Vg_step= %3.2lf",Vg_start,Vg_end,Vg_step); } // End of if(strcmp(str,"#VOLTAGES_INPUT")==0){ } // End of while (!feof(f)) fclose(f); // Phan in ra o monitor khi rank=0 int myrank, mysize; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); MPI_Comm_size(MPI_COMM_WORLD,&mysize); if(myrank ==0){ printf("\n\n Reading VOLTAGES_INPUT "); printf("\n V_source_input[V]= %5.2lf",V_source_input); printf("\n Vd_start[V]= %3.2lf Vd_end[V]= %3.2lf Vd_step= %3.2lf",Vd_start,Vd_end,Vd_step); printf("\n Vg_start[V]= %3.2lf Vg_end[V]= %3.2lf Vg_step= %3.2lf",Vg_start,Vg_end,Vg_step); }// End of if(myrank ==0) } /* ******** END OF Read voltages from file ********* */ double Get_V_source_input(){ return V_source_input; } double Get_Vd_start(){ return Vd_start; } double Get_Vd_end(){ return Vd_end; } double Get_Vd_step(){ return Vd_step; } double Get_Vg_start(){ return Vg_start; } double Get_Vg_end(){ return Vg_end; } double Get_Vg_step(){ return Vg_step; } // For Vd void SetDrainVoltage(double v) { DrainVoltage = v ; } double GetDrainVoltage() { return(DrainVoltage); } // For Vg void SetGateVoltage(double v) { GateVoltage = v; } double GetGateVoltage() { return(GateVoltage); } <file_sep>/* ****************************************************************************** The scattering() function is to - select a scattering mechanism by which the particles are scattered - calculate the states of particles after scattering (kx, valley(iv), subband, energy, i_region) Isotropic: is assumed for Acoustic and Non-polar Optical phonon Starting date: March 23, 2010 Latest update: March 25, 2010 ********************************************************************************** */ #include <stdio.h> #include <math.h> #include "constants.h" void scattering() { // Goi ham void Acoustic_mechanism(int s_th,int valley,int e_step,double ei,double eff_mass,double rr); void ZeroOrder_Optical_f_Absorption(int s_th,int val_befo,int val_aft,int e_step,double ei,double eff_mass,double rr,int index); void ZeroOrder_Optical_f_Emission(int s_th,int val_befo,int val_aft,int e_step,double ei,double eff_mass,double rr,int index); void ZeroOrder_Optical_g_Absorption(int s_th,int val,int e_step,double ei,double eff_mass,double rr,int index); void ZeroOrder_Optical_g_Emission(int s_th,int val,int e_step,double ei,double eff_mass,double rr,int index); double *****Get_scat_table(); double Get_electron_energy(),Get_emax(),Get_x_position(),Get_mesh_size_x(); double Get_ml(), Get_mt(); int Get_NSELECT(); long Get_idum(); float random2(long *idum); // int Get_particle_i_th(); // dua thu tu hat dang simulate va di vao ham scattering // Cac bien local double *****scat_table = Get_scat_table(); double electron_energy = Get_electron_energy(); double e_max = Get_emax(); // lay maximum electron energy ta dinh nghia double x_position = Get_x_position(); double mesh_size_x = Get_mesh_size_x(); double ml = Get_ml(); double mt = Get_mt(); int NSELECT = Get_NSELECT(); int Get_nx0(),Get_nx1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; // int nx_max = Get_nx_max(); long idum = Get_idum(); // Thuc hien int valley_before,valley_after; // before and after scattering int index; // chi so cuoi cho mang scat_table[s_th][n][m][ener_step][index] // No cung the hien loai scattering nao. Chu y: index=0:Self-scattering double rr; // gia tri random number da duoc chon double effective_mass; // phu thuoc vao valley_after la valley nao // Buoc 1: tu ham dritf() se biet duoc hat o section nao va co energy step la bao nhieu int s_th = (int)(round(x_position/mesh_size_x)); // s-th section if(s_th < 0) { s_th = 0;} if(s_th > nx_max) {s_th = nx_max;} double de = e_max/(double)(n_lev); //energy_interval if(electron_energy > e_max)// (May 28, 2010) vi co the electron energy no vuot qua cai nguong ma ta dinh nghia e_max lam thi sao ? { electron_energy = e_max; } int ener_step = (int)(electron_energy/de);// Gia tri DONG NANG dau vao thi THUOC energy step THU MAY if(ener_step < 1) { ener_step = 1;} if(ener_step > n_lev) {ener_step = n_lev;} // Buoc 2. Chon loai scattering theo index vv=1 den 21. Dua vao bang trang 107 va 122 double random_number = random2(&idum); if(random_number > scat_table[s_th][NSELECT][NSELECT][ener_step][21]) { // self scattering. KHONG thay doi bat cu Parameters nao index = 0; // Self-scattering //printf("\n particle %d-th: Self-scattering",Get_particle_i_th()); return; // ket thuc ham void scattering();. Kiem tra self scattering truoc de tang toc do } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][1]) { // Chon Acoustic : Valley 1 den Valley 1 valley_after = 1; //valley_before = 1; //index=1 TRUNG voi CHI SO valley index =1; effective_mass = ml*m0; rr = random_number; // random_number nay se duoc su dung de chon chinh xac la no o vi tri nao Acoustic_mechanism(s_th,valley_after,ener_step,electron_energy,effective_mass,rr); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][2]) { // Chon Acoustic : Valley 2 den Valley 2 valley_after = 2; //valley_before = 2;// index=2 TRUNG voi CHI SO valley index = 2; effective_mass = mt*m0; rr = random_number; Acoustic_mechanism(s_th,valley_after,ener_step,electron_energy,effective_mass,rr); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][3]) { // Chon Acoustic : Valley 3 den Valley 3 valley_after = 3; //valley_before = 3;//index=3 TRUNG voi CHI SO valley index = 3; effective_mass = mt*m0; rr = random_number; Acoustic_mechanism(s_th,valley_after,ener_step,electron_energy,effective_mass,rr); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][4]) { // f-Absortion Zero order nonpolar optical valley_before = 1; valley_after = 2; index = 4; effective_mass = mt*m0; rr = random_number; ZeroOrder_Optical_f_Absorption(s_th,valley_before,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][5]) { // f-Emission Zero order nonpolar optical valley_before = 1; valley_after = 2; index = 5; effective_mass = mt*m0; rr = random_number; ZeroOrder_Optical_f_Emission(s_th,valley_before,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][6]) { // f-Absortion Zero order nonpolar optical valley_before = 1; valley_after = 3; index = 6; effective_mass = mt*m0; rr = random_number; ZeroOrder_Optical_f_Absorption(s_th,valley_before,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][7]) { // f-Emission Zero order nonpolar optical valley_before = 1; valley_after = 3; index = 7; effective_mass = mt*m0; rr = random_number; ZeroOrder_Optical_f_Emission(s_th,valley_before,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][8]) { // f-Absortion Zero order nonpolar optical valley_before = 2; valley_after = 1; index = 8; effective_mass = ml*m0; rr = random_number; ZeroOrder_Optical_f_Absorption(s_th,valley_before,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][9]) { // f-Emission Zero order nonpolar optical valley_before = 2; valley_after = 1; index = 9; effective_mass = ml*m0; rr = random_number; ZeroOrder_Optical_f_Emission(s_th,valley_before,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][10]) { // f-Absortion Zero order nonpolar optical valley_before = 2; valley_after = 3; index = 10; effective_mass = mt*m0; rr = random_number; ZeroOrder_Optical_f_Absorption(s_th,valley_before,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][11]) { // f-Emission Zero order nonpolar optical valley_before = 2; valley_after = 3; index = 11; effective_mass = mt*m0; rr = random_number; ZeroOrder_Optical_f_Emission(s_th,valley_before,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][12]) { // f-Absortion Zero order nonpolar optical valley_before = 3; valley_after = 1; index = 12; effective_mass = ml*m0; rr = random_number; ZeroOrder_Optical_f_Absorption(s_th,valley_before,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][13]) { // f-Emission Zero order nonpolar optical valley_before = 3; valley_after = 1; index = 13; effective_mass = ml*m0; rr = random_number; ZeroOrder_Optical_f_Emission(s_th,valley_before,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][14]) { // f-Absortion Zero order nonpolar optical valley_before = 3; valley_after = 2; index = 14; effective_mass = mt*m0; rr = random_number; ZeroOrder_Optical_f_Absorption(s_th,valley_before,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][15]) { // f-Emission Zero order nonpolar optical valley_before = 3; valley_after = 2; index = 15; effective_mass = mt*m0; rr = random_number; ZeroOrder_Optical_f_Emission(s_th,valley_before,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][16]) { // g-Absortion Zero order nonpolar optical valley_after = 1; //valley_before = 1; effective_mass = ml*m0; index = 16; rr = random_number; ZeroOrder_Optical_g_Absorption(s_th,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][17]) { // g-Emission Zero order nonpolar optical valley_after = 1; //valley_before = 1; effective_mass = ml*m0; index = 17; rr = random_number; ZeroOrder_Optical_g_Emission(s_th,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][18]) { // g-Absortion Zero order nonpolar optical valley_after = 2; // valley_before = 2; index = 18; effective_mass = mt*m0; rr = random_number; ZeroOrder_Optical_g_Absorption(s_th,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][19]) { // g-Emission Zero order nonpolar optical valley_after = 2; //valley_before = 2; index = 19; effective_mass = mt*m0; rr = random_number; ZeroOrder_Optical_g_Emission(s_th,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][20]) { // g-Absortion Zero order nonpolar optical valley_after = 3; // valley_before = 3; index = 20; effective_mass = mt*m0; rr = random_number; ZeroOrder_Optical_g_Absorption(s_th,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else if(random_number <= scat_table[s_th][NSELECT][NSELECT][ener_step][21]) { // g-Emission Zero order nonpolar optical valley_after = 3; //valley_before = 3; index = 21; effective_mass = mt*m0; rr = random_number; ZeroOrder_Optical_g_Emission(s_th,valley_after,ener_step,electron_energy,effective_mass,rr,index); } else{ // Da kiem tra tat ca cac dieu kien roi nen neu o day co nghia la LOI printf("\n Some ERRORs in scattering.c"); } //if(index !=0){ // Do self-scattering da xet va printf neu co roi //printf("\n particle %d-th with type of scattering mechanism %d",Get_particle_i_th(), index); // } return; }// End of void scattering() //****************************************************************************** /* ****************************************************************************** Thuc hien machanism cho Acoustics INPUT: + s-th: section nao + valley: o valley nao (before va after la GIONG NHAU cho Acoustic) + e_step: o energy step nao? + ei: dong nang dau vao la bao nhieu. That ra tu ei cung biet duoc e_step + effective mass: Tham so nay duoc DUA vao ham isotropic + rr: so random_number nay se chon 1 trong cac kieu scattering cua Acoustic + NSELECT: number of subband for each valley + eig: eigen value OUTPUT: Update trang thai sau scattering goi ham isotropic() Starting date: March 23, 2010 Latest update: March 25, 2010 ********************************************************************************** */ void Acoustic_mechanism(int s_th,int valley,int e_step,double ei,double effective_mass,double rr) { // Goi cac ham void isotropic(int valley_final,int subband_final,double energy_final,double effective_mass); double ***Get_eig(),*****Get_scat_table(); int Get_NSELECT(); // Bien local double ***eig = Get_eig(); double *****scat_table = Get_scat_table(); int NSELECT = Get_NSELECT(); // Thuc hien double Ef; // final energy int n,m; for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ if(rr <=scat_table[s_th][n][m][e_step][valley]){ Ef = eig[s_th][valley][n] - eig[s_th][valley][m] + ei;//[eV] // valley_final = valley; // subband_final = m isotropic(valley,m,Ef,effective_mass); goto L_end; // Neu chon duoc loai scattering roi thi cho no thoat ra khoi vong lap luon } } }// End of for(n=1; n<=NSELECT; n++) L_end: return; } // End of void Acoustic_mechanism( /********************************************************************************* Thuc hien machanism cho ZeroOrder_Optical_f_Absorption or Emission INPUT: + s-th: section nao + valley_before: valley truoc scattering + valley_after: valley sau scattering + e_step: o energy step nao? + ei: dong nang dau vao la bao nhieu. That ra tu ei cung biet duoc e_step + effective mass: Tham so nay duoc DUA vao ham isotropic + rr: so random_number nay se chon 1 trong cac kieu scattering cua Acoustic + NSELECT: number of subband for each valley + index: chi so cuoi cung cho mang scat_table OUTPUT: Update trang thai sau scattering goi ham isotropic() Starting date: March 23, 2010 Latest update: March 25, 2010 ********************************************************************************** */ void ZeroOrder_Optical_f_Absorption(int s_th,int valley_before,int valley_after,int e_step,double ei,double effective_mass,double rr, int index) { // Goi cac ham void isotropic(int valley_final,int subband_final,double energy_final,double effective_mass); double ***Get_eig(),*****Get_scat_table(); int Get_NSELECT(); double Get_hw0f_phonon(); // Bien local double ***eig = Get_eig(); double *****scat_table = Get_scat_table(); int NSELECT = Get_NSELECT(); double hw0f_phonon = Get_hw0f_phonon(); // Thuc hien double Ef; // final energy int n,m; for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ if(rr <=scat_table[s_th][n][m][e_step][index]){ Ef = eig[s_th][valley_before][n] - eig[s_th][valley_after][m] + ei + hw0f_phonon;//[eV] Absorption // valley_final = valley_after; // subband_final = m isotropic(valley_after,m,Ef,effective_mass); goto L_end; // Neu chon duoc loai scattering roi thi cho no thoat ra khoi vong lap luon } } }// End of for(n=1; n<=NSELECT; n++) L_end: return; } // End of void ZeroOrder_Optical_f_Absorption void ZeroOrder_Optical_f_Emission(int s_th,int valley_before,int valley_after,int e_step,double ei,double effective_mass,double rr, int index) { // Goi cac ham void isotropic(int valley_final,int subband_final,double energy_final,double effective_mass); double ***Get_eig(),*****Get_scat_table(); int Get_NSELECT(); double Get_hw0f_phonon(); // Bien local double ***eig = Get_eig(); double *****scat_table = Get_scat_table(); int NSELECT = Get_NSELECT(); double hw0f_phonon = Get_hw0f_phonon(); // Thuc hien double Ef; // final energy int n,m; for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ if(rr <=scat_table[s_th][n][m][e_step][index]){ Ef = eig[s_th][valley_before][n] - eig[s_th][valley_after][m] + ei - hw0f_phonon;//Emission // valley_final = valley_after; // subband_final = m isotropic(valley_after,m,Ef,effective_mass); goto L_end; // Neu chon duoc loai scattering roi thi cho no thoat ra khoi vong lap luon } } }// End of for(n=1; n<=NSELECT; n++) L_end: return; } // End of void ZeroOrder_Optical_f_Emission /********************************************************************************* Thuc hien machanism cho ZeroOrder_Optical_g_Absorption or Emission INPUT: + s-th: section nao + valley: valley truoc va sau scattering GIONG NHAU + e_step: o energy step nao? + ei: dong nang dau vao la bao nhieu. That ra tu ei cung biet duoc e_step + effective mass: Tham so nay duoc DUA vao ham isotropic + rr: so random_number nay se chon 1 trong cac kieu scattering cua Acoustic + index: chi so cuoi cung cho mang scat_table + NSELECT: number of subband for each valley OUTPUT: Update trang thai sau scattering goi ham isotropic() Starting date: March 23, 2010 Latest update: March 25, 2010 ********************************************************************************** */ void ZeroOrder_Optical_g_Absorption(int s_th,int valley,int e_step,double ei,double effective_mass,double rr,int index) { // Goi cac ham void isotropic(int valley_final,int subband_final,double energy_final,double effective_mass); double ***Get_eig(),*****Get_scat_table(); int Get_NSELECT(); double Get_hw0g_phonon(); // Bien local double ***eig = Get_eig(); double *****scat_table = Get_scat_table(); int NSELECT = Get_NSELECT(); double hw0g_phonon = Get_hw0g_phonon(); // Thuc hien double Ef; // final energy int n,m; for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ if(rr <=scat_table[s_th][n][m][e_step][index]){ Ef = eig[s_th][valley][n] - eig[s_th][valley][m] + ei + hw0g_phonon;//Absorption // valley_final = valley; // subband_final = m isotropic(valley,m,Ef,effective_mass); goto L_end; // Neu chon duoc loai scattering roi thi cho no thoat ra khoi vong lap luon } } }// End of for(n=1; n<=NSELECT; n++) L_end: return; } // End of void ZeroOrder_Optical_f_Absorption void ZeroOrder_Optical_g_Emission(int s_th,int valley,int e_step,double ei,double effective_mass,double rr,int index) { // Goi cac ham void isotropic(int valley_final,int subband_final,double energy_final,double effective_mass); double ***Get_eig(),*****Get_scat_table(); int Get_NSELECT(); double Get_hw0g_phonon(); // Bien local double ***eig = Get_eig(); double *****scat_table = Get_scat_table(); int NSELECT = Get_NSELECT(); double hw0g_phonon = Get_hw0g_phonon(); // Thuc hien double Ef; // final energy int n,m; for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ if(rr <=scat_table[s_th][n][m][e_step][index]){ Ef = eig[s_th][valley][n] - eig[s_th][valley][m] + ei - hw0g_phonon;//Emission // valley_final = valley; // subband_final = m isotropic(valley,m,Ef,effective_mass); goto L_end; // Neu chon duoc loai scattering roi thi cho no thoat ra khoi vong lap luon } } }// End of for(n=1; n<=NSELECT; n++) L_end: return; }// End of void ZeroOrder_Optical_g_Emission( //********************************************************************************** /********************************************************************************* Thuc hien isotropic INPUT: + valley_final: valley after scattering + subband_final: subband after scattering + Ef: final energy after scattering + effective mass: la ml HAY mt TUY THUOC vao valley_final OUTPUT: Update trang thai sau scattering if Ef>0 + o valley nao: iv + o subband nao: m + gia tri energy la bao nhieu: electron_energy (xet khi Ef>0) + gia tri kx la bao nhieu: kx Starting date: March 25, 2010 Latest update: March 26, 2010 ********************************************************************************** */ void isotropic(int valley_final,int subband_final,double energy_final,double effective_mass){ // Goi ham void Set_iv(int valley_pair_index),Set_subb(int subband_index); void Set_kx(double k_momen_x),Set_electron_energy(double ener); double Get_nonparabolicity_factor(); long Get_idum(); float random2(long *idum); // Bien local double af = Get_nonparabolicity_factor(); long idum = Get_idum(); // Thuc hien double kx,k_update,random_number; if(energy_final <=0.0){ return; // khong thuc hien viec gi ca } else{ // energy_final >0.0 // Update carrier wavevector k_update=sqrt(2.0*effective_mass*q)*sqrt(energy_final*(1+af*energy_final))/hbar; random_number = random2(&idum); if(random_number <=0.5) { kx = k_update; // chon forward process } else { // random_number > 0.5 kx = -k_update; // chon backward process } // Update TAT CA ket qua cua HAT SAU SCATTERING Set_iv(valley_final); // valley Set_subb(subband_final); // subband Set_kx(kx); // momentum Set_electron_energy(energy_final);// energy //printf("\n val_final=%d, subb_final=%d,kx=%le, energy=%le",valley_final,subband_final,kx,energy_final); } // End of else{ // energy_final >0.0 return; } // End of void isotropic(double Ef) <file_sep>#include "nanowire.h" #include "region.h" #define SIGN_CONVFACTOR_DOPINGDENSITY sign*conv_factor*doping_density static double SourceDoping ; static double ChannelDoping ; static double DrainDoping ; void SetDopingDensityFor(int convflag, char region, char doping_type, double doping_density) { double sign ; double conv_factor ; if ( convflag==1 ) conv_factor = 1.0e06 ; else conv_factor = 1.0 ; doping_density = fabs(doping_density) ; // necessary for ldos-for-EF routines switch ( doping_type ) { case 'n' : sign = -1.0 ; break ; case 'p' : sign = 1.0 ; break ; case 'i' : sign = 0.0 ; break ; } switch ( region ) { case 's' : // Source SourceDoping = SIGN_CONVFACTOR_DOPINGDENSITY ; break ; case 'c' : // Channel ChannelDoping = SIGN_CONVFACTOR_DOPINGDENSITY ; break ; case 'd' : // Drain DrainDoping = SIGN_CONVFACTOR_DOPINGDENSITY ; break ; } } double GetDopingDensityFor(char region) { switch ( region ) { case 's' : return(SourceDoping) ; case 'c' : return(ChannelDoping) ; case 'd' : return(DrainDoping) ; } return(0.0) ; } double GetDoping(int p) { int region ; int i,j,k ; Region R ; PoiNum N ; double NL ; double *X ; N = GetPoiNum() ; get_ijk(p,&i,&j,&k) ; region = GetRegion(&R,p) ; X = GetPX() ; if ( JUNCTION_SILICON ) { if ( i<N.xa ) return(SourceDoping) ; else if ( i>N.xb ) return(DrainDoping) ; else report_error("Problem in GetDoping(), junction silicon") ; } else if ( CHANNEL_SILICON ) return(ChannelDoping) ; else return(0.0) ; return(0.0) ; } int signfunc(double x) { if ( x>0.0 ) return(1) ; else return(-1) ; } <file_sep>#include <stdlib.h> int nint() ; int imax() ; int imin() ; double dmax() ; double dmin() ; void i_interchange() ; void d_interchange() ; char *sword() ; char **svector() ; double **dmatrix_mpi() ; double ***d3matrix_mpi() ; double ****d4matrix() ; double ****d4matrix_mpi() ; double *****d5matrix_mpi() ; double maxV_of_Rvec() ; int stop_when() ; void report_error() ; void get_time() ; void reset_time() ; void free_sword() ; void free_svector() ; void free_dvector() ; void free_d4matrix_mpi() ; void free_dmatrix_mpi() ; //void nrerror() ; void Rmtx_mul() ; void rRmtx_mul() ; void Rmtx_mul_ABt() ; void Rmtx_mul_AtB() ; void Rmtx_3mul() ; void Rmtx_3mul_rABCt() ; void Rmtx_3mul_AtBC() ; void Rmtx_mul_dgemm() ; void Rmtx_add() ; void Rmtx_sub() ; void r_times_Rmtx() ; void r_times_Rmtx2() ; void tdRmtx_mul() ; void set_null_Rvec() ; void set_null_Rmtx() ; void set_null_R3mtx() ; void Transpose_Rmtx() ; void copy_Rvec() ; void copy_Rmtx() ; void copy_R3mtx() ; void print_Rvec() ; void print_Rmtx() ; void print_Rmtx_condensed() ; void Identity_Rmtx() ; int ConvertBooleanCharToInt() ; int ConvertBooleanToInt() ; #define MaxChar 100 #define tiny_03 1.0e-03 #define tiny_04 1.0e-04 #define tiny_05 1.0e-05 #define tiny_06 1.0e-06 #define tiny_07 1.0e-07 #define tiny_08 1.0e-08 #define tiny_09 1.0e-09 #define tiny_10 1.0e-10 #define tiny_12 1.0e-12 #define tiny_15 1.0e-15 #define tiny_20 1.0e-20 <file_sep>/* **************************************************************** To save parameters: Electrostatic potential Sau khi chay cuoi cung cua time flag = 1: xyz flag = 0: along x_direction (yz) or y_direction (xz) or z_direction (xy) flag = 2: co dinh y va z VE THEO PHUONG x only Starting date: May 24, 2010 Latest Update: May 25, 2010 ****************************************************************** */ #include <stdio.h> #include <math.h> #include "petscksp.h" #include "nanowire.h" #include "region.h" #include "nrutil.h" #include "constants.h" void save_potential_parameters_from_input_file(int flag){ double ***Phi = GetPot(); int Get_nx0(),Get_nx1(), Get_ny0(),Get_ny1(), Get_nz0(),Get_nz1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int ny0 = Get_ny0(); int ny1 = Get_ny1(); int nz0 = Get_nz0(); int nz1 = Get_nz1(); int nx_max = nx1-nx0; int ny_max = ny1-ny0; int nz_max = nz1-nz0; double Get_mesh_size_x(),Get_mesh_size_y(),Get_mesh_size_z(); double mesh_size_x = Get_mesh_size_x(); double mesh_size_y = Get_mesh_size_y(); double mesh_size_z = Get_mesh_size_z(); double Get_Eg(); // Band gap double Eg = Get_Eg(); double delta_Ec = Eg/2.0; double x_pos = 0.0, y_pos = 0.0, z_pos = 0.0;// Can khoi tao se tranh nham bien toan cuc int i,j,k; /* ****************** flag == 1 ve cac tham so tren xyz ************ */ if(flag==1){ // Ve cac tham so tren theo ca phuong x,y, va z FILE *f; f=fopen("potential_xyz.dat","w");//"w" nen neu chay cho nhieu (Vd,Vg) point thi no la cho CAP CUOI CUNG fprintf(f,"\n #x[nm] y[nm] z[nm] pot_xyz[eV] \n"); x_pos = 0.0, y_pos = 0.0, z_pos=0.0; for(i=0;i<=nx_max;i++){ x_pos = (double)(i)*mesh_size_x/1.0e-9;// [m] -> [nm] for(j=0;j<=ny_max;j++){ y_pos = (double)(j)*mesh_size_y/1.0e-9;// [m] -> [nm] for(k=0; k<=nz_max; k++){ z_pos = (double)(k)*mesh_size_z/1.0e-9; fprintf(f,"%le %le %le %le \n",x_pos,y_pos,z_pos, (delta_Ec - Phi[i][j][k]));// potential[eV] } //End of for(k=0; k<=nz_max; k++) } // End of for(j=0;j<=ny_max;j++){ }// End of for(i=0;i<=nx_max;i++){ fclose(f); }// End of if(flag ==1){ // Ve cac tham so tren theo ca phuong x,y,z /* **************** End of flag ==1 ve cac tham so tren xy plane ************ */ /* ***************** flag==0 ve cac tham so theo mat phang xy, yz and xz************ */ if(flag == 0){ double Get_length_plotted(), Get_depth_plotted(), Get_width_plotted(); double length = Get_length_plotted();// doc vao o read_simulation_list.c da chuyen sang dang [m] double depth = Get_depth_plotted(); double width = Get_width_plotted(); // **************************Cat theo phuong x **************************** FILE *f1; f1 = fopen("potential_yz_plane.dat","w");// "w" ghi de if(f1==NULL){ printf("\n Cannot open file potential_yz_plane.dat");return; } fprintf(f1,"\n #y[nm] z[nm] pot_yz[eV] \n"); i = (int)(length/mesh_size_x + 0.5); y_pos = 0.0, z_pos = 0.0; for(j=0;j<=ny_max;j++){ y_pos = (double)(j)*mesh_size_y/1.0e-9;// [m] -> [nm] for(k=0; k<=nz_max; k++){ z_pos = (double)(k)*mesh_size_z/1.0e-9; fprintf(f1," %le %le %le \n",y_pos,z_pos,(delta_Ec - Phi[i][j][k]));// potential[eV] } //End of for(k=0; k<=nz_max; k++) } // End of for(j=0;j<=ny_max;j++){ fclose(f1); // ********************** End of Cat theo phuong x **************************** /* ************************** Cat theo phuong y **************************** */ FILE *f2; f2 = fopen("potential_xz_plane.dat","w");// Kieu mo "w" ghi de if(f2==NULL){ printf("\n Cannot open file potential_xz_plane.dat"); return; } fprintf(f2,"\n #x[nm] z[nm] pot_xz[eV] \n"); j = (int)(depth/mesh_size_y + 0.5); x_pos = 0.0, z_pos = 0.0; for(i=0;i<=nx_max;i++){ x_pos = (double)(i)*mesh_size_x/1.0e-9;// [m] -> [nm] for(k=0; k<=nz_max; k++){ z_pos = (double)(k)*mesh_size_z/1.0e-9; fprintf(f2," %le %le %le \n",x_pos,z_pos,(delta_Ec - Phi[i][j][k]));// potential[eV] } //End of for(k=0; k<=nz_max; k++) }// End of for(i=0;i<=nx_max;i++){ fclose(f2); // ********************** End of Cat theo phuong y **************************** // **************************Cat theo phuong z **************************** FILE *f3; f3 = fopen("potential_xy_plane.dat","a"); if(f3==NULL){ printf("\n Cannot open file potential_xy_plane.dat");return; } fprintf(f3,"\n #x[nm] y[nm] pot_xy[eV] \n"); k = (int)(width/mesh_size_z + 0.5); x_pos = 0.0, y_pos = 0.0; for(i=0;i<=nx_max;i++){ x_pos = (double)(i)*mesh_size_x/1.0e-9;// [m] -> [nm] for(j=0;j<=ny_max;j++){ y_pos = (double)(j)*mesh_size_y/1.0e-9;// [m] -> [nm] fprintf(f3," %le %le %le \n",x_pos,y_pos, (delta_Ec - Phi[i][j][k]));// potential[eV] } // End of for(j=0;j<=ny_max;j++){ }// End of for(i=0;i<=nx_max;i++){ fclose(f3); // ********************** End of Cat theo phuong z **************************** } // End of if(flag ==0) /* *************** End of flag==0 ve cac tham so theo mat phang xy, yz and xz *********** */ /* ***************** flag==2 VE THEO x thoi con y va z duoc co dinh va doc tu Input file************ */ if(flag == 2){ double Get_depth_plotted(), Get_width_plotted(); double depth = Get_depth_plotted();// doc vao o read_simulation_list.c da chuyen sang dang [m] double width = Get_width_plotted(); // **************************Ve theo phuong x only **************************** FILE *f4; f4 = fopen("potential_x_direction.dat","a"); if(f4==NULL){ printf("\n Cannot open file potential_x_direction.dat");return; } fprintf(f4,"\n #x[nm] pot_x[eV] \n"); j = (int)(depth/mesh_size_y + 0.5); k = (int)(width/mesh_size_z + 0.5); x_pos = 0.0; for(i=0;i<=nx_max;i++){ x_pos = (double)(i)*mesh_size_x/1.0e-9;// [m] -> [nm] fprintf(f4,"%le %le \n",x_pos, (delta_Ec - Phi[i][j][k]));// potential[eV] }// End of for(i=0;i<=nx_max;i++){ fclose(f4); } // ********************** End of Ve theo phuong x only **************************** return; } <file_sep> #ifndef _FUNCTIONS_H_ #define _FUNCTIONS_H_ // Material parameters void material_param(); double Get_ml(); double Get_mt(); double Get_constant_acoustic(); double Get_constant_optical_g_e(); double Get_constant_optical_g_a(); double Get_constant_optical_f_e(); double Get_constant_optical_f_a(); double Get_Vt(); double Get_intrinsic_carrier_density(); double Get_affinity_silicon(); double Get_gateWF(); double Get_Eg(); double Get_BandgapOxide(); double Get_nonparabolicity_factor(); double Get_emax(); double Get_hw0f_phonon(); double Get_hw0g_phonon(); //Device structure void device_structure(); double Get_mesh_size_x(); double Get_mesh_size_y(); double Get_mesh_size_z(); int Get_Tox_mesh(); int Get_Tbox_mesh(); int Get_Wox_mesh(); int Get_nx0(); int Get_nxa(); int Get_nxb(); int Get_nx1(); int Get_ny0(); int Get_nya(); int Get_nyb(); int Get_ny1(); int Get_nz0(); int Get_nza(); int Get_nzb(); int Get_nz1(); int Get_nxgate0(); int Get_nxgate1(); double *Get_doping_density(); // Find region int find_region(int i,int j,int k); // Initialization for doping and potential void initial_potential_doping(); void save_initial_potential_doping(); void save_initial_charge_density_for_Poisson(); // Cai lay tu initial potentential void save_charge_density_for_Poisson();// Save charge density cai dua vao Poisson tai cac Interim void save_potential();// Save potential tai bat cu diem nao dat ham nay // Khoi tao so hat tai dau Mut cua Source va Drain contact void source_drain_carrier_number(); int Get_nsource_side_carriers(); int Get_ndrain_side_carriers(); // Read voltages from an input file void read_voltages_input(); double Get_V_source_input(); double Get_Vd_start(); double Get_Vd_end(); double Get_Vd_step(); double Get_Vg_start(); double Get_Vg_end(); double Get_Vg_step(); void SetDrainVoltage(double v); double GetDrainVoltage(); void SetGateVoltage(double v); double GetGateVoltage(); // Read simulation list from Input.dat void read_simulation_list(); double Get_dt(); double Get_tot_time(); double Get_transient_time(); double Get_length_plotted(); double Get_depth_plotted(); double Get_width_plotted(); int Get_NSELECT(); int Get_NTimeSteps(); double Get_artificial_factor_cell_volume(); // Read scattering and save list void read_scattering_save_list(); int Get_num_scat_used(); int Get_flag_ballistic_transport(); int Get_flag_acoustic(); int Get_flag_zero_order_optical(); int Get_flag_first_order_optical(); int Get_flag_Coulomb(); int Get_flag_Surface_roughness(); int Get_save_eig_wavefuntion(); int Get_save_doping_potential_init(); int Get_save_electron_initlization(); int Get_save_form_factor(); int Get_save_scattering_rate(); int Get_save_electron_population(); int Get_save_electron_density(); int Get_save_VelEnerCurr_all_time_steps(); int Get_save_VelEnerCurr_after_transient(); int Get_save_init_free_flight(); // Applied voltage void apply_voltage(); // Khoi tai so hat electrons trong device void electrons_initialization(); void save_electron_parameters(char *fn);// Dat o dau thi save o day void save_electron_distribution(char *fnSubband,char *fnEnergy); // Dat o dau thi save o day // Khoi tao momentum, energy, valley, subband void init_kspace(int ne,int i); // Khoi tao position void init_realspace(int ne,int i); // Tinh so hat dang duoc su dung trong device voi valley KHAC 9 int count_used_particles(); // Ham random float random2(long *idum); // Define functions void initial_variables(); void Set_n_used( int n); int Get_n_used(); double **Get_p(); double *Get_energy(); int *Get_valley(); int *Get_subband(); long Get_idum(); double *****Get_wave(); double ***Get_eig(); double ***Get_eig_jthSchro(); double ***Get_doping(); double ***Get_fai(); double ***Get_fai_jthSchro(); double *Get_pot(); double **Get_trap_weights(); double ****Get_form_factor(); double *****Get_scat_table(); double *Get_max_gm(); void Set_iss_out(int out_p); int Get_iss_out(); void Set_iss_eli(int eli_p); int Get_iss_eli(); void Set_iss_cre(int cre_p); int Get_iss_cre(); void Set_idd_out(int out_p); int Get_idd_out(); void Set_idd_eli(int eli_p); int Get_idd_eli(); void Set_idd_cre(int cre_p); int Get_idd_cre(); void Set_kx(double k_momen_x); double Get_kx(); void Set_dtau(double flight_time); double Get_dtau(); void Set_x_position(double position_in_x); double Get_x_position(); void Set_electron_energy(double ener); double Get_electron_energy(); void Set_iv(int valley_pair_index); int Get_iv(); void Set_subb(int subband_index); int Get_subb(); void Set_particle_i_th( int i); //26/03/10 15:16 int Get_particle_i_th(); double ***Get_electron_density(); double *Get_velocity_x_sum(); double *Get_energy_sum(); double *Get_current_sum(); double *Get_velocity_x_sum_after_transient(); double *Get_energy_sum_after_transient(); double *Get_current_sum_after_transient(); double *Get_pot_x_avg(); double **Get_pot_yz_avg(); // Lay Potential de dua vao 2D Schrodinger void get_potential(int s, int ny, int nz); // Using First order correction for eigen energy void eigen_energy_correction(int StepsUsedCorrection); //Solved_2D_Schro_for_MSMC() void Solved_2D_Schro_Parallel_for_MSMC(int *argc, char ***argv); void Solved_2D_Schro_for_MSMC(); void Schrodinger2D(int s, int v, double m1, double m2); void makeh(int ny,int nz,double ly,double lz,double *potential,double **ham,double m1, double m2); void diasym(int s, int v,int ny, int nz,double ly,double lz,int NSELECT, double **ham, double ***eig, double *****wave); void normalize_wave(int s,int v,int ny,int nz,int NSELECT, double *****wave); void save_eig_wave(int s,int v, char *fneigen, char *fnwave); double energy0(int ky,int kz,double ly,double lz,double m1, double m2); void multiply_matrix(int INDEX,double alpha, double **matrixA, double **matrixB, double **matrixC); void convert_mtx_to_array(int M, int N, double **mtx, double *a); void convert_array_to_mtx(int M, int N, double *a, double **mt); void print_matrix( char* desc, int m, int n, double* a, int lda ); double psirealspace(double y,double z,int ny,int nz,double ly,double lz,double **vec, int index); void save_subband_energy(char *fnsubband); void save_potential_used_for_2D_Schrodinger(char *fn_x, char *fn_yz); // Form factor void form_factor_calculation(); void trapezoidal_weights(); void printf_form_factor_calculation(int nx, int NSELECT); void save_form_factor_calculation(int s_th, char *fn); // Making scattering table and normalize void scattering_table(); void normalize_table(); void save_scattering_table(int s_th, char *fn); void save_normalized_table();//For checking // Save results void save_results(); // initial free flight time void init_free_flight(); // Thuc hien Ensemble Monte Carlo (EMC) cho 1 step dt void emcd(); void drift(double tau); void check_boundary(); // Thuc hien scattering() sau khi hat da drift void scattering() ; void Acoustic_mechanism(int s_th,int valley,int e_step,double ei,double eff_mass,double rr); void ZeroOrder_Optical_f_Absorption(int s_th,int val_befo,int val_aft,int e_step,double ei,double eff_mass,double rr,int index); void ZeroOrder_Optical_f_Emission(int s_th,int val_befo,int val_aft,int e_step,double ei,double eff_mass,double rr,int index); void ZeroOrder_Optical_g_Absorption(int s_th,int val,int e_step,double ei,double eff_mass,double rr,int index); void ZeroOrder_Optical_g_Emission(int s_th,int val,int e_step,double ei,double eff_mass,double rr,int index); void isotropic(int valley_final,int subband_final,double energy_final,double effective_mass); // Kiem tra so hat o S va D theo charge neutrality de neu can thi eliminate hoac create void check_source_drain_contacts(); // Hat co subband[] =9 thi can delete void delete_particles(); // De tinh electron density cho dau vao cua Poisson void electron_density_caculation(); void save_electron_population(double ***electron_population, int nx_max, int v_max, int NSELECT); void save_electron_density(char *fn); void save_electron_density_all_sections(char *fn); // Tinh va Save velocity, energy and current cumulative void velocity_energy_cumulative(FILE *f1, FILE *f2, double time,int iteration_reference); void save_VeloEnerCurrent_all_time_steps(FILE *f1, double *velo,double *ener,double *curr,int steps,int nx_max,double mesh_size_x); void save_VeloEnerCurrent_after_transient(FILE *f2, double *velo,double *ener,double *curr,int n_ti,int nx_max,double mesh_size_x); // Thuc hien MSMC void multi_subbands_MC(FILE *logfile, int *argc, char ***argv); // Tinh current void current_calculation(double *cur_av); void linreg(double x[],double y[],double sigma[],int N ,double a_fit[],double sig_a[],double yy[],double *chisqr ); // Tinh eigen correction void eigen_energy_correction(int StepsUsedCorrection); void save_eig_correction(int StepsUsedCorrection); // Save potential void save_potential(int flag); void save_potential_average(FILE *f1, FILE *f2, double time, int iter_reference); // For Poisson 3D /* // Tai file init.c co 2 ham duoi day void Initialize(int *argc, char ***argv); void Finalize(); // Ket thuc Tai file init.c // Tai init_local.c co cac ham sau void initialize_general_constants(); void set_position_x_direction(); void set_position_y_direction(); void set_position_z_direction(); void set_regions(); void divide_region(double h,double xlimit,double *Pos,int *K,double *xv); // Ket thuc Tai init_local.c // Tai init_pot.c co cac ham void set_initial_potential(); void assign_built_in_potential(); // Referenced by SetPhi_Contact(). void guess_potential(); // Referenced by set_initial_potential(). void make_flat_zero_potential(int zflag); // KHONG Thay dung ham nay void mpi_distribute_potential_from_node0(int node, int np); // Referenced by set_initial_potential(). // Ket thuc tai init_pot.c // Tai doping.c co cac ham sau void SetDopingDensityFor(int convflag, char region, char doping_type, double doping_density); double GetDopingDensityFor(char region); double GetDoping(int p); int signfunc(double x); // Ket thuc tai doping.c // Tai nq.c co cac ham double Func_Nq(int i,int j,int k); double Func_DNq(int i,int j,int k); double nq(int i,int j,int k); double Dnq(int i,int j,int k); double nq_linearized(int p); double nq_linearized2(int p); void read_charge_density(); void mpi_distribute_nq_from_node0(double ***nq, int node, int np); // Ket thuc tai nq.c // Tai plain_outs.c co cac ham void print_potential_plain(char *fn); void print_midline_potential_plain(char *fn); void mpi_gather_potential_at_node0(); // Ke thuc tai plain_outs.c // Tai outs.c co cac ham void SetPRINT_MidPotFlag(); void SetPRINT_Pot3dFlag(); int GetPRINT_MidPotFlag(); int GetPRINT_Pot3dFlag(); void print_output(); // Ket thuc tai outs.c // Tai define_poi.c xem poisson3d.h void solve_3d_poisson() ; void solve_3d_poisson_linearized() ; void print_output() ; void read_charge_density() ; void (*SolvePoisson)() ; */ // De chay duoc ham mai cua GS void Initialize() ; void Finalize() ; void solve_3d_poisson() ; void solve_3d_poisson_linearized() ; void print_output() ; void read_charge_density() ; void (*SolvePoisson)() ; // Solve Poisson at equilibrium void solve_Poisson_at_equilibrium(int *argc, char ***argv); void logfile_PoissonInput(); void logging(FILE *log,const char *fmt,...);// Ham nay de tao ta logfile #endif // _FUNCTIONS_H_ <file_sep>#include "nrutil.h" #include "petscksp.h" #include "nanowire.h" #include "region.h" static Mat MatA ; static Vec Vecb,Vecx ; static KSPType ksptype ; static KSP ksp ; static PC pc ; static PCType pctype ; static double ksprtol ; static int gmres_restart ; static PoiNum N ; static int Ntot ; static int *diag_entry ; static double *alpha_xplus,*alpha_yplus,*alpha_zplus,*alpha_xminus,*alpha_yminus,*alpha_zminus ; static double *alpha_center,*alpha_const,*alpha_q0e ; double falpha_xplus(),falpha_yplus(),falpha_zplus() ; double falpha_xminus(),falpha_yminus(),falpha_zminus() ; #undef __FUNCT__ #define __FUNCT__ "initialize_poisson" int initialize_poisson() { N = GetPoiNum() ; Ntot = N.x*N.y*N.z ; PoiMem *M = PGetPoiMem() ; M->Phi = d3matrix_mpi(N.x0-1,N.x1+1,N.y0-1,N.y1+1,N.z0-1,N.z1+1) ; M->phi = d3matrix_mpi(N.x0-1,N.x1+1,N.y0-1,N.y1+1,N.z0-1,N.z1+1) ; M->n3d = d3matrix_mpi(N.x0,N.x1,N.y0,N.y1,N.z0,N.z1) ; M->p3d = d3matrix_mpi(N.x0,N.x1,N.y0,N.y1,N.z0,N.z1) ; void set_null_out_of_bound() ; set_null_out_of_bound() ; // Matrix Creation int np ; MPI_Comm_size(PETSC_COMM_WORLD,&np) ; int Nlocal = Ntot/np ; int d_nz,o_nz ; int *d_nnz = PETSC_NULL ; int *o_nnz = PETSC_NULL ; if ( Nlocal < N.z ) d_nz = 3 ; else if ( Nlocal < N.y*N.z ) d_nz = 5 ; else d_nz = 7 ; o_nz = 7-d_nz ; PetscErrorCode ierr ; ierr = MatCreateMPIAIJ(PETSC_COMM_WORLD,PETSC_DECIDE,PETSC_DECIDE,Ntot,Ntot,d_nz,d_nnz,o_nz,o_nnz,&MatA) ; CHKERRQ(ierr); ierr = MatSetFromOptions(MatA) ; CHKERRQ(ierr) ; // Assign Alphas void poisson_memory_allocation() ; poisson_memory_allocation() ; PoiParam CP = GetPoiParam() ; void set_alphas_1() ; set_alphas_1() ; // Assign Off-diagonal Elements int I,J,Istart,Iend,p,i,j,k ; int Ns = N.y*N.z ; double v ; ierr = MatGetOwnershipRange(MatA,&Istart,&Iend) ; CHKERRQ(ierr) ; for ( I=Istart ; I<Iend ; I++ ) { p = I+1 ; get_ijk(p,&i,&j,&k) ; if ( i-1>=N.x0 ) { J = I-Ns ; v = alpha_xminus[p] ; ierr = MatSetValues(MatA,1,&I,1,&J,&v,INSERT_VALUES) ; CHKERRQ(ierr) ; } if ( j-1>=N.y0 ) { J = I-N.z ; v = alpha_yminus[p] ; ierr = MatSetValues(MatA,1,&I,1,&J,&v,INSERT_VALUES) ; CHKERRQ(ierr) ; } if ( k-1>=N.z0 ) { J = I-1 ; v = alpha_zminus[p] ; ierr = MatSetValues(MatA,1,&I,1,&J,&v,INSERT_VALUES) ; CHKERRQ(ierr) ; } if ( k+1<=N.z1 ) { J = I+1 ; v = alpha_zplus[p] ; ierr = MatSetValues(MatA,1,&I,1,&J,&v,INSERT_VALUES) ; CHKERRQ(ierr) ; } if ( j+1<=N.y1 ) { J = I+N.z ; v = alpha_yplus[p] ; ierr = MatSetValues(MatA,1,&I,1,&J,&v,INSERT_VALUES) ; CHKERRQ(ierr) ; } if ( i+1<=N.x1 ) { J = I+Ns ; v = alpha_xplus[p] ; ierr = MatSetValues(MatA,1,&I,1,&J,&v,INSERT_VALUES) ; CHKERRQ(ierr) ; } } // Create Vectors ierr = VecCreate(PETSC_COMM_WORLD,&Vecb) ; CHKERRQ(ierr) ; ierr = VecSetSizes(Vecb,PETSC_DECIDE,Ntot) ; CHKERRQ(ierr) ; ierr = VecSetFromOptions(Vecb) ; CHKERRQ(ierr) ; ierr = VecDuplicate(Vecb,&Vecx) ; CHKERRQ(ierr) ; // KSP Setup PCType GetPCType() ; KSPType GetKSPType() ; pctype = GetPCType() ; ksptype = GetKSPType() ; ksprtol = CP.ksprtol ; gmres_restart = CP.gmres_restart ; ierr = KSPCreate(PETSC_COMM_WORLD,&ksp) ; CHKERRQ(ierr) ; ierr = KSPGetPC(ksp,&pc) ; CHKERRQ(ierr) ; ierr = PCSetType(pc,pctype) ; CHKERRQ(ierr) ; ierr = KSPSetType(ksp,ksptype) ; CHKERRQ(ierr) ; ierr = KSPGMRESSetRestart(ksp,gmres_restart) ; CHKERRQ(ierr) ; ierr = KSPSetTolerances(ksp,ksprtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT) ; CHKERRQ(ierr) ; ierr = KSPSetFromOptions(ksp) ; CHKERRQ(ierr) ; // Set n0 and n1 for schrodinger and negf int I0,I1 ; int *I0s = ivector(0,np-1) ; int *I1s = ivector(0,np-1) ; get_ijk(Istart+1,&I0,&j,&k) ; if ( !(j==N.y0 && k==N.z0) ) I0++ ; get_ijk(Iend,&I1,&j,&k) ; MPI_Allgather(&I0,1,MPI_INT,&I0s[0],1,MPI_INT,PETSC_COMM_WORLD) ; MPI_Allgather(&I1,1,MPI_INT,&I1s[0],1,MPI_INT,PETSC_COMM_WORLD) ; void SetLocalN() ; SetLocalN(np,I0s,I1s) ; free_ivector(I0s,0,np-1) ; free_ivector(I1s,0,np-1) ; return 0 ; } #undef __FUNCT__ #define __FUNCT__ "solve_3d_poisson" int solve_3d_poisson_linearized() { // Skip If Read from Existing File int node,np ; MPI_Comm_rank(PETSC_COMM_WORLD,&node) ; MPI_Comm_size(PETSC_COMM_WORLD,&np) ; // Set-Up int Istart,Iend,low,high,local_x0,local_x1,j,k ; double ***Phi = GetPot() ; void set_alphas_2(),fix_corners() ; PoiParam CP = GetPoiParam() ; int MaxIter = CP.MaxIter ; PetscErrorCode ierr ; PetscScalar *Vecx_local ; ierr = MatGetOwnershipRange(MatA,&Istart,&Iend) ; CHKERRQ(ierr) ; ierr = VecGetOwnershipRange(Vecb,&low,&high) ; CHKERRQ(ierr) ; get_ijk(Istart+1,&local_x0,&j,&k) ; get_ijk(Iend,&local_x1,&j,&k) ; fix_corners(Phi,local_x0,local_x1) ; set_alphas_2() ; // Iteration int iter,I,J,p,i,no_ksp_its ; double v,norm_local,norm,norm_old=-1.0e30,nq_linearized(),nq_linearized2(),fabs(),sqrt() ; void mpi_transfer_phi() ; // Assigning Diagonal Elements for ( I=Istart ; I<Iend ; I++ ) { p = I+1 ; J = I ; v = alpha_center[p]-alpha_q0e[p]*nq_linearized(p) ; ierr = MatSetValues(MatA,1,&I,1,&J,&v,INSERT_VALUES) ; CHKERRQ(ierr) ; } // Matrix Assemble ierr = MatAssemblyBegin(MatA,MAT_FINAL_ASSEMBLY) ; CHKERRQ(ierr) ; ierr = MatAssemblyEnd(MatA,MAT_FINAL_ASSEMBLY) ; CHKERRQ(ierr) ; ierr = MatSetOption(MatA,MAT_NO_NEW_NONZERO_LOCATIONS);CHKERRQ(ierr); // Assinging Right Hand Side Vector for ( I=low ; I<high ; I++ ) { p = I+1 ; v = -alpha_const[p] + alpha_q0e[p]*nq_linearized2(p) ; ierr = VecSetValues(Vecb,1,&I,&v,INSERT_VALUES) ; CHKERRQ(ierr) ; } // KSP Procedure ierr = KSPSetOperators(ksp,MatA,MatA,SAME_NONZERO_PATTERN) ; CHKERRQ(ierr) ; ierr = KSPSolve(ksp,Vecb,Vecx) ; CHKERRQ(ierr) ; ierr = KSPGetIterationNumber(ksp,&no_ksp_its) ; ierr = PetscPrintf(PETSC_COMM_WORLD,"KSP_Iter_No = %d\n",no_ksp_its) ; CHKERRQ(ierr) ; if ( no_ksp_its==0 ) { ierr = PetscPrintf(PETSC_COMM_WORLD,"KSP_Iter_No = 0 Ocurred") ; Finalize() ; exit(0) ; } // Update phi locallly ierr = VecGetArray(Vecx,&Vecx_local) ; CHKERRQ(ierr) ; for ( I=Istart ; I<Iend ; I++ ) { p = I+1 ; get_ijk(p,&i,&j,&k) ; Phi[i][j][k] = Vecx_local[I-Istart] ; } ierr = VecRestoreArray(Vecx,&Vecx_local) ; CHKERRQ(ierr) ; // Transfer Phi mpi_transfer_phi(Phi,node,np,Istart,Iend) ; // Fix Corners fix_corners(Phi,local_x0,local_x1) ; // Print Midline Potential if ( GetPRINT_MidPotFlag() ) { char fn[100] ; void print_midline_potential_plain() ; sprintf(fn,"mpot.r-Vd%.2lf-Vg%.2lf",GetDrainVoltage(),GetGateVoltage()) ; print_midline_potential_plain(fn,0) ; } return 0 ; } int solve_3d_poisson() { // Skip If Read from Existing File int node,np ; double Func_Nq(), Func_DNq() ; MPI_Comm_rank(PETSC_COMM_WORLD,&node) ; MPI_Comm_size(PETSC_COMM_WORLD,&np) ; // Set-Up int Istart,Iend,low,high,local_x0,local_x1,j,k ; double ***Phi = GetPot() ; double ***phi = GetPhiKth() ; void set_alphas_2(),fix_corners() ; PoiParam CP = GetPoiParam() ; int MaxIter = CP.MaxIter ; PetscErrorCode ierr ; PetscScalar *Vecx_local ; ierr = MatGetOwnershipRange(MatA,&Istart,&Iend) ; CHKERRQ(ierr) ; ierr = VecGetOwnershipRange(Vecb,&low,&high) ; CHKERRQ(ierr) ; get_ijk(Istart+1,&local_x0,&j,&k) ; get_ijk(Iend,&local_x1,&j,&k) ; fix_corners(Phi,local_x0,local_x1) ; copy_R3mtx(phi,Phi,local_x0-1,local_x1+1,N.y0-1,N.y1+1,N.z0-1,N.z1+1) ; set_alphas_2() ; // Iteration int iter,I,J,p,i,no_ksp_its ; double v,norm_local,norm,norm_old=-1.0e30,Fnn(),DFnn(),fabs(),sqrt() ; void mpi_transfer_phi() ; PetscPrintf(PETSC_COMM_WORLD,"\n - Poisson Solver -\n") ; for ( iter=1 ; iter<=MaxIter ; iter++ ) { // Assigning Diagonal Elements for ( I=Istart ; I<Iend ; I++ ) { p = I+1 ; J = I ; v = DFnn(p,Func_DNq) ; ierr = MatSetValues(MatA,1,&I,1,&J,&v,INSERT_VALUES) ; CHKERRQ(ierr) ; } // Matrix Assemble ierr = MatAssemblyBegin(MatA,MAT_FINAL_ASSEMBLY) ; CHKERRQ(ierr) ; ierr = MatAssemblyEnd(MatA,MAT_FINAL_ASSEMBLY) ; CHKERRQ(ierr) ; ierr = MatSetOption(MatA,MAT_NO_NEW_NONZERO_LOCATIONS);CHKERRQ(ierr); // Assinging Right Hand Side Vector for ( I=low ; I<high ; I++ ) { p = I+1 ; v = Fnn(p,Func_Nq) ; ierr = VecSetValues(Vecb,1,&I,&v,INSERT_VALUES) ; CHKERRQ(ierr) ; } // KSP Procedure ierr = KSPSetOperators(ksp,MatA,MatA,SAME_NONZERO_PATTERN) ; CHKERRQ(ierr) ; ierr = KSPSolve(ksp,Vecb,Vecx) ; CHKERRQ(ierr) ; ierr = KSPGetIterationNumber(ksp,&no_ksp_its) ; if ( no_ksp_its==0 ) { ierr = PetscPrintf(PETSC_COMM_WORLD,"KSP_Iter_No = 0 Ocurred") ; Finalize() ; exit(0) ; } // Update phi locallly ierr = VecGetArray(Vecx,&Vecx_local) ; CHKERRQ(ierr) ; norm_local = 0.0 ; for ( I=Istart ; I<Iend ; I++ ) { p = I+1 ; get_ijk(p,&i,&j,&k) ; phi[i][j][k] += Vecx_local[I-Istart] ; norm_local += phi[i][j][k]*phi[i][j][k] ; } ierr = VecRestoreArray(Vecx,&Vecx_local) ; CHKERRQ(ierr) ; // Check Convergence MPI_Allreduce(&norm_local,&norm,1,MPI_DOUBLE,MPI_SUM,PETSC_COMM_WORLD) ; norm = sqrt(norm) ; ierr = PetscPrintf(PETSC_COMM_WORLD,"Poisson Iteration %d : Norm of phi = %le, KSP_Iter_No = %d\n",iter,norm,no_ksp_its) ; CHKERRQ(ierr) ; if ( fabs(norm-norm_old) < norm*CP.ConvEps ) break ; else norm_old = norm ; // Transfer intermediate phi mpi_transfer_phi(phi,node,np,Istart,Iend) ; } // Finalize int i0,i1 ; get_ijk(Istart+1,&i0,&j,&k) ; get_ijk(Iend,&i1,&j,&k) ; copy_R3mtx(Phi,phi,i0-1,i1+1,N.y0,N.y1,N.z0,N.z1) ; fix_corners(Phi,local_x0,local_x1) ; // Print Midline Potential if ( GetPRINT_MidPotFlag() ) { char fn[100] ; void print_midline_potential_plain() ; sprintf(fn,"mpot.r-Vd%.2lf-Vg%.2lf",GetDrainVoltage(),GetGateVoltage()) ; print_midline_potential_plain(fn,0) ; } return 0 ; } void mpi_transfer_phi(double ***phi,int node, int np, int Istart, int Iend) { int tag1,tag2,p0,n,ntrans,data_size,sum_transmitted ; int trans_size = GetTransSize() ; MPI_Status status ; int y0 = N.y0-1 ; int z0 = N.z0-1 ; int y1 = N.y1+1 ; int z1 = N.z1+1 ; int Ns = (y1-y0+1)*(z1-z0+1) ; int i0,j0,k0,i1,j1,k1 ; get_ijk(Istart+1,&i0,&j0,&k0) ; get_ijk(Iend+1,&i1,&j1,&k1) ; data_size = Ns ; ntrans = data_size/trans_size ; if ( node-1>=0 ) { p0 = 0 ; sum_transmitted = 0 ; tag1 = 1 ; tag2 = 2 ; for ( n=1 ; n<=ntrans ; n++ ) { MPI_Send(&phi[i0][j0][k0]+p0,trans_size,MPI_DOUBLE,node-1,tag1,PETSC_COMM_WORLD) ; MPI_Recv(&phi[i0][j0][k0]-Ns+p0,trans_size,MPI_DOUBLE,node-1,tag2,PETSC_COMM_WORLD,&status) ; p0 += trans_size ; sum_transmitted += trans_size ; tag1 += 2 ; tag2 += 2 ; } MPI_Send(&phi[i0][j0][k0]+p0,data_size-sum_transmitted,MPI_DOUBLE,node-1,tag1,PETSC_COMM_WORLD) ; MPI_Recv(&phi[i0][j0][k0]-Ns+p0,data_size-sum_transmitted,MPI_DOUBLE,node-1,tag2,PETSC_COMM_WORLD,&status) ; } if ( node+1<np ) { p0 = 0 ; sum_transmitted = 0 ; tag1 = 1 ; tag2 = 2 ; for ( n=1 ; n<=ntrans ; n++ ) { MPI_Send(&phi[i1][j1][k1]-Ns+p0,trans_size,MPI_DOUBLE,node+1,tag2,PETSC_COMM_WORLD) ; MPI_Recv(&phi[i1][j1][k1]+p0,trans_size,MPI_DOUBLE,node+1,tag1,PETSC_COMM_WORLD,&status) ; p0 += trans_size ; sum_transmitted += trans_size ; tag1 += 2 ; tag2 += 2 ; } MPI_Send(&phi[i1][j1][k1]-Ns+p0,data_size-sum_transmitted,MPI_DOUBLE,node+1,tag2,PETSC_COMM_WORLD) ; MPI_Recv(&phi[i1][j1][k1]+p0,data_size-sum_transmitted,MPI_DOUBLE,node+1,tag1,PETSC_COMM_WORLD,&status) ; } } void set_alphas_1() { int p,region ; double sum ; Region R ; double e_si = GetESi() ; for ( p=1 ; p<=Ntot ; p++ ) { region = GetRegion(&R,p) ; sum = 0.0 ; sum += (alpha_xplus[p] = falpha_xplus(p)) ; sum += (alpha_yplus[p] = falpha_yplus(p)) ; sum += (alpha_zplus[p] = falpha_zplus(p)) ; sum += (alpha_xminus[p] = falpha_xminus(p)) ; sum += (alpha_yminus[p] = falpha_yminus(p)) ; sum += (alpha_zminus[p] = falpha_zminus(p)) ; alpha_center[p] = -sum ; if ( GATE_CONTACT || CORNERS ) alpha_center[p] = -1.0 ; if ( SILICON ) alpha_q0e[p] = NANOM*NANOM*q0/e_si ; else alpha_q0e[p] = 0.0 ; } } void set_alphas_2() { int p,i,j,k,region ; Region R ; double ***Phi = GetPot() ; double phi_gate = GetPhi_Gate() ; for ( p=1 ; p<=Ntot ; p++ ) { region = GetRegion(&R,p) ; if ( GATE_CONTACT ) alpha_const[p] = phi_gate ; else if ( CORNERS ) { get_ijk(p,&i,&j,&k) ; alpha_const[p] = Phi[i][j][k] ; } else alpha_const[p] = 0.0 ; } } double falpha_xplus(int p) { int i,j,k,region ; double *hx,*hy,*hz,e_ox,e_si ; Region R ; hx = GetHx() ; hy = GetHy() ; hz = GetHz() ; e_ox = GetEOx() ; e_si = GetESi() ; get_ijk(p,&i,&j,&k) ; region = GetRegion(&R,p) ; if ( BULK ) return(2.0/(hx[i]+hx[i-1])/hx[i]) ; if ( SOURCE_WALL ) return(1.0) ; if ( SOURCE_CONTACT ) return(1.0) ; return(0.0) ; } double falpha_xminus(int p) { int i,j,k,region ; double *hx,*hy,*hz,e_ox,e_si ; Region R ; hx = GetHx() ; hy = GetHy() ; hz = GetHz() ; e_ox = GetEOx() ; e_si = GetESi() ; get_ijk(p,&i,&j,&k) ; region = GetRegion(&R,p) ; if ( BULK ) return(2.0/(hx[i]+hx[i-1])/hx[i-1]) ; if ( DRAIN_WALL ) return(1.0) ; if ( DRAIN_CONTACT ) return(1.0) ; return(0.0) ; } double falpha_yplus(int p) { int i,j,k,region ; double *PY,*hy,e_ox,e_si ; double hj,hjm1,y,yc,zc ; Region R ; PY = GetPY() ; hy = GetHy() ; e_ox = GetEOx() ; e_si = GetESi() ; get_ijk(p,&i,&j,&k) ; region = GetRegion(&R,p) ; hj = hy[j] ; hjm1 = hy[j-1] ; if ( BULK ) return(2.0/(hj+hjm1)/hj) ; if ( LEFT_INTERFACE ) return(e_si/(e_ox*hj)) ; if ( RIGHT_INTERFACE ) return(1.0/hj) ; if ( LEFT_WALL ) return(1.0) ; return(0.0) ; } double falpha_yminus(int p) { int i,j,k,region ; double *PY,*hy,e_ox,e_si ; double hj,hjm1,y,yc,zc ; Region R ; hy = GetHy() ; e_ox = GetEOx() ; e_si = GetESi() ; get_ijk(p,&i,&j,&k) ; region = GetRegion(&R,p) ; hj = hy[j] ; hjm1 = hy[j-1] ; if ( BULK ) return(2.0/(hj+hjm1)/hjm1) ; if ( LEFT_INTERFACE ) return(1.0/hjm1) ; if ( RIGHT_INTERFACE ) return(e_si/(e_ox*hjm1)) ; if ( RIGHT_WALL ) return(1.0) ; return(0.0) ; } double falpha_zplus(int p) { int i,j,k,region ; double *PZ,*hz,e_ox,e_si ; double hk,hkm1,z,yc,zc ; Region R ; hz = GetHz() ; e_ox = GetEOx() ; e_si = GetESi() ; get_ijk(p,&i,&j,&k) ; region = GetRegion(&R,p) ; hk = hz[k] ; hkm1 = hz[k-1] ; if ( BULK ) return(2.0/(hk+hkm1)/hk) ; if ( TOP_INTERFACE ) return(e_si/(e_ox*hk)) ; if ( BOTT_INTERFACE ) return(1.0/hk) ; if ( TOP_WALL ) return(1.0) ; return(0.0) ; } double falpha_zminus(int p) { int i,j,k,region ; double *PZ,*hz,e_ox,e_si ; double hk,hkm1,z,yc,zc ; Region R ; hz = GetHz() ; e_ox = GetEOx() ; e_si = GetESi() ; get_ijk(p,&i,&j,&k) ; region = GetRegion(&R,p) ; hk = hz[k] ; hkm1 = hz[k-1] ; if ( BULK ) return(2.0/(hk+hkm1)/hkm1) ; if ( TOP_INTERFACE ) return(1.0/hkm1) ; if ( BOTT_INTERFACE ) return(e_si/(e_ox*hkm1)) ; if ( BOTT_WALL ) return(1.0) ; return(0.0) ; } double Fnn(p,nfunc) int p ; double (*nfunc)() ; { int i,j,k ; double fv,***phi,exp(),GetDoping() ; phi = GetPhiKth() ; get_ijk(p,&i,&j,&k) ; fv = alpha_xminus[p]*phi[i-1][j][k] + alpha_xplus[p]*phi[i+1][j][k] \ + alpha_yminus[p]*phi[i][j-1][k] + alpha_yplus[p]*phi[i][j+1][k] \ + alpha_zminus[p]*phi[i][j][k-1] + alpha_zplus[p]*phi[i][j][k+1] \ + alpha_center[p]*phi[i][j][k] + alpha_const[p] \ + alpha_q0e[p]*(-(*nfunc)(i,j,k)-GetDoping(p)) ; return(-fv) ; } double DFnn(p,dnfunc) int p ; double (*dnfunc)() ; { int i,j,k ; double ***phi,exp() ; phi = GetPhiKth() ; get_ijk(p,&i,&j,&k) ; return(alpha_center[p]+alpha_q0e[p]*(-(*dnfunc)(i,j,k))) ; } void poisson_memory_allocation() { alpha_xplus = dvector(1,Ntot) ; alpha_yplus = dvector(1,Ntot) ; alpha_zplus = dvector(1,Ntot) ; alpha_xminus = dvector(1,Ntot) ; alpha_yminus = dvector(1,Ntot) ; alpha_zminus = dvector(1,Ntot) ; alpha_center = dvector(1,Ntot) ; alpha_const = dvector(1,Ntot) ; alpha_q0e = dvector(1,Ntot) ; } void poisson_free_memory() { free_dvector(alpha_xplus, 1,Ntot) ; free_dvector(alpha_yplus, 1,Ntot) ; free_dvector(alpha_zplus, 1,Ntot) ; free_dvector(alpha_xminus,1,Ntot) ; free_dvector(alpha_yminus,1,Ntot) ; free_dvector(alpha_zminus,1,Ntot) ; free_dvector(alpha_center,1,Ntot) ; free_dvector(alpha_const, 1,Ntot) ; free_dvector(alpha_q0e, 1,Ntot) ; } #define tiny 1.0e-06 int GetRegion(Region *PR, int p ) { int i,j,k,l,jj,kk,region ; double y,z,yc,zc,radius_cr ; double *PY = GetPY() ; double *PZ = GetPZ() ; Dimen D = GetDimen() ; PoiParam P = GetPoiParam() ; Region R ; int GetRegion_Bulk() ; *PR = GetR_() ; R = *PR ; get_ijk(p,&i,&j,&k) ; if ( (i==N.x0 && j==N.y0) || (i==N.x0 && j==N.y1) || \ (i==N.x0 && k==N.z0) || (i==N.x0 && k==N.z1) || \ (i==N.x1 && j==N.y0) || (i==N.x1 && j==N.y1) || \ (i==N.x1 && k==N.z0) || (i==N.x1 && k==N.z1) || \ (j==N.y0 && k==N.z0) || (j==N.y0 && k==N.z1) || \ (j==N.y1 && k==N.z0) || (j==N.y1 && k==N.z1) ) { region = R._CORNERS ; return(region) ; } if ( i==N.x0 ) { // SOURCE if ( j<N.ya || j>N.yb || k<N.za || k>N.zb ) { region = R._SOURCE_WALL ; return(region) ; } else region = R._SOURCE_CONTACT ; } if ( i==N.x1 ) { // DRAIN if ( j<N.ya || j>N.yb || k<N.za || k>N.zb ) { region = R._DRAIN_WALL ; return(region) ; } else region = R._DRAIN_CONTACT ; } if ( i<N.xgate0 || i>N.xgate1 ) { if ( j==N.y0 ) { region = R._LEFT_WALL ; return(region) ; } if ( j==N.y1 ) { region = R._RIGHT_WALL ; return(region) ; } if ( k==N.z0 ) { region = R._TOP_WALL ; return(region) ; } if ( k==N.z1 ) { region = R._BOTT_WALL ; return(region) ; } } if ( i>=N.xgate0 && i<=N.xgate1 ) { // GATE if ( k==N.z0 ) { region = R._GATE_CONTACT ; return(region) ; } if ( k==N.z1 ) { if ( j<=N.ygate0 || j>=N.ygate1 ) region = R._GATE_CONTACT ; else region = R._BOTT_WALL ; return(region) ; } if ( j==N.y0 ) { if ( k<=N.zgate ) region = R._GATE_CONTACT ; else region = R._LEFT_WALL ; return(region) ; } if ( j==N.y1 ) { if ( k<=N.zgate ) region = R._GATE_CONTACT ; else region = R._RIGHT_WALL ; return(region) ; } } // BULK region = GetRegion_Bulk(i,j,k) ; if ( i==N.x0 ) { if ( OXIDE ) region = R._SOURCE_WALL ; else region = R._SOURCE_CONTACT ; } else if ( i<N.xa ) { if ( CHANNEL_SILICON ) region = R._JUNCTION_SILICON ; } else if ( i>N.xb && i<N.x1 ) { if ( CHANNEL_SILICON ) region = R._JUNCTION_SILICON ; } else if ( i==N.x1 ) { if ( OXIDE ) region = R._DRAIN_WALL ; else region = R._DRAIN_CONTACT ; } return(region) ; } int GetRegion_Bulk(int i, int j, int k) { int region,jj,kk,l ; Region R = GetR_() ; if ( k==N.za && (j>N.ya && j<N.yb) ) { region = R._TOP_INTERFACE ; return(region) ; } else if ( k==N.zb && (j>N.ya && j<N.yb) ) { region = R._BOTT_INTERFACE ; return(region) ; } else if ( j==N.ya && (k>N.za && k<N.zb) ) { region = R._LEFT_INTERFACE ; return(region) ; } else if ( j==N.yb && (k>N.za && k<N.zb) ) { region = R._RIGHT_INTERFACE ; return(region) ; } else if ( k<=N.za || k>=N.zb || j<=N.ya || j>=N.yb ) { region = R._OXIDE ; return(region) ; } else { region = R._CHANNEL_SILICON ; return(region) ; } } #undef tiny void get_ijk(p,iv,jv,kv) int p,*iv,*jv,*kv ; { int pp ; *iv = (p-1)/(N.y*N.z) ; pp = p-(*iv)*N.y*N.z ; *jv = (pp-1)/N.z ; *kv = pp-(*jv)*N.z-1 ; } int get_p(int i, int j, int k) { return(i*N.y*N.z+j*N.z+k+1) ; } void set_null_out_of_bound() { int i,j,k ; double ***Phi = GetPot() ; for ( j=N.y0-1 ; j<=N.y1+1 ; j++ ) for ( k=N.z0-1 ; k<=N.z1+1 ; k++ ) { Phi[N.x0-1][j][k] = 0.0 ; Phi[N.x1+1][j][k] = 0.0 ; } for ( i=N.x0-1 ; i<=N.x1+1 ; i++ ) for ( k=N.z0-1 ; k<=N.z1+1 ; k++ ) { Phi[i][N.y0-1][k] = 0.0 ; Phi[i][N.y1+1][k] = 0.0 ; } for ( i=N.x0-1 ; i<=N.x1+1 ; i++ ) for ( j=N.y0-1 ; j<=N.y1+1 ; j++ ) { Phi[i][j][N.z0-1] = 0.0 ; Phi[i][j][N.z1+1] = 0.0 ; } } void fix_corners(double ***Phi, int local_x0, int local_x1) { int i,j,k ; // Taking care of Corner Points if ( local_x0 == N.x0 ) { for ( j=N.y0 ; j<=N.y1 ; j++ ) { Phi[local_x0][j][N.z0] = Phi[local_x0][j][N.z0+1] ; Phi[local_x0][j][N.z1] = Phi[local_x0][j][N.z1-1] ; } for ( k=N.z0 ; k<=N.z1 ; k++ ) { Phi[local_x0][N.y0][k] = Phi[local_x0][N.y0+1][k] ; Phi[local_x0][N.y1][k] = Phi[local_x0][N.y1-1][k] ; } } if ( local_x1 == N.x1 ) { for ( j=N.y0 ; j<=N.y1 ; j++ ) { Phi[local_x1][j][N.z0] = Phi[local_x1][j][N.z0+1] ; Phi[local_x1][j][N.z1] = Phi[local_x1][j][N.z1-1] ; } for ( k=N.z0 ; k<=N.z1 ; k++ ) { Phi[local_x1][N.y0][k] = Phi[local_x1][N.y0+1][k] ; Phi[local_x1][N.y1][k] = Phi[local_x1][N.y1-1][k] ; } } for ( i=local_x0 ; i<=local_x1 ; i++ ) { Phi[i][N.y0][N.z0] = 0.5*(Phi[i][N.y0+1][N.z0]+Phi[i][N.y0][N.z0+1]) ; Phi[i][N.y0][N.z1] = 0.5*(Phi[i][N.y0+1][N.z1]+Phi[i][N.y0][N.z1-1]) ; Phi[i][N.y1][N.z0] = 0.5*(Phi[i][N.y1-1][N.z0]+Phi[i][N.y1][N.z0+1]) ; Phi[i][N.y1][N.z1] = 0.5*(Phi[i][N.y1-1][N.z1]+Phi[i][N.y1][N.z1-1]) ; } } <file_sep>LOCAL_MKL_LIB = -L/opt/intel/mkl/10.1.1.019/lib/em64t -lmkl_lapack -lmkl -lguide -lpthread CC = /opt/intel/Compiler/11.0/081/bin/intel64/icc CFLAGS = -g MANSEC = KSP MAIN = main.o init.o init_local.o definefn.o material_param.o device_structure.o read_poisson_input.o read_voltages_input.o read_simulation_list.o read_scattering_save_list.o\ initial_variable.o find_region.o source_drain_carrier_number.o \ init_kspace.o init_realspace.o random2.o electrons_initialization.o count_used_particles.o trapezoidal_weights.o Solved_2D_Schro_for_MSMC.o form_factor_calculation.o \ scattering_table.o init_free_flight.o multi_subbands_MC.o current_calculation.o emcd.o check_source_drain_contacts.o delete_particles.o electron_density_caculation.o \ velocity_energy_cumulative.o eigen_energy_correction.o save_results.o drift.o scattering.o save_potential_parameters_from_input_file.o save_potential_average.o \ initial_potential_doping.o logfile_PoissonInput.o POISSON = init_pot.o poisson3d.o define_poi.o doping.o SELFCONS = nq.o AUX = outs.o plain_outs.o MATH = my_util.o nrutil.o LINKLIB = $(LOCAL_MKL_LIB) -lm LIB = -lf2c -lm include ${PETSC_DIR}/bmake/common/base msmc: $(MAIN) $(POISSON) $(MTXH) $(NEGF) $(SELFCONS) $(AUX) $(MATH) $(DEBUG) chkopts -${CLINKER} -o $@ $(MAIN) $(POISSON) $(MTXH) $(NEGF) $(SELFCONS) $(AUX) $(MATH) $(DEBUG) $(LIB) ${PETSC_KSP_LIB} ${RP_LIB} $(LINKLIB) remove: rm -f *.o rm -f *.o* rm -f *.e* rm -f *.*~ rm -f msmc clean: rm -f *.r* rm -f *.dat rm -f *.txt rm -f *.log rm -f *.o rm -f *.o* rm -f *.e* rm -f *.*~ rm -f msmc <file_sep>/* **************************************************************************** This function is to INITIALIZE DEVICE STRUCTURE (1) defines source, drain, gate, etc. regions (2) defines different doping regions (3) defines mesh size (4) defines initial doping Starting date: Feb 09, 2010 Update: Feb 11, 2010 Latest update: April 29, 2010 (Them tham so de mapping voi 3D Poisson) ***************************************************************************** */ #include <stdio.h> #include <math.h> #include <string.h> #include "nrutil.h" #include "constants.h" #include "petscksp.h" // for Poisson 3D #include "nanowire.h" // for Poisson 3D static double mesh_size_x,mesh_size_y,mesh_size_z; static int Tox_mesh,Tbox_mesh,Wox_mesh; // do la number of points static int nx0, nxa, nxb, nx1;// so diem chia o tung vung cho truc x static int ny0, nya, nyb, ny1;// truc y static int nz0, nza, nzb, nz1;// truc z static int nxgate0, nxgate1; // so diem chia cho vi tri cua gate static double *doping_density; /* ****************** Reading device structure ********************************** */ void device_structure(){ // Goi ham cho Poisson 3D void SetDopingDensityFor(int convflag, char region, char doping_type, double doping_density); double GetDopingDensityFor(char region); char device_type[40];// NanowireFET char cvar; // for Poisson 3D. doping dang n, p hay i double LsdInput,LchInput,LgInput,ToxInput,TboxInput,WoxInput,TsiInput,WsiInput;// tu Input file la nm double Lsd,Lch,Lg,Tox,Tbox,Wox,Tsi,Wsi; // chuyen tu [nm] -> [m] double TgateInput, WgateInput; // for Poisson 3D int n_region; doping_density=dvector(1,3); //[1] S, [2] D; [3] Channel double *doping_densityInput = dvector(1,3); /* ******** READING DEVICE PARAMETER ********* */ FILE *f; char s[180]; f = fopen("Input.d","r"); if(f == NULL){printf("Can't open file Input.d\n"); return;} //printf("\n\n Reading #DEVICE_PARAMETER"); fscanf(f,"%s",s); // read the current row if(strcmp(s,"#DEVICE_PARAMETER")==0){ fscanf(f,"%*s %*s %s",device_type);// Xem kieu device_type la loai gi ! //printf("\n Device type is %s",device_type); // Hien tai chi la NanowireFET fscanf(f,"%*s %*s %lf",&LsdInput); //printf("\n Source/Drain length [nm] = %5.2lf", LsdInput); Lsd = LsdInput*1.0e-9; // [nm] -> [m] fscanf(f,"%*s %*s %lf",&LchInput); //printf("\n Channel length [nm] = %5.2lf", LchInput); Lch = LchInput*1.0e-9; // [m] fscanf(f,"%*s %*s %lf",&LgInput); //printf("\n Gate length[nm] = %5.2lf", LgInput); Lg = LgInput*1.0e-9; // [m] fscanf(f,"%*s %*s %lf",&ToxInput); //printf("\n Tox [nm] = %5.2lf", ToxInput); Tox = ToxInput*1.0e-9; // [m] fscanf(f,"%*s %*s %lf",&TboxInput); //printf("\n Tbox [nm] = %5.2lf", TboxInput); Tbox = TboxInput*1.0e-9; // [m] fscanf(f,"%*s %*s %lf",&WoxInput); //printf("\n Wox [nm] = %5.2lf",WoxInput); Wox = WoxInput*1.0e-9; // [m] fscanf(f,"%*s %*s %lf",&TsiInput); //printf("\n Tsi [nm] = %5.2lf",TsiInput); Tsi = TsiInput*1.0e-9; // [m] fscanf(f,"%*s %*s %lf",&WsiInput); //printf("\n Wsi [nm] = %5.2lf",WsiInput); Wsi = WsiInput*1.0e-9; // [m] fscanf(f,"%*s %*s %lf",&TgateInput); //printf("\n T_gate [nm] = %5.2lf", TgateInput); // Khong chuyen sang [m] vi chi dung de mapping cho Poisson 3D ma thoi fscanf(f,"%*s %*s %lf",&WgateInput); //printf("\n W_gate [nm] = %5.2lf", WgateInput); // Khong chuyen sang [m] vi chi dung de mapping cho Poisson 3D ma thoi fscanf(f,"%*s %*s %lf",&mesh_size_x); // dinh nghia do rong mesh size theo phuong x //printf("\n mesh_size_x [nm] = %5.2lf",mesh_size_x); mesh_size_x = mesh_size_x*1.0e-9; // [m] fscanf(f,"%*s %*s %lf",&mesh_size_y); //printf("\n mesh_size_y [nm] = %5.2lf",mesh_size_y); mesh_size_y = mesh_size_y*1.0e-9; // [m] fscanf(f,"%*s %*s %lf",&mesh_size_z); //printf("\n mesh_size_z [nm] = %5.2lf",mesh_size_z); mesh_size_z = mesh_size_z*1.0e-9; // [m] fscanf(f,"%*s %*s %d",&Tox_mesh); //printf("\n Number of point Tox_mesh = %d",Tox_mesh); fscanf(f,"%*s %*s %d",&Tbox_mesh); //printf("\n Number of point Tbox_mesh= %d",Tbox_mesh); fscanf(f,"%*s %*s %d",&Wox_mesh); //printf("\n Number of point Wox_mesh = %d",Wox_mesh); fscanf(f,"%*s %*s %d",&n_region); //total_number_of_active_region //printf("\n n_region = %d",n_region); // Doping at Source fscanf(f,"%*s %*s %c", &cvar); //printf("\n Source doping type = %c",cvar); fscanf(f,"%*s %*s %lf",&doping_densityInput[1]); //Source //printf("\n Source doping </cm3> = %5.1le",doping_densityInput[1]); doping_density[1] = doping_densityInput[1]*1.0e+6; // [/cm3] -> [1/m3] SetDopingDensityFor(1,'s',cvar,doping_densityInput[1]);// cho Poisson 3D // Doping at Drain fscanf(f,"%*s %*s %c", &cvar); //printf("\n Drain doping type = %c",cvar); fscanf(f,"%*s %*s %lf",&doping_densityInput[2]); // Drain //printf("\n Drain doping </cm3> = %5.1le",doping_densityInput[2]); doping_density[2] = doping_densityInput[2]*1.0e+6; // [/cm3] -> [1/m3] SetDopingDensityFor(1,'d',cvar,doping_densityInput[2]);// Cho Poisson 3D // Doping at Channel fscanf(f,"%*s %*s %c", &cvar); //printf("\n Channel doping type = %c",cvar); fscanf(f,"%*s %*s %lf",&doping_densityInput[3]); // Channel //printf("\n Channel doping </cm3> = %5.2le",doping_densityInput[3]); doping_density[3] = doping_densityInput[3]*1.0e+6;// [/cm3] -> [1/m3] SetDopingDensityFor(1,'c',cvar,doping_densityInput[3]);// Cho 3D Poisson // Cua GS thi doping gia tri o Input file la + hay - thi luc vao deu duoc fabs() fclose(f); } // End of if(strcmp(s,"#DEVICE_PARAMETER")==0){ /* ******** END OF Reading #DEVICE_PARAMETER********* */ /* Specify reference points for source, drain and channel regions and junction depth and oxide region (bellow gate), ect. */ // Theo phuong x nx0 = 0; // goc TAO DO nxa = nx0 + (int)(Lsd/mesh_size_x + 0.5);// (int)(50.8)=50 nxb = nxa + (int)(Lch/mesh_size_x + 0.5); nx1 = nxb + (int)(Lsd/mesh_size_x + 0.5); //printf("\n nx0=%d, nxa=%d, nxb=%d, nx1=%d",nx0, nxa, nxb, nx1); // Theo phuong y ny0 = 0; // goc toa do nya = Wox_mesh; nyb = nya + (int)(Wsi/mesh_size_y + 0.5); ny1 = nyb + Wox_mesh; //printf("\n ny0=%d, nya=%d, nyb=%d, ny1=%d",ny0, nya, nyb, ny1); // Theo phuong z nz0 = 0; // goc toa do nza = Tox_mesh; nzb = nza + (int)(Tsi/mesh_size_z + 0.5); nz1 = nzb + Tbox_mesh; //printf("\n nz0=%d, nza=%d, nzb=%d, nz1=%d",nz0, nza, nzb, nz1); // Toa do cho gate double x3 = Lsd+Lch+Lsd; // do dai device double x2 = x3 - Lg; nxgate0 = (int)(0.5*x2/mesh_size_x + 0.5); double x4 = x3 + Lg; nxgate1 = (int)(0.5*x4/mesh_size_x + 0.5); //printf("\n nxgate0=%d, nxgate1=%d",nxgate0, nxgate1); // Khi Lg=Lch thi nxgate0=nxa, nxgate1=nxb: Cach Kiem tra cong thuc tinh dung hay sai // Mapping for 3D Poisson Dimen *D; PoiNum *N; D = PGetDimen(); N = PGetPoiNum(); D->Lsrc = LsdInput; // do dai Source N->Mx_src = (int)(Lsd/mesh_size_x + 0.5); // so diem chia o Source D->Lchannel = LchInput; // do dai channel length N->Mx_channel = (int)(Lch/mesh_size_x + 0.5); // so diem chia cho Lch D->Tox = ToxInput; N->Mz_ox = Tox_mesh; D->Tsi = TsiInput; N->Mz_si = (int)(Tsi/mesh_size_z + 0.5); D->Tbox = TboxInput; N->Mz_box = Tbox_mesh; D->Wox = WoxInput; N->My_ox = Wox_mesh; D->Wsi = WsiInput; N->My_si = (int)(Wsi/mesh_size_y + 0.5); D->Lgate = LgInput; D->Tgate = TgateInput; D->Wgate = WgateInput; // Kiem tra mapping for 3D Poisson //printf("\n Checking mapping for 3D Poisson at device_structure()"); //printf("\n Doping at Source[1/m3] =%le",GetDopingDensityFor('s')); //printf("\n Doping at Channel[1/m3]=%le",GetDopingDensityFor('c')); //printf("\n Doping at Drain[1/m3] =%le",GetDopingDensityFor('d')); //printf("\n Lsource[NoUnit] D->Lsrc =%f, Number of points N->Mx_src =%d",D->Lsrc,N->Mx_src); //printf("\n Lchannel[NoUnit]D->Lchannel =%f, Number of points N->Mx_channel =%d",D->Lchannel,N->Mx_channel); //printf("\n Tox[NoUnit] D->Tox =%f, Number of points N->Mz_ox =%d",D->Tox,N->Mz_ox); //printf("\n Tsi[NoUnit] D->Tsi =%f, Number of points N->Mz_si =%d",D->Tsi,N->Mz_si); //printf("\n Tbox[NoUnit] D->Tbox =%f, Number of points N->Mz_box =%d",D->Tbox,N->Mz_box); //printf("\n Wox[NoUnit] D->Wox =%f, Number of points N->My_ox =%d",D->Wox,N->My_ox); //printf("\n Wsi[NoUnit] D->Wsi =%f, Number of points N->My_si =%d",D->Wsi,N->My_si); //printf("\n Lgate[NoUnit] D->Lgate =%f",D->Lgate); //printf("\n Tgate[NoUnit] D->Tgate =%f",D->Tgate); //printf("\n Wgate[NoUnit] D->Wgate =%f",D->Wgate); // Phan in ra o monitor khi rank=0 int myrank, mysize; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); MPI_Comm_size(MPI_COMM_WORLD,&mysize); if(myrank ==0){ printf("\n\n Reading DEVICE_PARAMETER"); printf("\n Device type is %s",device_type); // Hien tai chi la NanowireFET printf("\n Source/Drain length [nm] = %5.2lf", LsdInput); printf("\n Channel length [nm] = %5.2lf", LchInput); printf("\n Gate length[nm] = %5.2lf", LgInput); printf("\n Tox [nm] = %5.2lf", ToxInput); printf("\n Tbox [nm] = %5.2lf", TboxInput); printf("\n Wox [nm] = %5.2lf",WoxInput); printf("\n Tsi [nm] = %5.2lf",TsiInput); printf("\n Wsi [nm] = %5.2lf",WsiInput); printf("\n T_gate [nm] = %5.2lf", TgateInput); printf("\n W_gate [nm] = %5.2lf", WgateInput); printf("\n mesh_size_x [nm] = %5.2lf",mesh_size_x/1.0e-9); printf("\n mesh_size_y [nm] = %5.2lf",mesh_size_y/1.0e-9); printf("\n mesh_size_z [nm] = %5.2lf",mesh_size_z/1.0e-9); printf("\n Number of point Tox_mesh = %d",Tox_mesh); printf("\n Number of point Tbox_mesh= %d",Tbox_mesh); printf("\n Number of point Wox_mesh = %d",Wox_mesh); printf("\n n_region = %d",n_region); printf("\n Source doping </cm3> = %5.1le",doping_densityInput[1]); printf("\n Drain doping </cm3> = %5.1le",doping_densityInput[2]); printf("\n Channel doping </cm3> = %5.2le",doping_densityInput[3]); printf("\n nx0=%d, nxa=%d, nxb=%d, nx1=%d",nx0, nxa, nxb, nx1); printf("\n ny0=%d, nya=%d, nyb=%d, ny1=%d",ny0, nya, nyb, ny1); printf("\n nz0=%d, nza=%d, nzb=%d, nz1=%d",nz0, nza, nzb, nz1); printf("\n nxgate0=%d, nxgate1=%d",nxgate0, nxgate1); }// End of if(myrank ==0) //Free local variable free_dvector(doping_densityInput,1,3); return; } // End of void device_structure(){ double Get_mesh_size_x(){ return mesh_size_x; } double Get_mesh_size_y(){ return mesh_size_y; } double Get_mesh_size_z(){ return mesh_size_z; } int Get_Tox_mesh(){ return Tox_mesh; } int Get_Tbox_mesh(){ return Tbox_mesh; } int Get_Wox_mesh(){ return Wox_mesh; } int Get_nx0(){ return nx0; } int Get_nxa(){ return nxa; } int Get_nxb(){ return nxb ; } int Get_nx1(){ return nx1 ; } int Get_ny0(){ return ny0 ; } int Get_nya(){ return nya ; } int Get_nyb(){ return nyb ; } int Get_ny1(){ return ny1 ; } int Get_nz0(){ return nz0 ; } int Get_nza(){ return nza ; } int Get_nzb(){ return nzb ; } int Get_nz1(){ return nz1 ; } int Get_nxgate0(){ return nxgate0 ; } int Get_nxgate1(){ return nxgate1 ; } // Chu y cho doping double *Get_doping_density(){ return (doping_density); } <file_sep>/* **************************************************************** Ham de thuc hien viec tinh Form Factor cho tat ca cross-section, 3 cap valley pairs va tu subband n den subband m INPUT: + nx: s-th section - so luong tu 0 den nx_max + subband index n (1 den NSELECT) den m (1 den NSELECT) + Wave_s,v,n_(y,z) va Wave_s,v,m_(y,z) + So diem chia theo phuong y (tu 0 den ny_max) va z ( tu 0 den nz_max) OUTPUT: + FormFactor_s,n,m,v : 4D array. NOTE chi so v la 1 kieu ket hop cua Intra va Inter_Valley RAT CHU Y: Cai ta tinh duoc la CHUA normalize theo DON VI. De tinh theo DON VI ta CAN NHAN them 1.0e+18. Xem trang 92 Starting date: March 05, 2010 Update: March 10, 2010 (Big change) Latest update: March 15, 2010: Y nghia cua don vi dang 1/m2 hoac 1/cm2 ****************************************************************** */ #include <stdio.h> void form_factor_calculation(){ // Goi ham double *****Get_wave(); // Lay wave function tu 2D Schrodinger double **Get_trap_weights();// Lay phan cong thuc 1 va hang so cua cong thuc 2 trang 92 double ****Get_form_factor();// chua form factor // Local bien double *****wave = Get_wave(); double **trap_weights = Get_trap_weights(); double ****form_factor = Get_form_factor(); int Get_nx0(),Get_nx1(), Get_nya(),Get_nyb(),Get_nza(),Get_nzb(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nya = Get_nya(); int nyb = Get_nyb(); int nza = Get_nza(); int nzb = Get_nzb(); int nx_max = nx1-nx0; // int nx_max = Get_nx_max(); int ny_max = nyb - nya;// De thay doi it nhat co the int nz_max = nzb - nza; int Get_NSELECT(); int NSELECT = Get_NSELECT(); // Thuc hien int i,j; // chay cho so diem tren truc y, z int s,v,n,m;// section, valley, tu subband n den subband m double sum = 0.0; // Reset form_factor truoc moi lan vao for(s=nx0; s<=nx1; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(v=1; v<=9; v++){ form_factor[s][n][m][v] = 0.0; } } } } /* ***************************************************************************** Part I. + Acoustic phonon (Intra-Valley (Inter- and Intra-subband)) + Or g-process zero-order optical: do MAC DU no la Inter-Valley nhung xay ra o SAME axis nen subband energy va wave cung GIONG voi truong hop acoustic. ******************************************************************************* */ for(s=0; s<=nx_max; s++){ // chay cho tung section for(v=1; v<=3; v++){// chay cho 3 cap valley. Xem trang 96 for(n=1; n<=NSELECT; n++){ // chay cho subband n for(m=1; m<=NSELECT; m++){ // chay cho subband m sum =0.0; for(i=0; i<=ny_max; i++){ // chay cho diem tren truc y for(j=0; j<=nz_max; j++){// chay cho diem tren truc z sum = sum + trap_weights[i][j]*wave[s][v][n][i][j]*wave[s][v][n][i][j]*wave[s][v][m][i][j]*wave[s][v][m][i][j]; } // End of for(j=0; j<=nz_max; j++) }// End of for(i=0; i<=ny_max; i++) form_factor[s][n][m][v] = sum*1.0e+18; // Nhan them 1.0e+18 Xem trang 92 sum = 0.0; // de quay ve vong lap ke tiep }// End of for(m=1; m<=NSELECT;m++) }// End of for(n=1; n<=NSELECT; n++) }// End of for(v=1; v<=3; v++) }// End of for(s=0; s<=nx_max; s++) /* **************************************************************************** Part II. f-process Non-polar Optical phonon (Inter-Valley (Inter- and Intra-subband)) (trang 99) *******************************************************************************/ // II.1. Tu valley pair 1 (v=1) --> Valley pair 2 sum = 0.0; for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ // chay cho subband n for(m=1; m<=NSELECT; m++){ // chay cho subband m for(i=0; i<=ny_max; i++){ // chay cho diem tren truc y for(j=0; j<=nz_max; j++){// chay cho diem tren truc z sum = sum + trap_weights[i][j]*wave[s][1][n][i][j]*wave[s][1][n][i][j]*wave[s][2][m][i][j]*wave[s][2][m][i][j]; } // End of for(j=0; j<=nz_max; j++) }// End of for(i=0; i<=ny_max; i++) form_factor[s][n][m][4] = sum*1.0e+18;// Nhan 1.0e+18 xem trang 92. De normalized lai theo m2 sum = 0.0; // de quay ve vong lap ke tiep }// End of for(m=1; m<=NSELECT;m++) }// End of for(n=1; n<=NSELECT; n++) }// End of for(s=0; s<=nx_max; s++) // End of II.1. Tu valley 1 (v=1) --> Valley 2 (v=2) // II.2. Tu valley 1 (v=1) --> Valley 3 (v=3) sum = 0.0; for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(i=0; i<=ny_max; i++){ for(j=0; j<=nz_max; j++){ sum = sum + trap_weights[i][j]*wave[s][1][n][i][j]*wave[s][1][n][i][j]*wave[s][3][m][i][j]*wave[s][3][m][i][j]; } // End of for(j=0; j<=nz_max; j++) }// End of for(i=0; i<=ny_max; i++) form_factor[s][n][m][5] = sum*1.0e+18; sum = 0.0; // de quay ve vong lap ke tiep }// End of for(m=1; m<=NSELECT;m++) }// End of for(n=1; n<=NSELECT; n++) }// End of for(s=0; s<=nx_max; s++) // End of II.2. Tu valley 1 (v=1) --> Valley 3 (v=3) // II.3. Tu valley 2 (v=2) --> Valley 1 (v=1) sum = 0.0; for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(i=0; i<=ny_max; i++){ for(j=0; j<=nz_max; j++){ sum = sum + trap_weights[i][j]*wave[s][2][n][i][j]*wave[s][2][n][i][j]*wave[s][1][m][i][j]*wave[s][1][m][i][j]; } // End of for(j=0; j<=nz; j++) }// End of for(i=0; i<=ny; i++) form_factor[s][n][m][6] = sum*1.0e+18; sum = 0.0; // de quay ve vong lap ke tiep }// End of for(m=1; m<=NSELECT;m++) }// End of for(n=1; n<=NSELECT; n++) }// End of for(s=0; s<=nx; s++) // End of II.3. Tu valley 2 (v=2) --> Valley 1 (v=1) // II.4. Tu valley 2 (v=2) --> Valley 3 (v=3) sum = 0.0; for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(i=0; i<=ny_max; i++){ for(j=0; j<=nz_max; j++){ sum = sum + trap_weights[i][j]*wave[s][2][n][i][j]*wave[s][2][n][i][j]*wave[s][3][m][i][j]*wave[s][3][m][i][j]; } // End of for(j=0; j<=nz; j++) }// End of for(i=0; i<=ny; i++) form_factor[s][n][m][7] = sum*1.0e+18; sum = 0.0; // de quay ve vong lap ke tiep }// End of for(m=1; m<=NSELECT;m++) }// End of for(n=1; n<=NSELECT; n++) }// End of for(s=0; s<=nx; s++) // End of II.4. Tu valley 2 (v=2) --> Valley 3 (v=3) // II.5. Tu valley 3 (v=3) --> Valley 1 (v=1) sum = 0.0; for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(i=0; i<=ny_max; i++){ for(j=0; j<=nz_max; j++){ sum = sum + trap_weights[i][j]*wave[s][3][n][i][j]*wave[s][3][n][i][j]*wave[s][1][m][i][j]*wave[s][1][m][i][j]; } // End of for(j=0; j<=nz; j++) }// End of for(i=0; i<=ny; i++) form_factor[s][n][m][8] = sum*1.0e+18; sum = 0.0; // de quay ve vong lap ke tiep }// End of for(m=1; m<=NSELECT;m++) }// End of for(n=1; n<=NSELECT; n++) }// End of for(s=0; s<=nx; s++) // End of II.5. Tu valley 3 (v=3) --> Valley 1 (v=1) // II.6. Tu valley 3 (v=3) --> Valley 2 (v=2) sum = 0.0; for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(i=0; i<=ny_max; i++){ for(j=0; j<=nz_max; j++){ sum = sum + trap_weights[i][j]*wave[s][3][n][i][j]*wave[s][3][n][i][j]*wave[s][2][m][i][j]*wave[s][2][m][i][j]; } // End of for(j=0; j<=nz; j++) }// End of for(i=0; i<=ny; i++) form_factor[s][n][m][9] = sum*1.0e+18; sum = 0.0; // de quay ve vong lap ke tiep }// End of for(m=1; m<=NSELECT;m++) }// End of for(n=1; n<=NSELECT; n++) }// End of for(s=0; s<=nx; s++) return; }//End of void form_factor_calculation //************************************************************************ /* **************************************************************** De in form factor INPUT: + nx: s-th section - so luong tu 0 den nx_max + subband index n (1 den NSELECT) den m (1 den NSELECT) + FormFactor_s,v,n->m OUTPUT: + In ra FormFactor_s,n,m,v tren man hinh Starting date: March 05, 2010 Latest update: March 10, 2010 ****************************************************************** */ void printf_form_factor_calculation(int nx, int NSELECT){ // Goi ham double ****Get_form_factor();// chua form factor // Local bien double ****form_factor = Get_form_factor(); // Thuc hien int s,v,n,m;// section, valley, tu subband n den subband m for(s=0; s<=nx; s++){ // chay cho tung section for(n=1; n<=NSELECT; n++){ // chay cho subband n for(m=1; m<=NSELECT; m++){ // chay cho subband m for(v=1; v<=9; v++){// 1 den 3: Acoustic; 4 den 9: Optical Phonon printf("\n form_factor[%d][%d][%d][%d]=%le",s,n,m,v,form_factor[s][n][m][v]); } } } } } // End of void printf_form_factor_calculation //************************************************************************ /* **************************************************************** De SAVE form factor vao trong 1 file INPUT: + nx: s-th section - so luong tu 0 den nx_max + subband index n (1 den NSELECT) den m (1 den NSELECT) + FormFactor_s,n,m,v OUTPUT: + SAVE FormFactor_s,n,m,v Vao File Form_factor.dat Starting date: March 06, 2010 Latest update: March 10, 2010 ****************************************************************** */ void save_form_factor_calculation(int s_th, char *fn){ double ****Get_form_factor();// chua form factor double ****form_factor = Get_form_factor(); int Get_NSELECT(); int NSELECT = Get_NSELECT(); // Thuc hien // To store Form factor FILE *f; f = fopen(fn,"w"); // "w" neu tep ton tai no se bi xoa //f = fopen("Form_factor.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL) { printf("\n Cannot open file at save_form_factor_calculation.c"); return ; } fprintf(f,"\n #s_th n m v form_factor[1/m2] \n"); int v,n,m;// section, valley, tu subband n den subband m for(n=1; n<=NSELECT; n++){ // chay cho subband n for(m=1; m<=NSELECT; m++){ // chay cho subband m for(v=1; v<=9; v++){// Kieu ket hop Intra- va Inter-Valley fprintf(f,"%d %d %d %d %le \n",s_th,n,m,v,form_factor[s_th][n][m][v]); } } } fclose(f); return; } // End of void save_form_factor_calculation <file_sep>/* *********************************************************************** To initialise position for each particle (electron) based on node location 1D transport direction only nen chi can tham so i la du Starting date: Feb 22, 2010 Update: Feb 22, 2010 Update: March 28, 2010 (Giai thich TAI SAO khong update cho y va z) + Vi hat chi chay tren x direction ma thoi + Hat co scattering theo phuong x, NHUNG no chi CO THE lam thay doi momentum, energy, valley hay subband ma thoi + Cach tinh charge density cung KHAC voi Semiclassical MC Latest update: May 06, 2010 (De phu hop voi 3D Poisson) ************************************************************************* */ #include <math.h> #include <stdio.h> void init_realspace(int ne,int i){ // Goi cac ham double **Get_p(); int Get_nx0(),Get_nx1(); long Get_idum(); float random2(long *idum); double Get_mesh_size_x(); // Cac bien local double **p = Get_p(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); long idum = Get_idum(); double mesh_size_x = Get_mesh_size_x(); // Thuc hien double device_length = ((double)(nx1-nx0))*mesh_size_x; double x_position=0.0,factor = 0.0;// Define particle coordinates based on grid location if((i!=nx0) && (i!= nx1)){ x_position = ((double)(i)+random2(&idum)-0.5) *mesh_size_x; goto L11; } else if(i==nx0){ x_position = 0.5*random2(&idum)*mesh_size_x; goto L11; } else { // if(i==nx1){ x_position = device_length-0.5*random2(&idum)*mesh_size_x; } L11: //Label: lam cac lenh tiep theo if(x_position <0.0) {x_position=-x_position;} if(x_position > device_length){ factor = fabs(x_position - device_length); x_position = device_length - factor; } // Map particle atributes p[ne][2] = x_position; // [m] //printf("\n Init real space x position=%le",x_position); //if(p[ne][2]>1.0e-8){printf("\n Ket qua: x=%le ",p[ne][2]); getch();} return; } <file_sep>#define SOURCE_CONTACT (region==R._SOURCE_CONTACT) #define DRAIN_CONTACT (region==R._DRAIN_CONTACT) #define GATE_CONTACT (region==R._GATE_CONTACT) #define TOP_INTERFACE (region==R._TOP_INTERFACE) #define BOTT_INTERFACE (region==R._BOTT_INTERFACE) #define LEFT_INTERFACE (region==R._LEFT_INTERFACE) #define RIGHT_INTERFACE (region==R._RIGHT_INTERFACE) #define TOP_WALL (region==R._TOP_WALL) #define BOTT_WALL (region==R._BOTT_WALL) #define LEFT_WALL (region==R._LEFT_WALL) #define RIGHT_WALL (region==R._RIGHT_WALL) #define SOURCE_WALL (region==R._SOURCE_WALL) #define DRAIN_WALL (region==R._DRAIN_WALL) #define CHANNEL_SILICON (region==R._CHANNEL_SILICON) #define JUNCTION_SILICON (region==R._JUNCTION_SILICON) #define SILICON (region==R._CHANNEL_SILICON || region==R._JUNCTION_SILICON ) #define OXIDE (region==R._OXIDE) #define BULK (SILICON || OXIDE ) #define INTERFACE (TOP_INTERFACE || BOTT_INTERFACE || LEFT_INTERFACE || RIGHT_INTERFACE ) #define CORNERS (region==R._CORNERS) <file_sep>/* **************************************************************** TO CREATE THE SCATTERING TABLE and then NORMALIZE Scattering mechanism: - Acoustic phonons - Zero-order Non-polar optical phonons - First-order Non-polar optical phonons (not yet) - Coulomb scattering (not yet) - Interface roughness scattering (not yet) CHU Y 1: flag_mech = 1 ==> Isotropic scattering process (acoustic or g-process) vi o g-process no xay ra o SAME axis nen cung xep vao loai nay flag_mech = 2 ==> Isotropic cho f-process (xay ra o DIFFRENT axis) flag_mech = 3 ==> Anistropic (vi du Coulomb scattering) CHU Y 2: Ro rang scattering se KHAC nhau o region KHAC nhau (vi du Coulomb scattering) Vay o MANG scat_table can 1 index cho region. (March 12, 2010: CHUA them vao) Starting date: March 11, 2010 Update: March 12, 2010 Update: March 23, 2010. SUA lai dang g-process Latest update: April 15, 2010. Gop ham Density_of_State_1D() vao ham scattering_table() De khong can su dung mang DOS1D => giam memory can dung khi chay chuong trinh ****************************************************************** */ #include <stdio.h> #include <math.h> #include "nrutil.h" #include "constants.h" void scattering_table(){ // Goi ham double *****Get_scat_table(); double ****Get_form_factor(); double ***Get_eig(); double Get_ml(),Get_mt(),Get_emax(); int Get_NSELECT(); // chay cho section va subband double Get_nonparabolicity_factor(),Get_hw0f_phonon(),Get_hw0g_phonon(); // Goi cac ham flag cho scattering int Get_flag_acoustic(),Get_flag_zero_order_optical(); int Get_flag_first_order_optical(),Get_flag_Coulomb(),Get_flag_Surface_roughness(); // Goi cac ham hang so double Get_constant_acoustic(); double Get_constant_optical_g_e(),Get_constant_optical_g_a(); double Get_constant_optical_f_e(),Get_constant_optical_f_a(); // Bien local double *****scat_table = Get_scat_table(); double ****form_factor = Get_form_factor(); double ***eig = Get_eig(); double ml = Get_ml(); // chi la gia tri ml, CHUA nhan voi m0 double mt = Get_mt(); double emax = Get_emax(); int Get_nx0(),Get_nx1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; // int nx_max = Get_nx_max(); int NSELECT = Get_NSELECT(); double af = Get_nonparabolicity_factor(); //printf("\n Nonparabolicity factor[1/eV] = %f",af); getchar(); double hw0f_phonon = Get_hw0f_phonon(); double hw0g_phonon = Get_hw0g_phonon(); // Cac bien cho flag: ADD cac loai Scattering NAO ? int flag_acoustic = Get_flag_acoustic(); int flag_zero_order_optical = Get_flag_zero_order_optical(); int flag_first_order_optical = Get_flag_first_order_optical(); int flag_Coulomb = Get_flag_Coulomb(); int flag_Surface_roughness = Get_flag_Surface_roughness(); // Cac bieb cho hang so double constant_acoustic = Get_constant_acoustic(); double constant_optical_g_e = Get_constant_optical_g_e(); double constant_optical_g_a = Get_constant_optical_g_a(); double constant_optical_f_e = Get_constant_optical_f_e(); double constant_optical_f_a = Get_constant_optical_f_a(); // Cu moi lan tinh scattering table thi ta reset no cho chac chan int s,v,n,m,e_step; for(s=nx0; s<=nx1; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(e_step=1; e_step<=n_lev; e_step++){ for(v=1; v<=21; v++){ scat_table[s][n][m][e_step][v]=0.0; } } } } } // Thuc hien double de=emax/(double)(n_lev); // energy interval double *E; E=dvector(1,n_lev); // [eV] Dinh nghia dai nang luong minh quan tam E di tu 1*de den "emax" // Neu di tu 0 thi se co loi. The hien phan kinetic cua electron truoc scattering for(e_step=1; e_step<=n_lev; e_step++){ E[e_step] = e_step*de; } double Ef = 0.0; // Ef trong cong thuc tinh DOS double theta = 0.0; // la de tinh ham step function trong cong thuc tinh DOS; double DOS_temp = 0.0;//DOS_temp la bien trung gian tinh DOS tranh dung mang nhu o version truoc double const_DOS_ml, const_DOS_mt; // Thanh phan dau tien cua DOS1D. Xem cong thuc 1 trang 93 const_DOS_ml = sqrt(ml*m0)/(2.0*sqrt(2.0)*pi*hbar*sqrt(q));//printf("\n const_DOS_ml = %le", const_DOS_ml); const_DOS_mt = sqrt(mt*m0)/(2.0*sqrt(2.0)*pi*hbar*sqrt(q));//printf("\n const_DOS_mt = %le", const_DOS_mt); getchar(); // I. Acoustic phonons scattering (Intra-Valley (Inter- and Intra-subband)) if(flag_acoustic==1){ // Include: Acoustic phonon <--Tinh gia tri scattering nay //m* = ml: Cap valley pair 1. Xem page 84 //v =1; // Cap valley pair 1, const_DOS_ml = sqrt(ml*m0)/(2.0*sqrt(2.0)*pi*hbar*sqrt(q)); for(s=0; s<=nx_max; s++){ // Cho moi section slice for(n=1; n<=NSELECT; n++){ // Scattering tu subband n-th for(m=1; m<=NSELECT; m++){ // den subband m-th for(e_step=1; e_step<=n_lev; e_step++){// cac buoc nang luong Ef = eig[s][1][n] - eig[s][1][m] + E[e_step];// [eV] printf("\n Ef = %le", Ef); // For acoustic phonon if(Ef > 0.0) { //ham step function -> Ef<0 thi theta=0, Ef>0 thi theta=1 theta = 1.0; DOS_temp = const_DOS_ml*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][1] = constant_acoustic*form_factor[s][n][m][1]*DOS_temp; //printf("\n scat_table[s][n][m][e_step][1] = %le",scat_table[s][n][m][e_step][1]); getchar(); } else {// Ef <0.0 //theta =0.0; DOS_temp =0.0 scat_table[s][n][m][e_step][1] = 0.0; } }// End of for(e_step=1; e_step<=n_lev; e_step++) } // End of for(m=1; m<=NSELECT; m++){ } // End of for(n=1; n<=NSELECT; n++) } // End of for(int s=0; s<=nx_max; s++){ // Cho moi section slice //m* = mt: Cap valley pair 2 va 3. Xem page 84, const_DOS_mt = sqrt(mt*m0)/(2.0*sqrt(2.0)*pi*hbar*sqrt(q)); for(s=0; s<=nx_max; s++){ // Cho moi section slice for(v=2; v<=3; v++){// v=2 va v=3: 2 cap valley pairs co cung mt for(n=1; n<=NSELECT; n++){ // Scattering tu subband n-th for(m=1; m<=NSELECT; m++){ // den subband m-th for(e_step=1; e_step<=n_lev; e_step++){// cac buoc nang luong Ef = eig[s][v][n] - eig[s][v][m] + E[e_step];// [eV] // For acoustic phonon if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][v] = constant_acoustic*form_factor[s][n][m][v]*DOS_temp; } else{// theta =0.0; DOS_temp = 0.0 scat_table[s][n][m][e_step][v] = 0.0; } }// End of for(e_step=1; e_step<=n_lev; e_step++) } // End of for(m=1; m<=NSELECT; m++){ } // End of for(n=1; n<=NSELECT; n++) }// for(v=2; v<=3; v++) } // End of for(s=0; s<=nx_max; s++){ // Cho moi section slice } // End of if(flag_acoustic==1) // End of Part I. Acoustic phonons scattering rate /* **************************************************************************** Part II. Non-polar Optical phonon (Inter-Valley (Inter- and Intra-subband)) f-process: tu Valley NAY den Valley KIA KHAC truc AXIS g-process: tu Valley NAY den Valley KIA CUNG truc Axis *******************************************************************************/ if(flag_zero_order_optical ==1){ // II.1. f-process // II.1.1. Tu valley pair 1 (v=1) --> Valley pair 2 (v=2): m* la mt // Chi so cho form factor la 4, chi so cho scat_table la tu 4-5 for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(e_step=1; e_step<=n_lev; e_step++){ // f-process ABSORPTION Ef = eig[s][1][n] - eig[s][2][m] + E[e_step]+ hw0f_phonon; if(Ef > 0.0) { theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][4] = constant_optical_f_a* form_factor[s][n][m][4]* DOS_temp; //printf("\n scat_table[s][n][m][e_step][4] = %le",scat_table[s][n][m][e_step][4]); getchar(); } else { //theta =0.0; DOS_temp = 0.0 scat_table[s][n][m][e_step][4] = 0.0; } //f-process EMISSION Ef = eig[s][1][n] - eig[s][2][m] + E[e_step] - hw0f_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][5] = constant_optical_f_e* form_factor[s][n][m][4]* DOS_temp; } else{ //theta =0.0; DOS_temp = 0.0 scat_table[s][n][m][e_step][5] = 0.0; } } // End of for(e_step=1; e_step<=n_lev; e_step++) } // End of for(m=1; m<=NSELECT; m++){ } // End of for(n=1; n<=NSELECT; n++) } // End of for(int s=0; s<=nx_max; s++){ // Cho moi section slice // End of II.1.1. Tu valley 1 (v=1) --> Valley 2 (v=2): m* la mt // II.1.2. Tu valley 1 (v=1) --> Valley 3 (v=3): m* la mt // Chi so cho form factor la 5, chi so cho scat_table la tu 6-7 for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(e_step=1; e_step<=n_lev; e_step++){ // f-process ABSORPTION Ef = eig[s][1][n] - eig[s][3][m] + E[e_step]+ hw0f_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][6] = constant_optical_f_a* form_factor[s][n][m][5]* DOS_temp; } else{//theta =0.0;DOS_temp=0.0 scat_table[s][n][m][e_step][6]=0.0; } //f-process EMISSION Ef = eig[s][1][n] - eig[s][3][m] + E[e_step] - hw0f_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][7] = constant_optical_f_e* form_factor[s][n][m][5]* DOS_temp; } else{//theta =0.0; DOS_temp = 0.0 scat_table[s][n][m][e_step][7]=0.0; } } // End of for(e_step=1; e_step<=n_lev; e_step++) } // End of for(m=1; m<=NSELECT; m++){ } // End of for(n=1; n<=NSELECT; n++) } // End of for(int s=0; s<=nx_max; s++){ // Cho moi section slice // End of II.1.2. Tu valley 1 (v=1) --> Valley 3 (v=3): m* la mt // II.1.3. Tu valley 2 (v=2) --> Valley 1 (v=1): m* la ml // Chi so cho form factor la 6, chi so cho scat_table la tu 8-9 for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(e_step=1; e_step<=n_lev; e_step++){ // f-process ABSORPTION Ef = eig[s][2][n] - eig[s][1][m] + E[e_step]+ hw0f_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_ml*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][8] = constant_optical_f_a* form_factor[s][n][m][6]* DOS_temp; } else{//theta =0.0; DOS_temp=0.0 scat_table[s][n][m][e_step][8]=0.0; } //f-process EMISSION Ef = eig[s][2][n] - eig[s][1][m] + E[e_step] - hw0f_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_ml*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][9] = constant_optical_f_e* form_factor[s][n][m][6]* DOS_temp; } else{//theta =0.0; DOS_temp = 0.0 scat_table[s][n][m][e_step][9]=0.0; } } // End of for(e_step=1; e_step<=n_lev; e_step++) } // End of for(m=1; m<=NSELECT; m++){ } // End of for(n=1; n<=NSELECT; n++) } // End of for(s=0; s<=nx_max; s++){ // Cho moi section slice // End of II.1.3. Tu valley 2 (v=2) --> Valley 1 (v=1): m* la ml // II.1.4. Tu valley 2 (v=2) --> Valley 3 (v=3): m* la mt for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(e_step=1; e_step<=n_lev; e_step++){ // f-process ABSORPTION Ef = eig[s][2][n] - eig[s][3][m] + E[e_step]+ hw0f_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][10] = constant_optical_f_a* form_factor[s][n][m][7]* DOS_temp; } else{//theta =0.0; DOS_temp = 0.0 scat_table[s][n][m][e_step][10]=0.0; } //f-process EMISSION Ef = eig[s][2][n] - eig[s][3][m] + E[e_step] - hw0f_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][11] = constant_optical_f_e* form_factor[s][n][m][7]* DOS_temp; } else{ //theta =0.0; DOS_temp = 0.0 scat_table[s][n][m][e_step][11]=0.0; } } // End of for(e_step=1; e_step<=n_lev; e_step++) } // End of for(m=1; m<=NSELECT; m++){ } // End of for(n=1; n<=NSELECT; n++) } // End of for(int s=0; s<=nx_max; s++){ // Cho moi section slice // End of II.1.4. Tu valley 2 (v=2) --> Valley 3 (v=3): m* la mt // II.1.5. Tu valley 3 (v=3) --> Valley 1 (v=1): m* la ml // Chi so cho form factor la 8, chi so cho scat_table la tu 12-13 for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(e_step=1; e_step<=n_lev; e_step++){ // f-process ABSORPTION Ef = eig[s][3][n] - eig[s][1][m] + E[e_step]+ hw0f_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_ml*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][12] = constant_optical_f_a* form_factor[s][n][m][8]* DOS_temp; } else{ //theta =0.0; DOS_temp = 0.0 scat_table[s][n][m][e_step][12]=0.0; } //f-process EMISSION Ef = eig[s][3][n] - eig[s][1][m] + E[e_step] - hw0f_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_ml*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][13] = constant_optical_f_e* form_factor[s][n][m][8]* DOS_temp; } else{// theta =0.0; DOS_temp = 0.0 scat_table[s][n][m][e_step][13]=0.0; } } // End of for(e_step=1; e_step<=n_lev; e_step++) } // End of for(m=1; m<=NSELECT; m++){ } // End of for(n=1; n<=NSELECT; n++) } // End of for(s=0; s<=nx_max; s++){ // Cho moi section slice // End of II.1.5. Tu valley 3 (v=3) --> Valley 1 (v=1): m* la ml // II.1.6. Tu valley 3 (v=3) --> Valley 2 (v=2): m* la mt // Chi so cho form factor la 9, chi so cho scat_table la tu 14-15 for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(e_step=1; e_step<=n_lev; e_step++){ // f-process ABSORPTION Ef = eig[s][3][n] - eig[s][2][m] + E[e_step]+ hw0f_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][14] = constant_optical_f_a* form_factor[s][n][m][9]* DOS_temp; } else{//theta =0.0; DOS_temp = 0.0 scat_table[s][n][m][e_step][14]=0.0; } //f-process EMISSION Ef = eig[s][3][n] - eig[s][2][m] + E[e_step] - hw0f_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][15] = constant_optical_f_e* form_factor[s][n][m][9]* DOS_temp; } else{//theta =0.0; DOS_temp = 0.0 scat_table[s][n][m][e_step][15]=0.0; } } // End of for(e_step=1; e_step<=n_lev; e_step++) } // End of for(m=1; m<=NSELECT; m++){ } // End of for(n=1; n<=NSELECT; n++) } // End of for(s=0; s<=nx_max; s++){ // Cho moi section slice // End of II.1.6. Tu valley 3 (v=3) --> Valley 2 (v=2): m* la mt // End of II.1 // II.2. g-process // II.2.1. Tu valley 1 (v=1) --> Valley 1' (v=1): m* la ml // Chi so cho form factor la 1, chi so cho scat_table la tu 16-17 for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(e_step=1; e_step<=n_lev; e_step++){ //g-process ABSORPTION Ef = eig[s][1][n] - eig[s][1][m] + E[e_step] + hw0g_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_ml*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][16] = constant_optical_g_a* form_factor[s][n][m][1]* DOS_temp; } else{//theta =0.0; DOS_temp = 0.0 scat_table[s][n][m][e_step][16]=0.0; } //g-process EMISSION Ef = eig[s][1][n] - eig[s][1][m] + E[e_step] - hw0g_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_ml*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][17] = constant_optical_g_e* form_factor[s][n][m][1]* DOS_temp; } else{//theta =0.0; DOS_temp=0.0 scat_table[s][n][m][e_step][17]=0.0; } } // End of for(e_step=1; e_step<=n_lev; e_step++) } // End of for(m=1; m<=NSELECT; m++){ } // End of for(n=1; n<=NSELECT; n++) } // End of for(s=0; s<=nx_max; s++){ // Cho moi section slice // End of II.2.1. Tu valley 1 (v=1) --> Valley 1' (v=1): m* la ml // II.2.2. Tu valley 2 (v=2) --> Valley 2' (v=2): m* la mt // Chi so cho form factor la 2, chi so cho scat_table la tu 18-19 for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(e_step=1; e_step<=n_lev; e_step++){ //g-process ABSORPTION Ef = eig[s][2][n] - eig[s][2][m] + E[e_step] + hw0g_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][18] = constant_optical_g_a* form_factor[s][n][m][2]* DOS_temp; } else{//theta =0.0; DOS_temp=0.0 scat_table[s][n][m][e_step][18]=0.0; } //g-process EMISSION Ef = eig[s][2][n] - eig[s][2][m] + E[e_step] - hw0g_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][19] = constant_optical_g_e* form_factor[s][n][m][2]* DOS_temp; } else{//theta =0.0; DOS_temp=0.0 scat_table[s][n][m][e_step][19]=0.0; } } // End of for(e_step=1; e_step<=n_lev; e_step++) } // End of for(m=1; m<=NSELECT; m++){ } // End of for(n=1; n<=NSELECT; n++) } // End of for( s=0; s<=nx_max; s++){ // Cho moi section slice // End of II.2.2. Tu valley 2 (v=2) --> Valley 2' (v=2): m* la mt // II.2.3. Tu valley 3 (v=3) --> Valley 3' (v=3): m* la mt for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(e_step=1; e_step<=n_lev; e_step++){ //g-process ABSORPTION Ef = eig[s][3][n] - eig[s][3][m] + E[e_step] + hw0g_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][20] = constant_optical_g_a* form_factor[s][n][m][3]* DOS_temp; } else{//theta =0.0; DOS_temp=0.0 scat_table[s][n][m][e_step][20]=0.0; } //g-process EMISSION Ef = eig[s][3][n] - eig[s][3][m] + E[e_step] - hw0g_phonon; if(Ef > 0.0){ theta = 1.0; DOS_temp = const_DOS_mt*theta*((1+2.0*af*Ef)/sqrt(Ef*(1+af*Ef))); scat_table[s][n][m][e_step][21] = constant_optical_g_e* form_factor[s][n][m][3]* DOS_temp; } else{//theta =0.0; DOS_temp=0.0 scat_table[s][n][m][e_step][21]=0.0; } } // End of for(e_step=1; e_step<=n_lev; e_step++) } // End of for(m=1; m<=NSELECT; m++){ } // End of for(n=1; n<=NSELECT; n++) } // End of for( s=0; s<=nx_max; s++){ // Cho moi section slice // End of II.2.1. Tu valley 3 (v=3) --> Valley 3' (v=3): m* la mt // End of Part II.2 // End of Part II } // End of if(flag_zero_order_optical ==1) //***************************************************************************** // Free local variables free_dvector(E,1,n_lev); return; }// End of void scattering_table() /* ********************************************************************************* */ /* **************************************************************** De SAVE Scattering rate vao trong 1 file. Chi Save tai 1 section thoi INPUT: + s_th: s-th section. Chi save tai section s_th thoi - so luong tu 0 den nx_max + valley pair - so luong tu 1 den 3 + NSELECT: subband index n (1 den NSELECT) den m (1 den NSELECT) + n_lev: So enerfy steps: tu constants.h + scat_table[s][n][m][e_step][scatName] OUTPUT: + SAVE scat_table[s][n][m][e_step][scatName] tai 1 section TONG 3 valley pair xac dinh Vao file Scattering_rate.dat gom Acoustic va Nonpolar Optical Phonon Starting date: March 13, 2010 Update: March 13, 2010 Latest update: March 23, 2010 De kiem tra scattering rate tai cac valley ****************************************************************** */ void save_scattering_table(int s_th, char *fn){ // Goi ham double *****Get_scat_table(), Get_emax(); int Get_NSELECT(); // Local bien double *****scat_table = Get_scat_table(); double emax = Get_emax();// printf("\n emax=%f, n_lev=%d",emax, n_lev); int Get_nx0(),Get_nx1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; // int nx_max = Get_nx_max(); int NSELECT = Get_NSELECT(); // Thuc hien if (s_th < 0){ s_th = 0;}// Kiem tra dau vao s_th de khong vuot qua chi so cua cross-section if (s_th > nx_max) { s_th = nx_max; } double *Scat_Acous_All_Valley = dvector(1,n_lev); // bien trung gian tinh Acoustic la tong cac o cac subband va valley double *Scat_Acous_Valley_1 = dvector(1,n_lev); //tinh Acoustic la tong cac o cac subband o Valley pair 1 double *Scat_Acous_Valley_2 = dvector(1,n_lev); //tinh Acoustic la tong cac o cac subband o Valley pair 2 double *Scat_Acous_Valley_3 = dvector(1,n_lev); //tinh Acoustic la tong cac o cac subband o Valley pair 3 double *Scat_Optical_All_Valley = dvector(1, n_lev); //double *Scat_Optical_Valley_1 = dvector(1, n_lev); //double *Scat_Optical_Valley_2 = dvector(1, n_lev); //double *Scat_Optical_Valley_3 = dvector(1, n_lev); int i; for(i=1; i<=n_lev; i++){// KHONG HIEU TAI sao neu khong khoi tao thi no lai lay gia tri cua DOS Scat_Acous_All_Valley[i]=0.0; Scat_Acous_Valley_1[i]=0.0; Scat_Acous_Valley_2[i]=0.0; Scat_Acous_Valley_3[i]=0.0; Scat_Optical_All_Valley[i]=0.0; //Scat_Optical_Valley_1[i]=0.0; //Scat_Optical_Valley_2[i]=0.0; // Scat_Optical_Valley_3[i]=0.0; } double de=emax/(double)(n_lev); // energy interval FILE *f; f = fopen(fn,"w"); // "w" neu tep ton tai no se bi xoa //FILE *f; f = fopen("Scat_table.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL) { printf("\n Cannot open file at save_scattering_table.c"); return ; } fprintf(f,"\n #ener_step AcouVall_1 AcouVall_2 AcouVall_3 AcouAllValley OpticalAllValley s_th \n"); //fprintf(f,"\n ener_step AcouVall_1 AcouVall_2 AcouVall_3 AcouAllValley OptVall_1 OptVall_2 OptVall_3 OptAllVall s_th \n"); int n,m,e_step,v;// for(e_step=1; e_step<=n_lev; e_step++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ // Tinh cho Acoustic Scat_Acous_Valley_1[e_step]=Scat_Acous_Valley_1[e_step]+scat_table[s_th][n][m][e_step][1]; Scat_Acous_Valley_2[e_step]=Scat_Acous_Valley_2[e_step]+scat_table[s_th][n][m][e_step][2]; Scat_Acous_Valley_3[e_step]=Scat_Acous_Valley_3[e_step]+scat_table[s_th][n][m][e_step][3]; for(v=1; v<=3; v++){// Acoustic Scat_Acous_All_Valley[e_step]= Scat_Acous_All_Valley[e_step]+ scat_table[s_th][n][m][e_step][v]; } // Nghia la Tong o 3 cap valley // Tinh cho Non-polar Optical Phonon for(v=4; v<=21; v++){ // Optical. KINH NGHIEM: it nhat gia tri 21 nay can 1 cai TEN Scat_Optical_All_Valley[e_step] = Scat_Optical_All_Valley[e_step] + scat_table[s_th][n][m][e_step][v]; } } // End of for(m=1; m<=NSELECT; m++){ } // End of for(n=1; n<=NSELECT; n++) }// End of for(e_step=1; e_step<=n_lev; e_step++) for(e_step=1; e_step<=n_lev; e_step++){ // Ghi vao file fprintf(f,"%le %le %le %le %le %le %d \n", e_step*de, Scat_Acous_Valley_1[e_step], Scat_Acous_Valley_2[e_step], Scat_Acous_Valley_3[e_step], Scat_Acous_All_Valley[e_step], Scat_Optical_All_Valley[e_step], s_th); } fclose(f); // Free local matrix free_dvector(Scat_Acous_Valley_1,1,n_lev); free_dvector(Scat_Acous_Valley_2,1,n_lev); free_dvector(Scat_Acous_Valley_3,1,n_lev); free_dvector(Scat_Acous_All_Valley,1,n_lev); free_dvector(Scat_Optical_All_Valley,1,n_lev); return; } // End of void save_scattering_table(int s_th){ /* ********************************************************************************* To normalize the scattering table for EACH SECTION s-th - choose the maximum of scattering rate - normalize of scattering rate Starting date: March 12, 2010 Latest update: March 16, 2010 *********************************************************************************** */ void normalize_table(){ // Goi ham double *****Get_scat_table(); double *Get_max_gm(); int Get_NSELECT(); // Cac bien local double *****scat_table = Get_scat_table(); double *max_gm = Get_max_gm(); int Get_nx0(),Get_nx1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; // int nx_max = Get_nx_max(); int NSELECT = Get_NSELECT(); // Reset max_gm truoc moi lan chay int s; for(s=nx0; s<=nx1; s++){ max_gm[s] = 0.0; } // Thuc hien double **gm = dmatrix(0,nx_max,1,n_lev);// gm la gamma day. Do ta se gan GIAN TIEP gm nen CAN KHOI TAO int i,j; for(i=0; i<=nx_max; i++){ for(j=1; j<=n_lev; j++){ gm[i][j] = 0.0; } } double temp = 0.0; // la bien de tinh tong double *****temp_scat = d5matrix(0,nx_max,1,NSELECT,1,NSELECT,1,n_lev,1,21);// KINH NGHIEM it nhat thi gia tri 21 nay CAN CO 1 CAI TEN // La BIEN TRUNG GIAN cho scat_table NO PHAI MATCH HOAN TOAN voi bien scat_table int i1,i2,i3,i4,i5; for(i1=0; i1<=nx_max; i1++){ for(i2=1; i2<=NSELECT; i2++){ for(i3=1; i3<=NSELECT; i3++){ for(i4=1; i4<=n_lev; i4++){ for(i5=1; i5<=21; i5++){ temp_scat[i1][i2][i3][i4][i5]=0.0; } } } } } // End of for(i1=0; i1<=nx_max; i1++) int v,n,m,e_step; // NOTE: Luc da chon IT NHAT 1 loai SCATTERING thi mechanism cua SCATTERING DO luon lon hon 1. // Vi du: Acoustic cung co 3 index cho 3 kieu intra-Valley // Buoc 1: tinh tong scattering rate tai s-th section va energy_step for(s=0; s<=nx_max; s++){ for(e_step=1; e_step<=n_lev; e_step++){ temp = 0.0; for(v=1; v<=21; v++){//v=1 den 3: Acoustic; v=4 den 21: Zero-order Optical // NOTE: phai chay cho v TRUOC roi moi den n va m thi moi tao ra bang trang 107 duoc for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ gm[s][e_step] = gm[s][e_step] + scat_table[s][n][m][e_step][v]; temp = temp + scat_table[s][n][m][e_step][v]; temp_scat[s][n][m][e_step][v]= temp; } } } } } // End of for(s=0; s<=nx_max; s++) // Buoc 2: Tinh gia tri gm max tai moi section for(s=0; s<=nx_max; s++){ max_gm[s] = gm[s][n_lev]; // gan cho gia tri tai diem energy cuoi cung for(e_step=1; e_step<=n_lev-1; e_step++){ if(max_gm[s]< gm[s][e_step]){ max_gm[s] = gm[s][e_step]; } } //printf("\n Maximum scatering rate at %d section is %le",s,max_gm[s]); //Da check: Ket qua DUNG }// End of for(s=0; s<=nx_max; s++) // Buoc 3: Normalized scattering table with max_gm[s] for(s=0; s<=nx_max; s++){ for(e_step=1; e_step<=n_lev; e_step++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(v=1; v<=21; v++){ scat_table[s][n][m][e_step][v]=temp_scat[s][n][m][e_step][v];//Matchinh scat_table lay tu temp_scat scat_table[s][n][m][e_step][v] = scat_table[s][n][m][e_step][v]/max_gm[s]; //printf("\n Normalized scatering rate at %d section is %f",s,scat_table[s][n][m][e_step][v]); getchar(); } } } } } // End of for(s=0; s<=nx_max; s++) // Free cac bien local free_dmatrix(gm,0,nx_max,1,n_lev); free_d5matrix(temp_scat,0,nx_max,1,NSELECT,1,NSELECT,1,n_lev,1,21); return; } /* **************************************************************** De SAVE normalize table vao trong 1 file. Chi Save tai tat ca section thoi INPUT: + s_th: s-th section. Chi save tai section s_th thoi - so luong tu 0 den nx_max + valley pair - so luong tu 1 den 3 + NSELECT: subband index n (1 den NSELECT) den m (1 den NSELECT) + n_lev: So enerfy steps: tu constants.h + scat_table[s][n][m][e_step][scatName] : cai da Normalized NHE OUTPUT: + SAVE scat_table[s][n][m][e_step][scatName] tai 1 section TONG 3 valley pair xac dinh Chi show neu gia tri cua no 1.0e-6 > gia tri >= 1. Y dinh cua ta la biet duoc tai moi section, o subband nao den subband nao va energy step la bao nhieu thi gia tri normalized la 1 Starting date: June 03, 2010 Latest update: June 03, 2010 De kiem tra ****************************************************************** */ void save_normalized_table(){ // Goi ham double *****Get_scat_table();// Bang scat da DUOC normalized double *****scat_table = Get_scat_table(); double Get_emax(); double emax = Get_emax(); int Get_nx0(),Get_nx1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; int Get_NSELECT(); int NSELECT = Get_NSELECT(); FILE *f; f = fopen("normalized_table.dat","w"); // "w" neu tep ton tai no se bi xoa if(f==NULL) { printf("\n Cannot open file normalized_table.dat"); return ; } fprintf(f,"\n # Section_sth Subband_n Subband_m e_step normalized \n"); int s, n,m,e_step,v; for(s=0; s<=nx_max; s++){ for(n=1; n<=NSELECT; n++){ for(m=1; m<=NSELECT; m++){ for(e_step=1; e_step<=n_lev; e_step++){ for(v=1; v<=21; v++){ // NOTE if if((scat_table[s][n][m][e_step][v]<1.0e-6)||(scat_table[s][n][m][e_step][v]>=1))//Chung to xem no co o trong KHOANG (0,1) { fprintf(f,"%d %d %d %d %le \n ",s, n,m, e_step, scat_table[s][n][m][e_step][v]); } } } } } } fclose(f); return; } // End of void save_normalized_table(int s_th) <file_sep>// Ham ran2 o day, nhung ta thu su dung ran4 xem sao -> Ham random o duoi la ran4 day // Note #undef's at end of file #define IM1 2147483563 #define IM2 2147483399 #define AM (1.0/IM1) #define IMM1 (IM1-1) #define IA1 40014 #define IA2 40692 #define IQ1 53668 #define IQ2 52774 #define IR1 12211 #define IR2 3791 #define NTAB 32 #define NDIV (1+IMM1/NTAB) #define EPS 1.2e-7 #define RNMX (1.0-EPS) // Returns a uniform random deviate between 0.0 and 1.0 (exclusive of the endpoint values) float random2(long *idum) { int j; long k; static long idum2=123456789; static long iy=0; static long iv[NTAB]; float temp; if (*idum <= 0) { //Initialize if (-(*idum) < 1) *idum=1; // Be sure to prevent idum=0. else *idum = -(*idum); idum2=(*idum); for (j=NTAB+7;j>=0;j--) { //Load the shuffle table (after 8 warm-ups) k=(*idum)/IQ1; *idum=IA1*(*idum-k*IQ1)-k*IR1; if (*idum < 0) *idum += IM1; if (j < NTAB) iv[j] = *idum; } iy=iv[0]; } k=(*idum)/IQ1; // Start here when not initilizing *idum=IA1*(*idum-k*IQ1)-k*IR1; //Compute idum=(IA1*idum) % IM1 without if (*idum < 0) *idum += IM1; //overflow by Schrage's method k=idum2/IQ2; idum2=IA2*(idum2-k*IQ2)-k*IR2; //Compute idum2=IA2*idum %IM2 likewise if (idum2 < 0) idum2 += IM2; j=iy/NDIV; //Will be in the range 0...NTAB-1. iy=iv[j]-idum2; //Here idum is shuffled, idum and idum2 iv[j] = *idum; //are combine to generate output if (iy < 1) iy += IMM1; if ((temp=AM*iy) > RNMX) return RNMX;// Because users don't expect endpoint values else return temp; } #undef IM1 #undef IM2 #undef AM #undef IMM1 #undef IA1 #undef IA2 #undef IQ1 #undef IQ2 #undef IR1 #undef IR2 #undef NTAB #undef NDIV #undef EPS #undef RNMX // Ket thuc ham ran2. Ham ran4 below /* #define NITER 4 void psdes(unsigned long *lword, unsigned long *irword) { unsigned long i,ia,ib,iswap,itmph=0,itmpl=0; static unsigned long c1[NITER]={ 0xbaa96887L, 0x1e17d32cL, 0x03bcdc3cL, 0x0f33d1b2L}; static unsigned long c2[NITER]={ 0x4b0f3b58L, 0xe874f0c3L, 0x6955c5a6L, 0x55a7ca46L}; for (i=0;i<NITER;i++) { ia=(iswap=(*irword)) ^ c1[i]; itmpl = ia & 0xffff; itmph = ia >> 16; ib=itmpl*itmpl+ ~(itmph*itmph); *irword=(*lword) ^ (((ia = (ib >> 16) | ((ib & 0xffff) << 16)) ^ c2[i])+itmpl*itmph); *lword=iswap; } } #undef NITER // (C) Copr. 1986-92 Numerical Recipes Software z1+91. // Ham ran4 - ham tot nhat theo y tac gia nhung no chay hoi cham float random(long *idum) { //void psdes(unsigned long *lword, unsigned long *irword); unsigned long irword,itemp,lword; static long idums = 0; #if defined(vax) || defined(_vax_) || defined(__vax__) || defined(VAX) static unsigned long jflone = 0x00004080; static unsigned long jflmsk = 0xffff007f; #else static unsigned long jflone = 0x3f800000; static unsigned long jflmsk = 0x007fffff; #endif if (*idum < 0) { idums = -(*idum); *idum=1; } irword=(*idum); lword=idums; psdes(&lword,&irword); itemp=jflone | (jflmsk & irword); ++(*idum); return (*(float *)&itemp)-1.0; } // (C) Copr. 1986-92 Numerical Recipes Software z1+91. // */ <file_sep>/* *********************************************************************** To check the charge neutrality of the source and drain ohmic contacts + Neu so hat LON HON thi Eliminate no + Neu so hat NHO HON thi Create + Considering for SIDE CONTACT case Co nghia chi xac dinh cai phan cua Source va Drain ap vao Starting date: March 27, 2010 Latest update: March 29, 2010 ************************************************************************* */ #include <stdio.h> void check_source_drain_contacts(){ // Goi cac ham void init_kspace(int ne,int i),init_realspace(int ne,int i); int Get_nsource_side_carriers(),Get_ndrain_side_carriers(); int Get_n_used(); // Tinh SO HAT dang SU DUNG void Set_n_used( int n); double **Get_p(); int *Get_valley(); int Get_iss_eli(),Get_idd_eli(),Get_iss_cre(),Get_idd_cre(); void Set_iss_eli(int eli_p),Set_idd_eli(int eli_p),Set_iss_cre(int cre_p),Set_idd_cre(int cre_p); double Get_mesh_size_x(); // Cac bien local int nsource_side_carriers = Get_nsource_side_carriers(); int ndrain_side_carriers = Get_ndrain_side_carriers(); double **p = Get_p(); int *valley = Get_valley(); double mesh_size_x = Get_mesh_size_x(); int Get_nx0(),Get_nx1(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); int nx_max = nx1-nx0; // int nx_max = Get_nx_max(); // Thuc hien //****************************************************************************** // Buoc 1: Delete extra carriers at the source and drain contacts int iss_eli_update = 0, idd_eli_update = 0; double x_position = 0.0; int n,ix; //int count =0; // for checking int npt_source=0, npt_drain=0; int n_used = Get_n_used(); //printf("\n Truoc Check source and Drain contact n_used = %d",n_used); for(n = 1; n<=n_used; n++){ // Chay cho tung hat if(valley[n] !=9){// Chi chay cho cac hat co iv KHAC 9, Neu =9: xem ham delete_particle() //count +=1; x_position = p[n][2]; // lay vi tri hat thu n ix = (int)(x_position/mesh_size_x + 0.5); if(ix > nx_max) { ix = nx_max; } // Tai Source contact if(ix == 0){ // Phan mep ben tay trai (cuc Source) if(nsource_side_carriers > npt_source ) { npt_source += 1; // tang them 1 hat } // cho den khi nsource_side_carriers = npt_source else { // Qua so hat de tao charge neutrality. Can GHI NHO se Loai hat nay valley[n] = 9; iss_eli_update = Get_iss_eli();// 3 lenh tuong duong 1 lenh iss_eli += 1; iss_eli_update += 1; // Loai 1 hat ra Set_iss_eli(iss_eli_update); } }// End of if(ix ==0) // Tai Drain contact if(ix ==nx_max){// Phan mep ben tay phai (cuc Drain) if(ndrain_side_carriers > npt_drain ) { npt_drain += 1; } else { valley[n] = 9; idd_eli_update = Get_idd_eli(); idd_eli_update += 1; Set_idd_eli(idd_eli_update); } }// End of if(ix ==nx_max) } // End of if(valley[n] !=9) }// End of for(int n = 1; n<=n_used; n++) //printf("\n So hat co valley KHAC 9 la count= %d ",count); //printf("\n iss_eli = %d,Kieu 2 iss_eli = %d ", iss_eli_update,Get_iss_eli()); // Only for checking //printf("\n idd_eli = %d,Kieu 2 idd_eli = %d ", idd_eli_update,Get_idd_eli()); // End of Buoc 1: Delete extra carriers at the source and drain contacts //****************************************************************************** // Buoc 2. Create carriers at the source and drain contacts int iss_cre_update=0, idd_cre_update=0; int nele_diff = 0; // XAY RA khi sau khi quet het so hat ma nsource_side_carriers > npt_source // So particle KHAC NHAU giua (npt_source va nsource_side_carriers) // cho Source contact, tuong tu cho Drain contact. -> // need to create particles to make charge neutrality at the Souce // and Drain ohmic contacts */ int ne = 0; // Bien trung gian // Tai Source contact ne = 0; ix = 0; if(nsource_side_carriers > npt_source){ nele_diff = nsource_side_carriers - npt_source; ne = Get_n_used(); while(nele_diff >= 1){ ne = ne + 1; // Add vao cac vi tri tiep theo va lan luot init_kspace(ne,ix); init_realspace(ne,ix); nele_diff = nele_diff - 1; iss_cre_update = Get_iss_cre(); iss_cre_update += 1; Set_iss_cre(iss_cre_update); } // End of while Set_n_used(ne);// vi trong qua trinh tren "ne" da tang len, ta can update gia tri } // End of if(nsource_side_carriers > npt_source) // Tai Drain contact ix = nx_max; if(ndrain_side_carriers > npt_drain){ nele_diff = ndrain_side_carriers - npt_drain; ne = Get_n_used(); while(nele_diff >= 1){ ne = ne + 1; // Add vao cac vi tri tiep theo va lan luot init_kspace(ne,ix); init_realspace(ne,ix); nele_diff = nele_diff - 1; idd_cre_update = Get_idd_cre(); idd_cre_update += 1; Set_idd_cre(idd_cre_update); } // End of while Set_n_used(ne); }// End of if(ndrain_side_carriers > npt_drain) //printf("\n iss_cre = %d,Kieu 2 iss_cre = %d ", iss_cre_update,Get_iss_cre()); // Only for checking //printf("\n idd_cre = %d,Kieu 2 idd_cre = %d ", idd_cre_update,Get_idd_cre()); //printf("\n Sau Check source and Drain contact n_used = %d",Get_n_used()); // Hien nhien so hat se tang len neu co su Creation vi cac hat bi delete do out hay eliminate // se thuc hien o ham detele_particle() goi sau ham check_source_drain_contacts() return; } /* ************ End of check_source_drain_contacts() function ******************/ <file_sep>/* ************************************************************************ To read parameters in the SIMULATION_LIST part from input.dat file Starting date: Feb 23, 2010 Latest update: Feb 23, 2010 *************************************************************************** */ #include <stdio.h> #include <string.h> #include "mpi.h" double static dt,tot_time,transient_time,length_plotted,depth_plotted,width_plotted; int static NSELECT;// Number of subbands for each valley int static NTimeSteps; // Number of time steps to solve 2D Schrodinger Eq. De giam thoi gian cho 2D Schrodinger double static artificial_factor_cell_volume; void read_simulation_list(){ /* ******** Read simulation list from Input.d file ********* */ FILE *f; //char s[180]; f=fopen("Input.d","r"); if(f==NULL){printf("Error: can't open file Input.d \n"); return;} //printf("\n\n Reading #SIMULATION_LIST"); while (!feof(f)) { char str[180]; fscanf(f,"%s",str); if(strcmp(str,"#SIMULATION_LIST")==0){ fscanf(f,"%*s %*s %le",&dt); //printf("\n dt...MC_time_step[fs]= %3.2f",dt); dt = dt*1.0e-15; // chuyen [fs] -> [s] fscanf(f,"%*s %*s %le ",&tot_time); //printf("\n Total time[ps]= %3.8f",tot_time); tot_time = tot_time*1.0e-12; // chuyen [ps] -> [s] fscanf(f,"%*s %*s %le ",&transient_time); //printf("\n Transient time after which results are calculated[ps]= %3.8f",transient_time); transient_time = transient_time*1.0e-12; // chuyen [ps] -> [s] fscanf(f,"%*s %*s %le ",&length_plotted); //printf("\n Length where the 3D plots are plotted[nm]= %3.2f",length_plotted); length_plotted = length_plotted*1.0e-9; // chuyen [nm] -> [m] fscanf(f,"%*s %*s %le ",&depth_plotted); //printf("\n Depth where the 3D plots are plotted[nm]= %3.2f",depth_plotted); depth_plotted = depth_plotted*1.0e-9; // chuyen [nm] -> [m] fscanf(f,"%*s %*s %le ",&width_plotted); //printf("\n Width where the 3D plots are plotted[nm]= %3.2f",width_plotted); width_plotted = width_plotted*1.0e-9; // chuyen [nm] -> [m] fscanf(f,"%*s %*s %d ",&NSELECT); //printf("\n Number of Subbands wanted for 2D Schrodinger = %d",NSELECT); fscanf(f,"%*s %*s %d ",&NTimeSteps); //printf("\n Number of time steps to solve 2D Schrodinger = %d",NTimeSteps); fscanf(f,"%*s %*s %le ",&artificial_factor_cell_volume); //printf("\n Artificial factor of cell volume = %le",artificial_factor_cell_volume); } // End of if }// End of while fclose(f); //Phan printf ra Monitor o node co rank=0 int myrank, mysize; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); MPI_Comm_size(MPI_COMM_WORLD,&mysize); if(myrank ==0){ printf("\n\n Reading #SIMULATION_LIST"); printf("\n dt...MC_time_step[fs]= %3.2f",dt/1.0e-15); printf("\n Total time[ps]= %3.8f",tot_time/1.0e-12); printf("\n Transient time after which results are calculated[ps]= %3.8f",transient_time/1.0e-12); printf("\n Length where the 3D plots are plotted[nm]= %3.2f",length_plotted/1.0e-9); printf("\n Depth where the 3D plots are plotted[nm]= %3.2f",depth_plotted/1.0e-9); printf("\n Width where the 3D plots are plotted[nm]= %3.2f",width_plotted/1.0e-9); printf("\n Number of Subbands wanted for 2D Schrodinger = %d",NSELECT); printf("\n Number of time steps to solve 2D Schrodinger = %d",NTimeSteps); printf("\n Artificial factor of cell volume = %le",artificial_factor_cell_volume); }// End of if(myrank ==0) return; } // ********* End of void read_simulation_list() ************* double Get_dt(){ return dt; } double Get_tot_time(){ return tot_time; } double Get_transient_time(){ return transient_time; } double Get_length_plotted(){ return length_plotted; } double Get_depth_plotted(){ return depth_plotted; } double Get_width_plotted(){ return width_plotted; } int Get_NSELECT(){ return NSELECT; } int Get_NTimeSteps(){ return NTimeSteps; } double Get_artificial_factor_cell_volume(){ return artificial_factor_cell_volume; } <file_sep>typedef struct { int Mx_src ; int Mx_channel ; int My_ox ; int My_si ; int Mz_ox ; int Mz_si ; int Mz_box ; int x ; int x0 ; int x1 ; int xa ; int xb ; int xgate0 ; int xgate1 ; int y ; int y0 ; int y1 ; int ya ; int yb ; int ygate0 ; int ygate1 ; int z ; int z0 ; int z1 ; int za ; int zb ; int zgate ; } PoiNum ; typedef struct { double *X ; double *Y ; double *Z ; double *hx ; double *hy ; double *hz ; double ***Phi ; double ***phi ; double ***n3d ; double ***p3d ; } PoiMem ; typedef struct { int _SOURCE_CONTACT ; int _DRAIN_CONTACT ; int _SOURCE_WALL ; int _DRAIN_WALL ; int _LEFT_WALL ; int _RIGHT_WALL ; int _TOP_WALL ; int _BOTT_WALL ; int _GATE_CONTACT ; int _CHANNEL_SILICON ; int _JUNCTION_SILICON ; int _OXIDE ; int _LEFT_INTERFACE ; int _RIGHT_INTERFACE ; int _TOP_INTERFACE ; int _BOTT_INTERFACE ; int _CORNERS ; } Region ; typedef struct { int MaxIter ; double ConvEps ; char pctype[20] ; char ksptype[20] ; double ksprtol ; int gmres_restart ; int RoundGate ; } PoiParam ; PoiNum *PGetPoiNum() ; PoiNum GetPoiNum() ; PoiMem *PGetPoiMem() ; PoiParam *PGetPoiParam() ; PoiParam GetPoiParam() ; Region *PGetR_() ; Region GetR_() ; double ***GetPot() ; double ***GetPhiKth() ; double *GetPX() ; double *GetPY() ; double *GetPZ() ; double *GetHx() ; double *GetHy() ; double *GetHz() ; double ***GetN3d() ; double ***GetP3d() ; int GetRegion() ; void get_ijk() ; int get_p() ; int GetPx0() ; int GetPx1() ; int GetPy0() ; int GetPy1() ; int GetPz0() ; int GetPz1() ; int GetPya() ; int GetPyb() ; int GetPza() ; int GetPzb() ; <file_sep>/* *********************************************************************** To delete extra particles based on their valley[] Neu valley[tai hat i-th] = 9 <--Can delete HAT nay Starting date: March 28, 2010 Latest update: March 29, 2010 ************************************************************************* */ #include <stdbool.h> // De khai bao kieu bool #include <stdio.h> void delete_particles(){ // Goi ham double **Get_p(); double *Get_energy(); int *Get_valley(); int *Get_subband(); int Get_n_used(); // Tinh SO HAT dang LUU valley=1,2,3 HAY 9 void Set_n_used( int n); int count_used_particles(); // Ca bien local double **p = Get_p(); double *energy = Get_energy(); int *valley = Get_valley(); int *subband = Get_subband(); int n_used = Get_n_used(); // TAT ca cac HAT valley=1,2,3 HAY 9 // Thuc hien int n_fix = 0; bool flag_conv; //int ne = count_used_particles(); //printf("\n Number of electrons from count_used_particles() = %d ",ne); // phai bang so hat sau delete //printf("\n Number of electrons Before delete = %d ",n_used); int i,j; for(i = 1; i<=n_used; i++){ if(valley[i] == 9){ // Particle i-th has iv=9 need to delete flag_conv = false; // =0 means FALSE n_fix = n_used + 1; // Cong them 1 hat vao n_used while(!flag_conv){ if(valley[n_fix] != 9){ // Neu hat cong them vao do co iv khac 9 //thi ta tien hanh chuyen tat ca cac parameters cua hat do //cho hat thu i va giam gia tri di 1 valley[i] = valley[n_fix]; // move valley index energy[i] = energy[n_fix]; // move energy subband[i] = subband[n_fix];// move subband for(j = 1; j <= 4; j++) { // j=1: move mometum; j=2: move position p[i][j]=p[n_fix][j];// j=3: move free flight time hien tai; } // j=4: move i-region> Hien tai (March 29) CHUA DUNG valley[n_fix] = 9; // inactive particle n_fix -> will be delete it n_fix = n_fix - 1; // flag_conv = true; // =1 means TRUE } // End of if(valley[n_fix] != 9) // Below, means ip[n_fix]==9 n_fix = n_fix - 1; // reduce n_fix and check ip index again if(n_fix < i) { flag_conv = true; } // =1 means TRUE } // End of while(!flag_conv){ }// End of if(valley[i] == 9) } //End of for (int i=1; i<=n_used; i++){ // Gio day no da NOI LEN ca roi thi ta moi GIAM while (valley[n_used]==9){ n_used = n_used - 1; } Set_n_used(n_used); //printf("\n Number of particles used (after deleting) = %d, Kieu 2 =%d",n_used,Get_n_used()); return; } <file_sep>/* ***************************************************************************** De giai MSMC Starting date: April 3, 2010 Update: April 5, 2010 Latest update: May 16, 2010 ****************************************************************************** */ #include <stdio.h> #include "functions.h" #include "nanowire.h" #include "petscksp.h" #include "region.h" void multi_subbands_MC(FILE *logfile, int *argc, char ***argv){ // Goi cac ham void emcd(); void check_source_drain_contacts(); void delete_particles(); void electron_density_caculation(); void eigen_energy_correction(int StepsUsedCorrection); void Solved_2D_Schro_for_MSMC(); void Solved_2D_Schro_Parallel_for_MSMC(int *argc, char ***argv); void form_factor_calculation(); void scattering_table(); void save_results(); void normalize_table(); int Get_iss_out(),Get_iss_eli(),Get_iss_cre(),Get_idd_out(),Get_idd_eli(),Get_idd_cre(); double Get_dt(),Get_tot_time(),Get_transient_time(); // Xac dinh tu Input.d int Get_NTimeSteps(); void mpi_gather_potential_at_node0(); void mpi_distribute_potential_from_node0(); void save_potential(); // Cac bien local double dt = Get_dt(); // Observation time step double tot_time = Get_tot_time(); // Tong thoi gian chay Simulation double transient_time = Get_transient_time(); // Chon bang BAO NHIEU can KINH NGHIEM int NTimeSteps = Get_NTimeSteps(); int Get_nx1(); int NumSections = Get_nx1(); // Thuc hien int StepsUsedCorrection=0; // tai buoc j_th using time independent perturbation for eigen energy correction // Buoc 1.1. Lay rank, size va Mo 2 file de tinh current int myrank, mysize; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); MPI_Comm_size(MPI_COMM_WORLD,&mysize); FILE *ff, *ff_transient; if(myrank ==0){// Chi mo cac files TAI 1 NODE thoi ff=fopen("charge_source_drain.dat","w"); // Chu y dieu kien chon la "w" day ! if(ff==NULL){printf("Error: can't open file charge_source_drain.dat.\n");return;} // Thu tu time | source_factor | drain_factor cai nay la tinh tu thoi diem dau tien tro di // Ta khong nen ghi comment vao file nay vi file nay se duoc doc o ham current_calculation() ff_transient=fopen("charge_source_drain_transient.dat","w"); // Chu y dieu kien chon la "w" day ! if(ff_transient==NULL){printf("Error: can't open file charge_source_drain_transient.dat\n");return;} // Thu tu time | source_factor | drain_factor cai nay la tinh tu thoi diem transient tro di } // Buoc 1.2. Mo cac files de dung trong vong lap while // Cho ham void velocity_energy_cumulative // Cho ham void save_VeloEnerCurrent_all_time_steps(FILE *fname.... FILE *fAllTimeSteps, *fAfterTransient, *fPotetialAveragex,*fPotentialAvewrageyz; if(myrank ==0){ fAllTimeSteps=fopen("Velo_ener_current_averages_all_time_steps.dat","w"); // Chu y kieu mo la "a" co the GHI THEM if(fAllTimeSteps==NULL){ printf("\n Cannot open file Velo_ener_current_averages_all_time_steps.dat");return;} fprintf(fAllTimeSteps,"\n #x[nm] velocity_x[m/s] energy[eV] current\n"); // Cho ham void save_VeloEnerCurrent_after_transient(FILE *fname..... //FILE *fAfterTransient; fAfterTransient=fopen("Velo_ener_current_averages_after_transient.dat","w"); // Chu y kieu mo la "a" if(fAfterTransient==NULL){ printf("\n Cannot open file Velo_ener_current_averages_after_transient.dat");return;} fprintf(fAfterTransient,"\n #x[nm] velocity_x[m/s] energy[eV] current\n"); // Cho ham void save_potential_average(FILE *f1, FILE *f2,double time, int iter_reference) //FILE *fPotetialAveragex; fPotetialAveragex = fopen("average_potential_along_x.dat","w");// Do la "w" nen neu chay nhieu cap (Vd,Vg) thi no la CAP CUOI CUNG if(fPotetialAveragex == NULL){printf("\n Cannot open file average_potential_along_x.dat");return; } fprintf(fPotetialAveragex,"\n #x[nm] Pot_x[eV] \n"); //FILE *fPotentialAvewrageyz; fPotentialAvewrageyz = fopen("average_potential_yz_plane.dat","w"); if(fPotentialAvewrageyz == NULL){printf("\n Cannot open file average_potential_yz_plane.dat");return; } fprintf(fPotentialAvewrageyz,"\n #y[nm] z[nm] Pot_avg_yz[eV] \n"); } // Buoc 2. Khoi tao cac bien dung trong vong lap while int issOut=0, issEli=0, issCre=0, iddOut=0, iddEli=0, iddCre=0; double drain_factor=0.0, source_factor=0.0; double time = 0.0; // thoi gian chay cua hat int iter_total=(int)(tot_time/dt+0.5); if(myrank ==0){ logging(logfile,"\n Total number of iterations = %d",iter_total); printf("\n Total number of iterations = %d",iter_total); } // Ta khong the save tat ca duoc. Chi co the save tai 1 vai iteration hoac o last interation ma thoi. int TimeStepsToSave = iter_total; // Save tai last iteration ma thoi // Buoc 3. Start MSMC phase int iter_reference=1; int j_iter=0; while(j_iter < iter_total){ // Chay tung lan cho tat ca cac iterations. Neu ma co dau = thi so luong j_iter la total number of interation +1 j_iter = j_iter + 1;// Lenh nay quan trong lam day time=dt*(double)(j_iter); // thoi gian o interation thu j_iter la bao nhieu emcd();// EMC: The function drift() and scattering() are used trong 1 khoang dt for all particles. Can SONG SONG check_source_drain_contacts();// To check the charge neutrality of the source and drain ohmic contacts //call initial_kspace and initial_realspace if needed. KHONG can SONG SONG delete_particles(); // Neu can. KHONG can SONG SONG electron_density_caculation();// la tu MSMC. KHONG can SONG SONG // Save electron density de kiem tra khong ? if(myrank ==0){// Chi TAI 1 NODE thoi if(j_iter % TimeStepsToSave ==0){// Save. TimeStepsToSave = iter_total nen save tai last char fnElectronDensity[100]; sprintf(fnElectronDensity,"Electron_Density-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); save_electron_density(fnElectronDensity); char fnAllSections[100]; sprintf(fnAllSections,"Electron_Density_All_Sections-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); save_electron_density_all_sections(fnAllSections);// For Checking only } } //PHAN GIAI 3D POISSON get_charge_density_for_Poisson();// chuyen charge density tu MSMC sang Poisson. No chuyen den TAT CA cac node // Co save charge dua vao Poisson tai cac Interim khong //save_charge_density_for_Poisson(); //logfile_PoissonInput(); // For checking if (GetPoissonLinearized()) { SolvePoisson = solve_3d_poisson_linearized;} else { SolvePoisson = solve_3d_poisson;} (*SolvePoisson)();// Chon kieu gi o tren thi solve Poisson theo kieu do //void mpi_gather_potential_at_node0();// Sau khi giai 3D Poisson xong thi can gather chu potential lai.RAT NOTE day mpi_gather_potential_at_node0(); // Neu chon Print_Midline_Potential(y/n) = y hoac print_output(); thi no da gather lai cho minh roi. mpi_distribute_potential_from_node0(myrank, mysize); // KET THUC giai 3D Poisson if(myrank ==0){// Chi TAI 1 NODE thoi if(j_iter % TimeStepsToSave ==0){// Save. TimeStepsToSave = iter_total nen save tai last print_output();// Chi de cuoi cung thoi. Neu de o day se gay loi sau khoang 502 vong lap //Nhung do GS con gather potential roi moi lam nen. Chua hieu lam ??? save_potential();//printf("\n Dung tai Solved_2D_Schro_for_MSMC() lan thu 2"); } } iter_reference=1; // Ban dau gan iter_reference =1 sau do neu j_iter=iter_total //(tuc bien chay j-iter di den diem cuoi cung)thi ta cho iter_reference=0; if(j_iter == iter_total) { iter_reference=0; } // Tinh cac gia tri trung binh save_potential_average(fPotetialAveragex, fPotentialAvewrageyz, time,iter_reference);//Trong source code minh tinh toan va chay cho 1 node if(myrank ==0){// Chi TAI 1 NODE thoi velocity_energy_cumulative(fAllTimeSteps,fAfterTransient, time,iter_reference); // Lay cac gia tri cua HAT VAO (CREATION) va RA (OUT or ELIMINATE) issOut = Get_iss_out(); issEli = Get_iss_eli(); issCre = Get_iss_cre(); iddOut = Get_idd_out(); iddEli = Get_idd_eli(); iddCre = Get_idd_cre(); source_factor =(double)(issOut+issEli-issCre); // tong so hat vao ra drain_factor = (double)(iddOut+iddEli-iddCre); // tong so hat vao ra fprintf(ff,"%le %le %le \n",time,source_factor,drain_factor);//Ghi vao file charge_source_drain.dat if(time >transient_time){// Ghi vao file charge_source_drain_transient.dat fprintf(ff_transient,"%le %le %le \n",time,source_factor,drain_factor); } }// End of if(myrank ==0) // NEED to solve 2D Scchrodinger or NOT if(j_iter % NTimeSteps !=0){// chi can dung phuong phap correction StepsUsedCorrection = j_iter; eigen_energy_correction(StepsUsedCorrection);// First order correction for energy using time-independent pertubation } else { // j_iter % NTimeSteps ==0 can giai 2D Schrodinger. if(myrank ==0){ printf("\n Solved 2D Schrodinger at interation =%d",j_iter); }// End of if(myrank ==0) //Solved_2D_Schro_Parallel_for_MSMC(argc,argv); Solved_2D_Schro_for_MSMC(); // LAN TIEP //if(myrank ==0){ //Save potential cai su dung de giai 2D Schrodinger //if(j_iter % TimeStepsToSave ==0){// Save. TimeStepsToSave = iter_total nen save tai last //char fn_x_Interim[100], fn_yz_Interim[100]; //sprintf(fn_x_Interim,"potential_x_at_midpoint_yz_in2DSchrodingerInterim-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //sprintf(fn_yz_Interim,"potential_yz_at_midpoint_x_in2DSchrodingerInterim-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //save_potential_used_for_2D_Schrodinger(fn_x_Interim,fn_yz_Interim); //Save subband_energy //char fnsubbandInterim[100]; //sprintf(fnsubbandInterim,"subbandInterim-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); //save_subband_energy(fnsubbandInterim); // }// End of if(j_iter % TimeStepsToSave ==0){// Save. TimeStepsToSave = iter_total nen save tai last // } form_factor_calculation();// LAN TIEP // Co save form factor cac lan TRUNG GIAN de Kiem tra khong ? if(myrank ==0){// Chi TAI 1 NODE thoi if(j_iter % TimeStepsToSave ==0){// Save. TimeStepsToSave = iter_total nen save tai last char fnformfactor[100]; sprintf(fnformfactor,"FormfactorLastInteration-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); int FormfactoSavedAtsth = (int)(NumSections/2 +0.5);// lay o giua save_form_factor_calculation(FormfactoSavedAtsth, fnformfactor); } } scattering_table(); //LAN TIEP // Save scattering cho nhung lan trung gian de kiem tra khong ? if(myrank ==0){// Chi TAI 1 NODE thoi if(j_iter % TimeStepsToSave ==0){// Save. TimeStepsToSave = iter_total nen save tai last char fnscat[100]; sprintf(fnscat,"ScatTableLastIteration-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); int ScatSavedAtsth = (int)(NumSections/2 +0.5);// lay o giua save_scattering_table(ScatSavedAtsth,fnscat); } } normalize_table(); //LAN TIEP de quay lay emcd() }//End of else { // j_iter % NTimeSteps ==0 can giai 2D Schrodinger if(myrank ==0){// Chi TAI 1 NODE thoi if(j_iter % TimeStepsToSave ==0){// Save. TimeStepsToSave = iter_total nen save tai last void save_electron_parameters(char *fn);// Dat o dau thi save o day char fn[100]; sprintf(fn,"ElectronParametersLastIteration-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); save_electron_parameters(fn); void save_electron_distribution(char *fnSubband,char *fnEnergy); char fnSubbandInter[100], fnEnergyInter[100]; sprintf(fnSubbandInter,"ElectronDistributionSubbandsLastIteration-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); sprintf(fnEnergyInter,"ElectronDistributionEnergyLastIteration-Vd%0.2f-Vg%0.2f.dat",GetDrainVoltage(),GetGateVoltage()); save_electron_distribution(fnSubbandInter,fnEnergyInter); } } } // End of the while(j_iter < iter_total) Time Loop fclose(ff); // Close file ff= ("charge_source_drain.dat","w"); fclose(ff_transient); // Close file ff_transient= ("charge_source_drain_transient.dat","w"); fclose(fAllTimeSteps); fclose(fAfterTransient); fclose(fPotetialAveragex); fclose(fPotentialAvewrageyz); }// End of multi_subbands_MC() <file_sep>#include <stdio.h> #include <string.h> #include "petscksp.h" #include "nanowire.h" void read_poisson_input(){ char cvar1, cvar2, cvar3 ; Param *P ; PoiParam *CP ; P = PGetParam() ; CP = PGetPoiParam() ; FILE *f; f = fopen("Input.d","r"); if(f == NULL){printf("Can't open file Input.d\n"); return;} //printf("\n\n Reading #POISSON_INPUT"); while (!feof(f)){ char str[180]; fscanf(f,"%s",str); if (strcmp(str,"#POISSON_INPUT")==0){ fscanf(f,"%*s %*s %d",&(CP->MaxIter)) ; //printf("\n Max Interation =%d",CP->MaxIter); fscanf(f,"%*s %*s %lf",&(CP->ConvEps)) ; //printf("\n Convergence_Eps =%le",CP->ConvEps); fscanf(f,"%*s %*s %s",CP->ksptype) ; //printf("\n KSPType =%s",CP->ksptype); fscanf(f,"%*s %*s %s",CP->pctype) ; //printf("\n PCType =%s",CP->pctype); fscanf(f,"%*s %*s %le",&(CP->ksprtol)) ; //printf("\n KSP_Rtol =%le",CP->ksprtol); fscanf(f,"%*s %*s %d",&(CP->gmres_restart)) ; //printf("\n GMRES_Restart =%d",CP->gmres_restart); fscanf(f,"%*s %*s %c", &cvar1); SetPoissonLinearized(ConvertBooleanCharToInt(cvar1)) ; //printf("\n Pois_Linea(n/y) =%c",cvar1); fscanf(f,"%*s %*s %d",&(P->trans_size)) ; //printf("\n Trans_Data_Siz =%d",P->trans_size); fscanf(f,"%*s %*s %c", &cvar2); SetPRINT_MidPotFlag(ConvertBooleanCharToInt(cvar2)) ; //printf("\n Print_Midline_Potential(y/n) =%c",cvar2); fscanf(f,"%*s %*s %c", &cvar3); SetPRINT_Pot3dFlag(ConvertBooleanCharToInt(cvar3)) ; //printf("\n Print_3D_Potential_at_Each_Bias_Point(y/n) =%c \n",cvar3); }// End of if(strcmp(s,"#POISSON_INPUT")==0) } // End of while fclose(f) ; //Phan printf ra Monitor o node co rank=0 int myrank; MPI_Comm_rank(MPI_COMM_WORLD,&myrank); if(myrank ==0){ printf("\n\n Reading #POISSON_INPUT"); printf("\n Max Interation =%d",CP->MaxIter); printf("\n Convergence_Eps =%le",CP->ConvEps); printf("\n KSPType =%s",CP->ksptype); printf("\n PCType =%s",CP->pctype); printf("\n KSP_Rtol =%le",CP->ksprtol); printf("\n GMRES_Restart =%d",CP->gmres_restart); printf("\n Pois_Linea(n/y) =%c",cvar1); printf("\n Trans_Data_Siz =%d",P->trans_size); printf("\n Print_Midline_Potential(y/n) =%c",cvar2); printf("\n Print_3D_Potential_at_Each_Bias_Point(y/n) =%c \n",cvar3); }// End of if(myrank ==0) return; }// End of void read_poisson_input() <file_sep>/* ***************************************************************************** Kiem tra cac dau vao Poisson co dung nhu GS khong Starting date: June 16, 2010 Latest update: June 16, 2010 ****************************************************************************** */ #include <stdio.h> #include <string.h> #include "petscksp.h" #include "nanowire.h" void logfile_PoissonInput(){ void logging(FILE *log,const char *fmt,...); FILE *logfile = fopen("logfile_PoissonInput.txt","w"); Param *P ; Dimen *D ; PoiNum *N ; Energy *E ; Density *n ; PoiParam *CP ; P = PGetParam() ; D = PGetDimen() ; N = PGetPoiNum() ; n = PGetDensity() ; E = PGetEnergy() ; CP = PGetPoiParam() ; logging(logfile,"\n ************* Physical_Parameters*********************"); logging(logfile,"\n Temperature P->Temp = %f",P->Temp); logging(logfile,"\n Band gap of Si E->g_si = %f",E->g_si); logging(logfile,"\n Band gap of Oxide E->g_ox = %f",E->g_ox); logging(logfile,"\n Dielectric constant of Si P->e_si = %le",P->e_si); logging(logfile,"\n Dielectric constant of Oxide P->e_ox = %le",P->e_ox); logging(logfile,"\n Gate workfunction offset P->offset_gate = %f",P->offset_gate); logging(logfile,"\n\n ************* Doping *********************"); double GetDopingDensityFor(char region); logging(logfile,"\n Source Doping GetDopingDensityFor('s') = %le", GetDopingDensityFor('s')); logging(logfile,"\n Channel Doping GetDopingDensityFor('c') = %le", GetDopingDensityFor('c')); logging(logfile,"\n Drain Doping GetDopingDensityFor('d') = %le", GetDopingDensityFor('d')); logging(logfile,"\n\n ************* Dimensions(nm) *********************"); logging(logfile,"\n Lsource[NoUnit] D->Lsrc =%f, Number of points N->Mx_src =%d",D->Lsrc,N->Mx_src); logging(logfile,"\n Lchannel[NoUnit]D->Lchannel =%f, Number of points N->Mx_channel =%d",D->Lchannel,N->Mx_channel); logging(logfile,"\n Tox[NoUnit] D->Tox =%f, Number of points N->Mz_ox =%d",D->Tox,N->Mz_ox); logging(logfile,"\n Tsi[NoUnit] D->Tsi =%f, Number of points N->Mz_si =%d",D->Tsi,N->Mz_si); logging(logfile,"\n Tbox[NoUnit] D->Tbox =%f, Number of points N->Mz_box =%d",D->Tbox,N->Mz_box); logging(logfile,"\n Wox[NoUnit] D->Wox =%f, Number of points N->My_ox =%d",D->Wox,N->My_ox); logging(logfile,"\n Wsi[NoUnit] D->Wsi =%f, Number of points N->My_si =%d",D->Wsi,N->My_si); logging(logfile,"\n Lgate[NoUnit] D->Lgate =%f",D->Lgate); logging(logfile,"\n Tgate[NoUnit] D->Tgate =%f",D->Tgate); logging(logfile,"\n Wgate[NoUnit] D->Wgate =%f",D->Wgate); logging(logfile,"\n\n ***************** Voltages * *********************"); double GetDrainVoltage(); double GetGateVoltage(); logging(logfile,"\n GetDrainVoltage() =%f, GetGateVoltage()=%f",GetDrainVoltage(),GetGateVoltage()); logging(logfile,"\n\n ************* POISSON::Control_Parameters **** **********"); logging(logfile,"\n Max Interation CP->MaxIter =%d",CP->MaxIter); logging(logfile,"\n Convergence_Eps CP->ConvEps =%le",CP->ConvEps); logging(logfile,"\n KSPType CP->ksptype =%s",CP->ksptype); logging(logfile,"\n PCType CP->pctype =%s",CP->pctype); logging(logfile,"\n KSP_Rtol CP->ksprtol =%le",CP->ksprtol); logging(logfile,"\n GMRES_Restart CP->gmres_restart =%d",CP->gmres_restart); fclose(logfile); return; } #include <stdarg.h> #include "constants.h" void logging(FILE *logfile,const char *fmt,...) // fmt la format kieu nhu frintf { #ifdef ENABLE_LOG va_list ap; va_start(ap,fmt); vfprintf(logfile, fmt, ap); //fprintf(logfile, "########################################\n"); va_end(ap); #endif } <file_sep>#include <stdio.h> #include "petscksp.h" #include "nanowire.h" static char help[] = "Solves Poisson equation in parallel with KSP" ; void Initialize(int *argc, char ***argv) { // initialize MPI void read_poisson_input(); void initialize_general_constants(); void set_position_z_direction(); void set_position_y_direction(); void set_position_x_direction(); void set_regions() ; void initialize_poisson() ; PetscInitialize(argc,argv,(char *)0,help);// KHONG Lay ra o ham main luon read_poisson_input(); // Doc tham so #POISSON_INPUT tu Input file initialize_general_constants(); // Chuyen 1 so constant ve dang DON VI VAT LY day du //printf("\n Vuot qua ham initialize_general_constants()"); set_position_z_direction(); //printf("\n Vuot qua ham set_position_z_direction()"); set_position_y_direction() ; //printf("\n Vuot qua ham set_position_y_direction()"); set_position_x_direction() ; //printf("\n Vuot qua ham set_position_x_direction()"); set_regions() ; //printf("\n Vuot qua ham set_regions()"); initialize_poisson() ; //printf("\n Vuot qua ham initialize_poisson()"); //printf("\n Ket thuc Initialize() o file init.c"); } void Finalize() { PetscFinalize() ; } <file_sep> #include "petscksp.h" #include "nanowire.h" #include "region.h" static PoiNum N; static int Ntot; static int entry; /****************************************************************************** Thay doi 1 vai cai de mapping code cua ta voi 3D Poisson INPUT: ***Phi = GetPot() cua Poisson Starting date: May 04, 2010 Latest update: May 04, 2010 ******************************************************************************/ void set_initial_potential() { if ( ++entry > 1 ) return ; void guess_potential() ; void make_flat_zero_potential() ; void mpi_distribute_potential_from_node0() ; // MPI int node, np ; MPI_Comm_rank(PETSC_COMM_WORLD,&node) ; MPI_Comm_size(PETSC_COMM_WORLD,&np) ; // begin FILE *fphi = fopen("pot.r","r") ; double ***Phi = GetPot() ; N = GetPoiNum() ; Ntot = N.x*N.y*N.z ; int i,j,k,nx,ny,nz ; double v ; if ( fphi != (FILE *)NULL ) { if ( node==0 ) { PetscPrintf(PETSC_COMM_WORLD,"\n*******\nREADING PHI FROM EXISTING FILE\n*******\n") ; fscanf(fphi,"%*s %d %d %d\n",&nx,&ny,&nz) ; if ( nx!=N.x || ny!=N.y || nz!=N.z ) report_error("Problems reading Phi's") ; for ( i=1 ; i<=nx ; i++ ) fscanf(fphi,"%*s") ; for ( j=1 ; j<=ny ; j++ ) fscanf(fphi,"%*s") ; for ( k=1 ; k<=nz ; k++ ) fscanf(fphi,"%*s") ; for ( i=0 ; i<N.x ; i++ ) for ( j=0 ; j<N.y ; j++ ) for ( k=0 ; k<N.z ; k++ ) { fscanf(fphi,"%le",&v) ; Phi[i][j][k] = -v ; } } mpi_distribute_potential_from_node0(node,np) ; } else guess_potential() ; // Print Midline Potential if ( GetPRINT_MidPotFlag() ) { void print_midline_potential_plain() ; void reset_print_midline_potential() ; print_midline_potential_plain("mpot.r0") ; } } void guess_potential() // Referenced by set_initial_potential(). { //****************Ta them vao******************* void mpi_distribute_potential_from_node0(int node, int np); // MPI int node, np ; MPI_Comm_rank(PETSC_COMM_WORLD,&node) ; MPI_Comm_size(PETSC_COMM_WORLD,&np) ; // begin N = GetPoiNum() ; // Neu khong du so du lieu thi lam sao ma ham guess_potential() chay dung duoc Ntot = N.x*N.y*N.z ; int nx,ny,nz ; double v ; //**********Het phan them vao*********************** int p,i,j,k,region ; Region R ; double Vd = GetDrainVoltage() ; double phi_source = GetPhi_Source() ; double phi_drain = GetPhi_Drain() ; double phi_gate = GetPhi_Gate() ; double ***Phi = GetPot() ; for ( p=1 ; p<=Ntot ; p++ ) { get_ijk(p,&i,&j,&k) ; region = GetRegion(&R,p) ; if ( i<N.xa ) { Phi[i][j][k] = phi_source; //printf("\n phi_source tai guess_potential = %f", phi_source); } else if ( i>N.xb ){ Phi[i][j][k] = phi_drain; //printf("\n phi_drain tai guess_potential = %f", phi_drain); } else { Phi[i][j][k] = (phi_drain-phi_source)/(N.xb-N.xa)*(i-N.xa)+phi_source; } if ( GATE_CONTACT ){ Phi[i][j][k] = phi_gate; //printf("\n phi_gate tai guess_potential = %f", phi_gate); } }// End of for ( p=1 ; p<=Ntot ; p++ ) { //************Ta them vao********************* // Print Midline Potential if ( GetPRINT_MidPotFlag() ) { void print_midline_potential_plain() ; void reset_print_midline_potential() ; print_midline_potential_plain("mpot.r0") ; } }// End of void guess_potential() /* Ham nay duoc dinh o definefn.c nhung de o day cho tien theo doi void SetPhi_Contact() { void assign_built_in_potential() ; assign_built_in_potential() ; printf("\n ********** From SetPhi_Contact() *********"); double Vd = GetDrainVoltage() ; printf("\n Drain Voltage Vd = %f", Vd); double Vg = GetGateVoltage() ; printf("\n Gate Voltage Vg = %f", Vg); Phi_Source = E.biS ; printf("\n Phi_Source = %f",Phi_Source); Phi_Drain = E.biD + Vd ; printf("\n Phi_Drain = %f",Phi_Drain); Phi_Gate = Vg - P.offset_gate ; // for n-mos; //Phi_Gate = -Vg + P.offset_gate + Vd ; // for p-mos with CB_PEMT mode printf("\n Phi_Gate = %f",Phi_Gate); //printf("\n ********** Ket thuc SetPhi_Contact() *********");// getchar(); } double GetPhi_Source() { return(Phi_Source) ; } double GetPhi_Drain() { return(Phi_Drain) ; } double GetPhi_Gate() { return(Phi_Gate) ; } ***************************************************************************************************************************/ void assign_built_in_potential() // Referenced by SetPhi_Contact().Ta da sua lai 1 it roi ( June 10, 2010) { Energy *E = PGetEnergy() ; Param *P = PGetParam() ; double kT = GetKT() ; //printf("\n ******From assign_built_in_potential() ******"); double EF = GetEF() ; //printf("\n EF = %f",EF); double EFnS = GetEFnS() ; //printf("\n EFnS = %f",EFnS); double EFnD = GetEFnD() ; //printf("\n EFnD = %f",EFnD); // Built-in Potentials /* Sua lai xem duoi. Cai nay la cua GS E->biS = EFnS - EF ; printf("\n Built-in potential E->biS = %f",E->biS); E->biD = EFnD - EF ; printf("\n Built-in potential E->biD = %f",E->biD); */ //******************************************************************* // Minh them vao de tinh built-in potential double *Get_doping_density(); double *doping_density = Get_doping_density();//1,2 or 3 ->S,D or Channel double Get_Vt(); double Vt = Get_Vt(); double Get_intrinsic_carrier_density(); double intrinsic_carrier_density = Get_intrinsic_carrier_density(); double factor = 0.0, dop_temp =0.0, built_in_S =0.0, built_in_D=0.0 ; // Tinh built-in potential tai Source dop_temp = doping_density[1];// Doping tai Source dop_temp = 0.5*dop_temp/intrinsic_carrier_density; // (May 26, 2010) Lam viec thieu can than la the day ! if(dop_temp > 0.0){ // Hien nhien la the do ta dope la n-type factor = dop_temp + sqrt(dop_temp*dop_temp + 1.0); built_in_S = Vt*log(factor); } else { // dop_term <= 0.0. Trong truong hop nay khong xay ra nhung van lam dop_temp = - dop_temp; factor = dop_temp + sqrt(dop_temp*dop_temp + 1.0); built_in_S = - Vt*log(factor); } // Tinh built-in potential tai Drain dop_temp = doping_density[2]; // Doping tai Drain dop_temp = 0.5*dop_temp/intrinsic_carrier_density; //(May 26, 2010) if(dop_temp > 0.0){ // Hien nhien la the do ta dope la n-type factor = dop_temp + sqrt(dop_temp*dop_temp + 1.0); built_in_D = Vt*log(factor); } else { // dop_temp <= 0.0. Trong truong hop nay khong xay ra nhung van lam dop_temp = - dop_temp; factor = dop_temp + sqrt(dop_temp*dop_temp + 1.0); built_in_D = - Vt*log(factor); } //printf("\n built_in_S =%f, built_in_D =%f", built_in_S, built_in_D ); getchar(); // Ket thuc phan minh them vao //************************************************************************************** // Built-in Potentials. Can sua lai the nay E->biS = built_in_S ;//printf("\n Built-in potential E->biS = %f",E->biS); E->biD = built_in_D ;// printf("\n Built-in potential E->biD = %f",E->biD); getchar(); //******************************************************************* // Gate Offset //printf("\n Before P->offset_gate = %f, E->c_si = %f ",P->offset_gate, E->c_si); //P->offset_gate -= (E->c_si - EF) ; // Do xay ra loi khi chay Poisson lan thu 2, 3, 4 vi gia tri P->offset_gate cu bi tru di. Nen ta set luon no la 0 cho tien P->offset_gate = 0.0; // printf("\n After P->offset_gate = %f",P->offset_gate); //printf("\n ******Ket thuc assign_built_in_potential() ******"); } //******************************************************************************************** void make_flat_zero_potential(int zflag) // KHONG Thay dung ham nay { int p,i,j,k,region ; Region R ; double ***Phi = GetPot() ; if ( zflag == 0 ) PetscPrintf(PETSC_COMM_WORLD,"\n******\n FLAT ZERO POTENTIAL \n******\n") ; int Nyz = N.y*N.z ; for ( p=1 ; p<=Nyz ; p++ ) { get_ijk(p,&i,&j,&k) ; region = GetRegion(&R,p) ; Phi[i][j][k] = 0.0 ; } } void mpi_distribute_potential_from_node0(int node, int np) // Referenced by set_initial_potential(). { int x0,y0,z0,x1,y1,z1 ; int n,dest,datasize,ntrans,p0,sum_transmitted,tag ; int trans_size = GetTransSize(); //printf("\n Trans size = %d",trans_size); MPI_Status status ; double ***Pot ; Pot = GetPot() ; x0 = N.x0-1 ; x1 = N.x1+1 ; y0 = N.y0-1 ; y1 = N.y1+1 ; z0 = N.z0-1 ; z1 = N.z1+1 ; datasize = (x1-x0+1)*(y1-y0+1)*(z1-z0+1) ; ntrans = datasize/trans_size ; if ( node==0 ) { for ( dest=1 ; dest<np ; dest++ ) { p0 = 0 ; sum_transmitted = 0 ; tag = 0 ; for ( n=1 ; n<=ntrans ; n++ ) { MPI_Send(&Pot[x0][y0][z0]+p0,trans_size,MPI_DOUBLE,dest,++tag,PETSC_COMM_WORLD) ; p0 += trans_size ; sum_transmitted += trans_size ; } if ( sum_transmitted < datasize ) MPI_Send(&Pot[x0][y0][z0]+p0,datasize-sum_transmitted,MPI_DOUBLE,dest,++tag,PETSC_COMM_WORLD) ; } } else { p0 = 0 ; sum_transmitted = 0 ; tag = 0 ; for ( n=1 ; n<=ntrans ; n++ ) { MPI_Recv(&Pot[x0][y0][z0]+p0,trans_size,MPI_DOUBLE,0,++tag,PETSC_COMM_WORLD,&status) ; p0 += trans_size ; sum_transmitted += trans_size ; } if ( sum_transmitted < datasize ) MPI_Recv(&Pot[x0][y0][z0]+p0,datasize-sum_transmitted,MPI_DOUBLE,0,++tag,PETSC_COMM_WORLD,&status) ; } } // End of void mpi_distribute_potential_from_node0(int node, int np) <file_sep>#ifndef _CONSTANT_ #define _CONSTANT_ /* Physical Constant*/ #define pi 3.14159265358979 /* pi number viet 3.14 co nghia la kieu du lieu la double */ #define hbar 1.05459e-34 /* Planck's constant/2PI in J-sec */ #define m0 9.10953e-31 /* Electron rest mass in kg */ #define q 1.60219e-19 /* Electron charge */ #define kb 1.3806505e-23 /* Boltzmann constant J/Kelvin */ #define eps_0 8.85419e-12 /* Permittivity of free space. unit F/m */ /* For Monte Carlo */ #define max_electron_number 200000 /* maximum number of simulated electrons */ #define max_subband_number 30 // tinh trong 1 valley #define averaging_time 5.0e-13 /* [s] time to average/print data*/ /* For 2D Schrodinger */ #define beta 13.123288895 /* unit [1/eVnm**2], beta=m0/(hbar*hbar)*q*(1.0e-9*1.0e-9); /* Parameters of scattering table */ #define n_lev 1000 // # of energy levels in the scattering table #define n_scatt_max 10 // maximum # of scattering mechanisms /* For device geometry */ #define nx_size 400 // number of points in x-direction #define ny_size 200 // number of points in y-direction #define nz_size 200 // number of points in y-direction // Mac du doc tu Input file gia tri n_gate nhung ta chon max cua no la ny_size_negative /* De tao cac logfile: 1 Save logfie, KHAC 1 la Khong save */ #define ENABLE_LOG 1 #endif //_CONSTANT_ <file_sep>/* *********************************************************************** To INITIALIZE CARRIER ENERGY AND WAVEVECTOR ACCORDING TO THE MAXWELL-BOLTZMANN STATISTICS - Initial electron energy using thermal energy in 1D do o day ta dung 1D transport. Day la DONG NANG thoi - Initial momentum of electrons - Initial valley and subband where the particle is residing for the first time Matrix p[][] (parameters for particle) p[n][1] = kx (is stored kx) p[n][2] = x p[n][3] = is to store ts (ts or tc is free flight time) p[n][4] = i_region (which region we are considering?) Array valley[]: hat thu n-th nam o vallye pair nao valley[n] =1 : valley pair 1 valley[n] =2 : valley pair 2 valley[n] =3 : valley pair 3 Matran subband[n]: de chua subband index cua hat thu n-th Array energy[n]: electron energy of the n-th particle NOTE: ta hoan toan co the de cac gia tri valley, subband, energy cua n-th particle vao mang p[][] luon. Nhung tach ra nhu ta de cho no truc quan hon Starting date: Feb 21, 2010 Update: Feb 22, 2010 Update: March 29, 2010. Hien tai chua dung i_region va neu dung thi CAU HOI se la co CAN THIET update ca vi tri theo phuong y va z khong? Latest update: May 06, 2010 (De phu hop voi 3D Poisson) ************************************************************************** */ #include <math.h> #include <stdio.h> #include "constants.h" void init_kspace(int ne,int i){// March 29, 2010 //void init_kspace(int ne,int i,int j,int k){// ne-th electron to inilitialize at cell(i,j,k) // Goi cac ham double **Get_p(),*Get_energy(); int *Get_valley(),*Get_subband(); double Get_Vt(),Get_ml(),Get_mt(),Get_nonparabolicity_factor(); long Get_idum(); float random2(long *idum); int Get_nx0(),Get_nx1(); // Cac bien local double **p = Get_p(); double *energy = Get_energy(); int *valley = Get_valley(); int *subband = Get_subband(); double Vt = Get_Vt(); double ml = Get_ml(); double mt = Get_mt(); double af = Get_nonparabolicity_factor(); long idum = Get_idum(); int nx0 = Get_nx0(); int nx1 = Get_nx1(); // Thuc hien double k_momen = 0.0,kx = 0.0, electron_energy = 0.0; // k_momen la bien cho momentum TRANH nham voi k la bien chay cho truc z int iv = 0, subband_index = 0; // iv: valley index; i_region = 0 // Initial particle energy (using Boltzman statistics) double rr = 0.0; do { rr=random2(&idum); } while ((rr<=1.0e-6)||(rr>1.0)); // Day chi la DONG NANG thoi electron_energy = -(0.5*Vt)*log(rr); //[eV]// printf("\n electron energy =%f",electron_energy); // electron energy in 1D //Khoi tao valley index - Tu do khoi tao momentum va subband tuong ung trong valley do rr = 3.0*random2(&idum); //iv valley index luc initial thi chon theo random number if(rr <=1.0){ iv=1; //valley index =1 <- valley pair 1, m*=ml // Initial wavevector k_momen = sqrt(2.0*m0*ml)*sqrt(q)/hbar*sqrt(electron_energy*(1+af*electron_energy)); // Don vi chuan // Nhan manh: sqrt(q) la de chuyen energy sang don vi J. Nhung de ra ngoai vi cong thuc // sqrt(electron_energy(1+af*electron_energy))thi electron_energy phai la eV va af[1/eV] // NHAN MANH: electron_energy o day la DONG NANG kx = k_momen; // 1D transport // Khoi tao subband trong valley do subband_index = 1; // assumed o subband DAU TIEN } else if(rr <=2.0){ iv=2; //valley index =2 <- valley pair 2, m*=mt // Initial wavevector k_momen = sqrt(2.0*m0*mt)*sqrt(q)/hbar*sqrt(electron_energy*(1+af*electron_energy)); kx = k_momen; // Khoi tao subband trong valley do subband_index = 1; // assumed o subband DAU TIEN } else { // if(rr <=3.0) ; iv=3; //valley index =3 <- valley pair 3, m*=mt // Initial wavevector k_momen = sqrt(2.0*m0*mt)*sqrt(q)/hbar*sqrt(electron_energy*(1+af*electron_energy)); kx = k_momen; // Khoi tao subband trong valley do subband_index = 1; // assumed o subband DAU TIEN } // Khoi tao region dua vao toa do (i,j,k) cua hat //i_region = find_region(i,j,k); // tim duoc hat dang o region nao: 1:S, 2:D, 3:Channel // Check boundaries if((i==nx0)&&(kx<0.0)) { kx = -kx; } //reflection if((i==nx1)&&(kx>0.0)) { kx = -kx; } // Vi chua co bang scattering nen chua the Initial free-flight // Map particle atributes p[ne][1] = kx; // Don vi chuan // p[ne][2] = x; // in init_realspace() function // p[ne][3] = ts or tc; //in init_free_flight() phai sau khi tinh bang scattering //p[ne][4] = i_region; //29/03/10 15:44. Hien tai chua dung valley[ne] = iv; subband[ne] = subband_index; energy[ne] = electron_energy;// [eV] electron energy of particle neth //printf("\n Ket qua: kx=%le region=%d valley=%d subband=%d energy=%le",kx, i_region,iv,subband_index,electron_energy); //printf("\n Ket qua: kx=%le region=%d valley=%d subband=%d energy=%le", //p[ne][1],(int)(p[ne][4]),valley[ne],subband[ne],energy[ne] ); //printf("\n Tu init k-space kx=%le",kx); //getchar(); return; } <file_sep>/* *********************************************************************** To count the number of used electrons Starting date: Feb 22, 2010 Latest update: Feb 22, 2010 ************************************************************************* */ #include <stdio.h> #include "constants.h" int count_used_particles(){ // ne here is the number of electrons using in the simulator // Goi ham int *Get_valley(); // Ta su dung bien valley[] thay cho bien ip[] o Semiclassical MC // Bien local int *valley = Get_valley(); //Thuc hien int i, ne = 0; for(i=1; i<=max_electron_number; i++){ if(valley[i] != 9) { // KHAC 9 co nghia la hat dang duoc SU DUNG ne = ne + 1; } } //printf("\n Number of electrons using = %d ",ne); return ne; }
8445f458d5cc2f80cc43b2bd83746669a209f0a4
[ "Markdown", "C", "Makefile" ]
58
C
tuantla80/Multi-subband-Monte-Carlo
b7bfee0351c5b7e1ba479624b569c193fd0c4144
d9ad0a8f58772ae0c0c37e98851f22d32f153b8b
refs/heads/master
<repo_name>Sonray/Personal-blog-IP4<file_sep>/app/main/views.py from flask import render_template, request, redirect, url_for, abort, flash from flask_login import login_required, current_user import secrets import os from app import db from app.email import mail_message from app.main.forms import UpdateAccountForm, PostForm, SubscribeForm, CommentForm from app.models import User, Post, Subscription, Comments from . import main @main.route('/', methods=['GET', 'POST']) def index(): """ View root page function that returns the index page and its data """ title = 'Home' page = request.args.get('page', 1, type=int) posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=4) form = SubscribeForm() if form.validate_on_submit(): email = Subscription(email=form.email.data) db.session.add(email) db.session.commit() return render_template('index.html', title=title, posts=posts, form=form) @main.route('/about') def about(): title = 'About Us' return render_template('about.html', title=title) def save_picture(form_picture): random_hex = secrets.token_hex(8) _, f_ext = os.path.splitext(form_picture.filename) picture_fn = random_hex + f_ext picture_path = os.path.join(app.root_path, 'static/profile/', picture_fn) form_picture.save(picture_path) current_user.image_file = picture_fn image_file = url_for('static', filename='profile/' + current_user.image_file) @main.route("/user", methods=['GET', 'POST']) @login_required def profile(): form = UpdateAccountForm() if form.validate_on_submit(): if form.picture.data: picture_file = save_picture(form.picture.data) current_user.username = form.username.data current_user.email = form.email.data db.session.commit() return redirect(url_for('main.profile')) elif request.method == 'GET': form.username.data = current_user.username form.email.data = current_user.email image_file = url_for('static', filename='profile/' + current_user.image_file) return render_template('profile/profile.html', title='Account', image_file=image_file, form=form) @main.route("/post/new", methods=['GET', 'POST']) @login_required def new_post(): if current_user.username != 'davidokwacha': abort(403) form = PostForm() if form.validate_on_submit(): post = Post(title=form.title.data, content=form.content.data) db.session.add(post) db.session.commit() subs = Subscription.query.all() for sub in subs: mail_message("New ", "email/new_post", sub.email) return redirect(url_for('main.index')) return render_template('create_post.html', title='New Post', form=form, legend='New Post') @main.route("/post/<int:post_id>", methods=['GET', 'POST']) def post(post_id): post = Post.query.get_or_404(post_id) form = CommentForm() if form.validate_on_submit(): comment = form.comment.data new_comment = Comments(comment=comment, post_id=post_id, user=current_user) new_comment.save_comments() return redirect(url_for('main.post', post_id=post.id)) comments = Comments.query.filter_by(post_id=post_id).all() return render_template('post.html', title=post.title, post=post, comment_form=form, comments=comments) @main.route("/post/<int:post_id>/update", methods=['GET', 'POST']) @login_required def update_post(post_id): post = Post.query.get_or_404(post_id) if current_user.username != 'davidokwacha': abort(403) form = PostForm() if form.validate_on_submit(): post.title = form.title.data post.content = form.content.data db.session.commit() return redirect(url_for('main.post', post_id=post.id)) elif request.method == 'GET': form.title.data = post.title form.content.data = post.content return render_template('create_post.html', title='Update Post', form=form, post=post, legend='Update Post') @main.route("/post/<int:post_id>/delete", methods=['POST']) @login_required def delete_post(post_id): post = Post.query.get_or_404(post_id) if current_user.username != 'davidokwacha': abort(403) db.session.delete(post) db.session.commit() return redirect(url_for('main.index')) @main.route("/comment/<int:comment_id>", methods=['GET', 'POST']) def comment(comment_id): comment = Comments.query.get_or_404(comment_id) return render_template('comment.html', title='Comment', comment=comment) @main.route("/comment/<int:comment_id>/delete", methods=['POST', 'GET']) @login_required def delete_comment(comment_id): comment = Comments.query.get_or_404(comment_id) if current_user.username != 'davidokwacha': abort(403) db.session.delete(comment) db.session.commit() return redirect(url_for('main.index'))<file_sep>/app/main/forms.py from flask_login import current_user from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed from wtforms.validators import Email, Length, Required, EqualTo from wtforms import ValidationError, PasswordField from wtforms import StringField, SubmitField, TextAreaField from app.models import User, Subscription class UpdateAccountForm(FlaskForm): username = StringField('Username', validators=[Length(min=2, max=20)]) email = StringField('Your Email Address', validators=[Email()]) picture = FileField('Change Profile Picture', validators=[FileAllowed(['jpg', 'png'])]) submit = SubmitField('Update information') def validate_username(self, username): if username.data != current_user.username: user = User.query.filter_by(username=username.data).first() if user: raise ValidationError('That username is taken. Please choose a different one.') def validate_email(self, email): if email.data != current_user.email: user = User.query.filter_by(email=email.data).first() if user: raise ValidationError('That email is taken. Please choose a different one.') class PostForm(FlaskForm): title = StringField('Title', validators=[Required()]) content = TextAreaField('Content', validators=[Required()]) submit = SubmitField('Post') class SubscribeForm(FlaskForm): email = StringField('Email address', validators=[Required(), Email()]) submit = SubmitField('Subscribe') def validate_email(self, email): email = Subscription.query.filter_by(email=email.data).first() if email: raise ValidationError('That email is already subscribed to our emailing list.') class CommentForm(FlaskForm): comment = StringField('Comment: ', validators=[Required()]) submit = SubmitField('Submit') <file_sep>/app/models.py from datetime import datetime from flask import url_for, app, config from werkzeug.utils import redirect from . import db from flask_login import UserMixin from . import login_manager from werkzeug.security import generate_password_hash, check_password_hash class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(255), unique=True, nullable=False) email = db.Column(db.String(255), unique=True, index=True, nullable=False) image_file = db.Column(db.String(70), nullable=False, default='default.jpg') comments = db.relationship('Comments', backref='user', lazy='dynamic') def __repr__(self): return f'User {self.username}' pass_secure = db.Column(db.String(255)) @property def password(self): raise AttributeError('You cannot read the password attribute') @password.setter def password(self, password): self.pass_secure = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.pass_secure, password) @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255), unique=True, nullable=False) date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) content = db.Column(db.Text, nullable=False) author = db.Column(db.String(15), nullable=False, default='<NAME>') comment = db.relationship('Comments', backref='post', lazy='dynamic') def __repr__(self): return f"Post( '{self.title}', '{self.date_posted}')" class Subscription(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True, index=True, nullable=False) def __repr__(self): return f'{self.email}' class Comments(db.Model): __tablename__ = 'comments' id = db.Column(db.Integer, primary_key=True) comment = db.Column(db.String(10000)) post_id = db.Column(db.Integer, db.ForeignKey("posts.id")) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) def save_comments(self): db.session.add(self) db.session.commit()
1cfad94712cab1bb247c20fb9292ff55e81d9c53
[ "Python" ]
3
Python
Sonray/Personal-blog-IP4
6dcc122f7394a746ca3f8cf4f8095bfa6adb7473
404f256b278719194f8e9789ced00ff36f645b5a
refs/heads/main
<repo_name>SarahRDH/jspractice<file_sep>/app-advfunc.js function add(x, y) { return x + y; } const subtract = function (x, y) { return x - y; } const multiply = function (x, y) { return x * y; } const divide = function (x, y) { return x / y; } const operations = [add, subtract, multiply, divide]; //call operations[0](100, 4) to add //or call operations[1](5, 4) to subtract //etc for (let func of operations) { let result = func(30, 5); console.log(result); // gives answers for add, sub, mult, div of 30 and 5 } //adding a function to an object creates a method! const thing = { doSomething: multiply } //run thing //shows that it is an obj //run thing.doSomething //shows that it is an object containing the function multiply(x,y) return x*y //run thing.doSomething(50,2) //returns 100 //------------------------------------ //higher order functions are functions that accept functions as arguments OR return a function function callThreeTimes(f,g) { f(); f(); f(); g(); } function cry() { console.log('boo hoo i am so sad'); } function rage() { console.log('I hate everything'); } function repeatNTimes(action, num) { for (let i = 0; i < num; i++) { action(); } } repeatNTimes(rage, 13); function pickOne(f1, f2) { let rand = Math.random(); console.log(rand); if (rand < 0.5) { f1(); } else { f2(); } } //93. functionas as return values // const triple = multiplyBy(3); // triple(5);//15 // const double = multiplyBy(2); // double(8);//16 function multiplyBy(num) { return function(x) { return x * num; } } //this way of writing triple is the same as below // const triple = function (x) { // return x * 3; // } // triple(3); //returns 9 //this way of writing triple is the same as above const triple = multiplyBy(3); const double = multiplyBy(2); const quintuple = multiplyBy(5); //could write makeBetweenFunc this way OR // function makeBetweenFunc(x,y) { // return function(num) { // if (num >= x && num <= y) { // return true; // } // return false; // } // } function makeBetweenFunc(x,y) { return function(num) { return num >= x && num <= y; } } //could write isChild like this OR // makeBetweenFunc(0,18); // const isChild = function (num) { // return num >= 0 && num <= 18; // } const isChild = makeBetweenFunc(0,18); isChild(17); const isNineties = makeBetweenFunc(1990, 2000); const isNiceWeather = makeBetweenFunc(60-79); //callbacks function callTwice(func) { func(); func(); } function laugh() { console.log("hahahahah"); } callTwice(laugh);//here, laugh is the callback function function grumpus() { alert("ga go away"); } //setTimeout(func, 5000) //setTimeout expects a function and some milliseconds to wait until executing that funcion. // setTimeout(grumpus, 5000); setTimeout(function() { //pass in anonymous function that you don't have to use anywhere else again alert('whoa'); }, 2000); const btn = document.querySelector('button'); // btn.addEventListener('click', grumpus); btn.addEventListener('click', function() { alert("why did you click me"); });<file_sep>/fnct-chlg.js function isValid(password, username) { if (password.length >= 8 && password.indexOf(' ') !== -1 && password.indexOf(username) !== -1) { return true; } else { return false; } } // function isValid(password, username) { // if (password.length < 8) { // return false; // } // if (password.indexOf(' ') !== -1) { // return false; // } // if (password.indexOf(username) !== -1) { // return false; // } // return true; // } const arrOne = [0, 50]; const arrTwo = [75, 76, 80, 95, 100]; function takeAvg(arr) { let sum = 0; //don't forget to set variable to zero outside the for loop for (let x of arr) { sum += x; } let avg = sum / arr.length; //could just say return avg = sum / arr.length; console.log(sum); return avg; } // function isPangram(words) { // //.sort the string // //.split the string // //.split the alphabet // //compare .indexOf both chars // let alphabet = 'abcdefghijklmnopqrstuvwxyz'; // let sentence = 'The quick brown fox jumped over the lazy dog'; // let sentenceChars = sentence.split(''); // let alphaArr = alphabet.split(''); // console.log(sentenceChars); // console.log(alphaArr); // if (words.indexOf(alphaArr) === -1) { // return true; // } // return false; // } function isPangram(words) { let lowerWords = words.toLowerCase(); let alphabet = 'abcdefghijklmnopqrstuvwxyz'; for (let char of alphabet) { if (lowerWords.indexOf(char) === -1) { console.log(char); //this prints some of the missing letters! I didn't mean for it too, but it does... return false; //if (!lowerWords.includes(char)) { //return false; //} } } return true; } function pick(arr) { const idx = Math.floor(Math.random() * arr.length); return arr[idx]; } //another way to write getCard using a helper function so we don't have to duplicate code function getCard() { const myValue = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'K', 'Q']; const value = pick(myValue); const mySuit = ['clubs', 'hearts', 'diamonds', 'spades']; const suit = pick(mySuit); return {value: value, suit: suit}; } // function getCard() { // const myValue = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'K', 'Q']; // const valIdx = Math.floor(Math.random() * myValue.length); // const value = myValue[valIdx]; // const mySuit = ['clubs', 'hearts', 'diamonds', 'spades']; // const suitIdx = Math.floor(Math.random() * mySuit.length); // const suit = mySuit[suitIdx]; // return {value: value, suit: suit}; // } <file_sep>/app-methods.js //forEach const numbers = [20, 21, 22, 23]; numbers.forEach(function (num) { //uses an anonymous function to do the same thing as below console.log(num * 2); }) function printTriple(n) { //uses a reusable function to do the same thing as above console.log(n * 3); } numbers.forEach(printTriple); const books = [{ title: 'Good Omens', authors: ['<NAME>', '<NAME>'], rating: 4.25, genres: ['fiction', 'fantasy'] }, { title: 'Bone: The Complete Edition', authors: ['<NAME>'], rating: 4.42, genres: ['nonfiction', 'essays'] }, { title: 'Changing My Mind', authors: ['<NAME>'], rating: 3.83, genres: ['nonfiction', 'essays'] }, { title: 'American Gods', authors: ['<NAME>'], rating: 4.11, genres: ['fiction', 'fanatasy'] }, { title: 'The Way of Kings', authors: ['<NAME>'], rating: 4.65, genres: ['fantasy', 'epic'] } ] books.forEach(function(book) { console.log(book.title.toUpperCase()); }) //or write it with a for of loop for (let book of books) { console.log(book.title.toUpperCase()); } //or write it with a good ole for loop for (let i = 0; i < books.length; i ++) { console.log(books[i].title.toUpperCase()); } numbers.forEach(function (num, idx) { console.log(idx, num); }) //map const texts = ['rofl', 'lol', 'omg', 'ttyl']; const caps = texts.map(function (t) { return t. toUpperCase(); }) texts; //rofl, lol, omg, ttyl caps; //ROFL, LOL, OMG, TTYL const words = ['asap', 'byob', 'rsvp', 'diy']; const doubles = numbers.map(function(num) { return num *2; }) const evenOdd = numbers.map(function(n) { return { value: n, isEven: n % 2 === 0 } }) const doubles2 = []; for (let num of numbers) { doubles2.push(num * 2) //this is pushing each number one at a time into the new array. a better way is to use .map } const abbrevs = words.map(function(word) { return word.toUpperCase().split('').join('.'); }) const titles = books.map(function (b) { return b.title; }) //arrow functions explanation const square2 = function(x) { return x * x; } const square = (x) => {//can take the parens off! return x * x; } const isEven = (num) => { return num % 2 === 0; } const isEven2 = function (num) { return num % 2 === 0; } const multiply = (x, y) => {//can not take the parens off! return x * y; } const greet = () => { console.log('hi'); } //three ways to write the same thing more simply, but you can only use this if there is only one thing to return in the function. const square3 = n => { return n * n; //normal arrow function } const square4 = n => ( n * n //implicit return without word 'return' or curlys or ; ) const square5 = n => n * n; //one liner still needs ; const nums = [0, 2, 3, 4, 5, 6, 7]; const dbl1 = nums.map(function (num) { return num * 2; }) const dbl2 = nums.map(num => { return num * 2; }) const dbl3 = nums.map(num => num * 2); //end arrow functions //find //find returns the value of the first element in the array that meets the requirements let movies = [ 'The Fantastic Mr. Fox', 'Mr. and Mrs. Smith', 'Mrs. Doubtfire', 'Mr. Deeds' ] const movie = movies.find(movie => { return movie.includes('Mrs'); //returns mr and mrs smith because it's the first one it came to with mrs in it somewhere }) const movie2 = movies.find(movie => { return movie.indexOf('Mrs') === 0; //returns mrs doubtfire because it's the first mrs at index 0 of each string }) const goodBook = books.find(b => b.rating >= 4); const neilBook = books.find(b => b.authors.includes('<NAME>')); //filter //returns a new array with the filtered out info const nums2 = [34, 35, 67, 89, 34, 25, 9]; const odds = nums2.filter(n => n % 2 === 1); const evens = nums2.filter(n => n % 2 === 0); const bigNums = nums2.filter(n => nums2 > 50); const goodBooks = books.filter(b => b.rating > 5); const fantasyBooks = books.filter(book => ( book.genres.includes('fantasy') )); const shortForm = books.filter(book => ( book.genres.includes('short stories') || book.genres.includes('essays') )); const query = 'THE'; //searches the object books for the title including 'the' in any case const results = books.filter(book => { const title = book.title.toLowerCase(); return title.includes(query.toLowerCase()) }); //every and some //every is boolean test function. does every element in this array have x? const words2 = ['dot', 'dig', 'log', 'bag', 'wag']; const all3Lets = words2.every(word => word.length === 3); //returns true const allEndInG = words2.every(word => { //returns false const last = word.length -1; return word[last] === 'g' }); //some is boolean test function. do some elements in ths array have x? const someStartD = words2.some(word => word[0] === 'd'); const everyStartD = words2.every(word => word[0] === 'd'); const allGoodBooks = books.every(book => book.rating > 3.5); const anyGoodAuthors = books.some(book => book.author === 2); //sort const prices = [400.50, 3000, 99.99, 35.99, 12.00, 9500]; //just calling sort() will return 12, 3000, 35.99, 400.5, 9500, 99.9, 9 prices.sort(); //without a callback function, sort converts numbers into strings and compares the stings which isn't correct //so we use arr.sort(compare(a, b)) //compare(a,b) will subtract either a - b or b - a (whatever we specify) and order the elements either in ascending or descending order (whatever we specify) const ascendingSort = prices.sort((a, b) => a - b);//but sort mutates the original array const descendingSort = prices.sort((a, b) => b - a); //but sort mutates the original array //so we should slice them first to save them as separate arrays const badSort = prices.slice().sort(); const ascSort = prices.slice().sort((a, b) => a - b); const descSort = prices.slice().sort((a, b) => b - a); books.sort((a, b) => b.rating - a.rating); //reduce const nums3 = [3, 4, 5, 6, 7]; const product = nums3.reduce((total, currentVal) => { return total * currentVal; }); let grades = [89, 96, 58, 77, 62, 93, 81, 99, 73]; const topScore = grades.reduce((accumulator, currVal) => { if (currVal > accumulator) return currVal; return accumulator; }) topScore; const maxGrade = grades.reduce((max, currVal) => { return Math.max(max, currVal) //Math.max or Math.min will return the max or min number in an array }); const minGrade = grades.reduce((min, currVal) => ( //implicit return without {} Math.min(min, currVal) )); const sums = [10, 20, 30, 40, 50].reduce((sums, currVal) => { return sums + currVal; }) const sums2 = [10, 20, 30, 40, 50].reduce((sums2, currVal) => { return sums2 + currVal; }, 1000) //setting the initial value to 1000 as the starting accumulator, so will return 1150 instead of 150 //using reduce for an object const votes = ['y', 'y', 'n', 'y', 'y', 'y', 'n', 'y', 'n', 'n', 'n', 'y', 'y', 'undecided']; // const results = votes.reduce(( , ), {}); //initial value is set to an empty object so it can fill it const results1 = votes.reduce((tally, val) => { if(tally[val]) { tally[val]++; } else { tally[val] = 1; } return tally }, {}); // { // y: 12, // n: 5 // } // const results = votes.reduce((tally, val)) => { //another way to write the same thing // tally[val] = (tally[val] || 0) + 1; // return tally; // }, {}) const groupedByRatings = books.reduce((groupedBooks, book) => { const key = Math.floor(book.rating); if(!groupedBooks[key]) groupedBooks[key] = []; groupedBooks[key].push(book) return groupedBooks; }, {}) <file_sep>/app.js //alert("it's alive!"); if (1==1) { console.log("it's true!"); } let rating = 5; if (rating === 3) { console.log('you are a superstar!'); } // rating =2; else if (rating === 2) { console.log('meets expectaions'); } else if (rating === 1) { console.log('needs improvement'); } else { console.log('whoops'); } let highScore = 1430; let userScore = 1500; if(userScore >= highScore) { console.log(`Congrats, you have new high score of ${userScore}`); //now update userScore to be the new high score highScore = userScore; } else { console.log(`Good game! your score of ${userScore} did not beat the high score of ${highScore}`); } console.log(highScore); // let num = 37; // if (num % 2 !== 0) { // console.log('odd number!'); // } // let password = '<PASSWORD>'; // if (password.length >= 6) { // if (password.indexOf(' ') === -1) { // console.log("valid password!"); // } // else { // console.log("password is long enough, but cannot contain spaces"); // } // } // else { // console.log("password must be longer"); // } let password = "<PASSWORD>"; if (password.length >= 6 && password.indexOf(' ') === -1) { console.log("valid password!"); } else { console.log("invalid password"); } let num = 3; if(num >= 1 && num <=10) { console.log('number is 1 -10'); } else { console.log('please guess again'); } let mystery = 'string'; if (mystery) { //when there is no comparision, it's implied you're asking "is this parameter true" console.log('truthy'); } else { console.log('falsey'); } let day = 3; // if (day === 1) { // console.log("monday"); // } switch (day) { case 1: console.log("monday"); break; //without the break, it will console log monday and tuesday- until it sees the next break case 2: console.log("tuesday"); break; case 3: console.log("tuesday"); break; case 4: console.log("tuesday"); break; case 5: console.log("tuesday"); break; case 6: console.log("tuesday"); break; case 7: console.log("tuesday"); break; } //ternary operators let num2 = 7 ; // if (num2 === 7) { // console.log('lucky!'); // } // else { // console.log('bad!'); // } // write the same thing as a ternary statement num2 === 7 ? console.log('lucky') : console.log('bad!'); // let status = "offline"; // let color; // if (status === "offline") { // color = "red"; // } // else { // color = "green"; // } // console.log(color); let color = status === 'offline' ? 'red' : 'green'; console.log(color); let shoppingList = ['cereal', 'cheese', 'ice']; shoppingList[1] = "whole Milk"; shoppingList[2] = 'ice cream'; shoppingList[shoppingList.length] = 'tomatoes'; let lotto = [45, 12, 23, 24]; let myCollection = [12, 'dog', true, null, NaN]; // new Array() // let myArray[] let topSongs = [ 'first time ever i saw your face', 'god only knows', 'a day in the life', 'life on mars' ]; topSongs.push('fortunate son'); let dishesToDo = ['plate', 'cup', 'fork']; dishesToDo.unshift('fork', 'knife'); let fruits = ["apple", "banana"]; let veggies = ["carrot", "asparagus"]; console.log(fruits.concat(veggies)); let ingredients = [ 'water', 'corn starch', 'flour', 'cheese', 'brown sugar', 'shrimp', 'eel', 'butter', ]; if (ingredients.includes('flour')) { console.log('yuk'); } // ingredients.reverse() // ingredients.reverse() let food = ingredients.slice(0, 3); let yummy = ingredients.slice(4); let sugar = ingredients.slice(-3); ingredients.splice(1, 0, 'berries'); ingredients.splice(1, 4, 'chocolate'); //sort will alphabetize strings, but not numbers. Sort actually converts the characters to UTF-16 values and organizes those, so you can't use it with numbers unless you pass in a function. let people = ['Ryan', 'Sarah', 'Olivia']; people.sort(); let streetAddress = [4250, 4300, 70, 1]; streetAddress.sort(); //storing a value as a primitive type will store that literal thing you typed. storing a value as an array or object just stores a reference point in memory. //that's why an array or object stored as a const can still be changed- it's not saved literally like a primitive type. What is stored in memory is the array's container- it's contents can be changed. const animalPairs = [ ['hamster', 'guinnea pig'], ['cat', 'dog'], ['fish', 'snake'] ]; //nested arrays often used in games const tictactoeBoard = [ ['O', null, 'X'], [null, 'X', 'O'], ['X', 'O', null] ]; //objects //inside the object literal are key:value pairs. the key is stored as strings, even if you use a number for a key. //comma is placed at the end of a property declaration const fitbitData = { totalSteps : 308727, totalMiles : 211.7, avgCalorieBurn : 5755, workoutsThisWeek : '5 of 7', avgGoodSleep : '2:13', 45: "that's the number", //can't get it with . notation '76 trombones' : 'great song' } //how to get data out of a numeral property key fitbitData[45]; //this works because the brackets convert the numeral to a string and matches it with the string key '45' fitbitData['76 trombones']; //have to have quotes because of the space-- really should always use quotes with bracket notation in accessing values. const palette = { red : '#eb4d4b', yellow : '#f9ca24', blue : '#30336b' } let mysteryColor = 'yellow'; palette[mysteryColor]; //gives value #f9ca24 because it sees that mysteryColor is 'yellow' and plugs that into palette as a key //updating object data const userReviews = {}; userReviews['queenBee49'] = 4.0; userReviews.mrSmith78 = 3.5; userReviews.mrSmith78++; userReviews.queenBee49+=2; userReviews.colt = 6; userReviews['colt'] += 4; //nesting objects and arrays const tictacGame = { player1 : { username: 'Ryan', mark : 'X' }, player2 : { username : 'Sarah', mark : 'O' }, board : [ ['O', null, 'X'], [null, 'X', 'O'], ['X', 'O', null] ] }; //comparing objects and arrays let numbs = [1,2,3]; let numbs2 = [1,2,3]; // numbs === numbs2 is false because they have 2 different locations in memory and that's what's being compared. let moreNums = numbs; // now numbs === moreNums is true because they live in the same memory spot. const user = { username : 'CherryGarcia8', email : '<EMAIL>', notifications : [] }; //below will not work because you're trying to comparing two arrays. Would either have to convert the array first, or ask in a different way. // if(user.notifications === []) { // console.log('no new notifications'); // } if(user.notifications.length === 0) { //asking if the length of the array is zero works console.log('no new notifications'); } if(!user.notifications.length) { //or asking if there is no user.notifications.length works. console.log('no new notifications'); } <file_sep>/app-scope.js //BLOCK SCOPE //------------------------------------- let bird = '<NAME>'; //((((((((((((((((((())))))))))))))))))) function birdWatch() { let bird = 'golden pheasant'; bird; //golden pheasant } //((((((((((((((((((())))))))))))))))))) bird; //mandarin duck //------------------------------------- //bird is scoped to (inside of) birdWatch function, but if bird is called outside of birdWatch function, it only sees mandarin duck. //it will see whatever is closest inside the function. if they're nested functions, the innermost function wins //let and const ARE block scoped. So if you declare a variable within a function with let and var, it's only accessible inside that function or that block //var is not scoped. So if you declare a variable with var, even inside a block or function, it can be accessed anywhere and it can be changed anywhere. //do not declare loop iteration variables with var //LEXICAL SCOPE //nested functions are scoped to their parent functions function outer() { let movie = 'Amadeus'; function inner() { let x = 10; console.log(movie.toUpperCase()) } inner(); console.log(x); //will not work because x is block scoped to inner function } function outer() { let movie = 'Amadeus'; function inner() { let movie = 'The Shining'; console.log(movie.toUpperCase()) } inner(); //will print THE SHINING because it will use whatever variable is in the innermost function/block } function outer() { let movie = 'Amadeus'; function inner() { let movie = 'The Shining'; function extrainner() { console.log(movie.toUpperCase()) } } inner(); //will print THE SHINING because it will use whatever variable is in the innermost function/block } function outer() { let movie = 'Amadeus'; function inner() { function extrainner() { console.log(movie.toUpperCase()) } } inner(); //will print AMADEUS because it will keep looking up through function/block till it gets to a parent that has that variable } //HOISTING //var is hoisted, but not the value. //let and const are not hoisted //function declarations are hoisted //function expressions are not hoisted var animal = "tapir"; console.log(animal); //tapir console.log(animal); var animal = "tapir"; //undefined //computer sees animal, but not what's saved in animal. so it hoisted the variable declaration first, but waits to store it. let shrimp = "<NAME>"; console.log(shrimp); //<NAME> console.log(shrimp); //<NAME> let shrimp = "<NAME>"; //uncaught reference error, cannot access 'shrimp 'before initialization. so it isn't hoisted at all. howl(); function howl() { console.log("awoooo"); //works because function declarations are hoisted. this function isn't stored in a variable. The interpreter runs these lines first. } hoot(); var hoot = function () { console.log("hoo hoo"); //uncaught type error, hoot is not a function. it sees the variable hoot, but not the function attached. this is a function expression. } hoot(); let hoot = function () { console.log("hoo hoo"); //uncaught referrence error, cannot access hoot before initialization. none of it is hoisted. this is a function expression. } <file_sep>/app-2.js // for(initial initialExpression; condition; incrementExpression) { // do something // } for (let i = 1; i <= 10; i++) { console.log('hello:', i); } // for (let i = 3; i <= 10; i++) { // console.log('hello:', i); // } // for (let i = 5; i <= 10; i+2) { // console.log('hello:', i); // } for (let j = 1; j <= 20; j++) { console.log(`${j}x${j} = ${j*j}`); } //start at 50, subtract 10 each time, until you get to 0 for (let k = 50; k >=0; k -= 10) { console.log(k); //50 40 30 20 10 0 } const examScores = [98, 77, 84, 91, 34, 66]; //print all exam scores for(let i = 0; i <= examScores.length-1; i++) { console.log (i, examScores[i]); } const myStudents = [ { firstName : 'Zeus', grade : 86 }, { firstName : 'Artemis', grade: 97 }, { firstName : 'Hera', grade : 72 } ]; let total = 0; //have to have this outside the loop or it will recalculate total to 0 every time the loop runs for (let i = 0; i < myStudents.length; i++) { console.log(`${myStudents[i]}`); //just prints the fact that there are 3 objects let student = myStudents[i]; //assigns student to each unique object so we can access data console.log(student); //prints each unique object info console.log(`${student.firstName} scored ${student.grade}`); total += student.grade; //adds grades together } console.log(total/myStudents.length); //takes the class avg const word = 'stressed'; for (let i = word.length-1; i >= 0; i--) { console.log(word[i]); } //nested for loop for (let i = 1; i <= 10; i ++) { console.log('OUTER LOOP:', i); for (let j = 10; j >=0; j --) { console.log(' inner loop:', j); } } //need two loops nested to access two arrays nested const gameBoard = [ [4, 32, 8, 4], [64, 8, 32, 2], [8, 32, 16, 4], [2, 8, 4, 2] ]; for (let i = 0; i < gameBoard.length; i ++) { console.log(gameBoard[i]); let row = gameBoard[i]; for(let j = 0; j < row.length; j ++) { console.log(row[j]); } } console.log('next are while loops'); //while loops //while(some condition) //in the loop, update or attempt to make that condition false //this for loop is the same as the while loop below for (let i = 0; i <= 5; i++) { console.log(i); } //this while loop is the same as the for loop above let j = 0; while (j <= 5) { console.log(j); j++; } //NOTE: it is best practice not to declare loop variables outside the loop, but you have to when using while loops const target = Math.floor(Math.random() * 10); let guess = Math.floor(Math.random() * 10); // use let because the guess will change while(guess !== target) { console.log(`Target: ${target} Guess: ${guess}`); //prints all except the correct match guess = Math.floor(Math.random() * 10); } console.log(`Target: ${target} Guess: ${guess}`);//prints the correct match console.log("it's a match!"); //another way to write the same thing using break // const target = Math.floor(Math.random() * 10); // let guess = Math.floor(Math.random() * 10); // use let because the guess will change // while(true) { //this will be an infinite loop without the break below // if(target === guess) break; //break stops the loop // console.log(`Target: ${target} Guess: ${guess}`); //prints all except the correct match // guess = Math.floor(Math.random() * 10); // } // console.log(`Target: ${target} Guess: ${guess}`);//prints the correct match // console.log("it's a match!"); //for of loop (new) to iterate each char in strings, each element in arrays //so much easier and cleaner! let's you declare your iterable and name it let subreddits = ['soccer', 'popheads', 'cringe', 'books']; for (let sub of subreddits) { console.log(sub); } for (let char of 'cockadoodledoo') { console.log(char.toUpperCase()); } //nested for loop versus nested for of loop const magicSquare = [ [2, 7, 6], [9, 5, 1], [4, 3, 8] ]; for (let i = 0; i <magicSquare.length; i++) { let row = magicSquare[i]; let sum = 0;//reset each sum to 0 so it doesn't add all the numbers in the whole outer array together for (let j = 0; j < row.length; j++) { sum += row[j]; } console.log(`${row} summed to ${sum}`); } for (let row of magicSquare) { let sum = 0; for (let num of row) { sum += num; } console.log(`${row} still summed to ${sum}`); } //when you need the index of the array, just use traditional for loop const words1 = ['mail', 'milk', 'bath']; const words2 = ['box', 'jug', 'tub']; for (let i = 0; i < words1.length; i++) { console.log(`${words1[i]}${words2[i]}`);//how does this know to iterate through words2 without declaring it in the for loop? } //looping over objects const movieReviews = { Arrival : 9.5, Alien : 9, Amelie : 8, 'In Bruges' : 9, Amadeus : 10, 'Kill Bill' : 8, 'Little Miss Sunshine' : 8.5, Coraline : 7.5 }; // for(let x of movieReviews) { //this does not work because objects are not iterable // console.log(x); // } for (let movie of Object.keys(movieReviews)) { console.log(movie, movieReviews[movie]); } const ratings = Object.values(movieReviews); let totals = 0; for(let r of ratings) { totals +=r; } totalAvg = totals /= ratings.length; console.log(totalAvg); //you could use a regular for loop and grab the index from Object.keys and Object.values //BUT there's a better way! Just use for in and you don't have to use Object.keys or .values at all //for in loops to be used in objects, not recommended for arrays const jeopardyWinnings = { regularPlay : 2522700, watsonChallenge : 300000, tournamentOfChampions : 500000, battleOfTheDecades : 100000 }; for (let prop in jeopardyWinnings) { console.log(prop);//prints keys console.log(jeopardyWinnings[prop]);//prints values } let totalWin=0; for (let prop in jeopardyWinnings) { totalWin += jeopardyWinnings[prop]; } console.log(totalWin);
965cb00b17933acbb5a0dbda72e677b1169126c5
[ "JavaScript" ]
6
JavaScript
SarahRDH/jspractice
535a5f22b8fe6566bacd6248f13055f6499848db
d1709d6e2e840480c93fd002ffd770e100637ab6
refs/heads/master
<file_sep>package exercises.diamond; import exercises.util.Utils; /** * Created by wbzhao on 15-4-10. * ============================= * Isosceles Triangle * Given a number n, print a centered triangle. Example for n=3: * * * *** * ***** * ============================= */ public class IsoscelesTriangle { public static void main(String[] args) { int amount = 0; String output = ""; amount = Utils.getInputInt(); for (int line = 0; line < amount; line++) { output += Utils.composeDiamondLine(line, amount); } System.out.print(output); } } <file_sep>package exercises.util; import java.util.Scanner; /** * Created by wbzhao on 15-4-10. */ public class Utils { public static int getInputInt() { System.out.print("Input a integer number: "); return Integer.parseInt(new Scanner(System.in).next()); } public static String composeDiamondLine(int line, int amount) { int column; String result = ""; for (column = 0; column < amount - line - 1; column++) { result += " "; } int lineLength = column + line * 2; for (; column <= lineLength; column++) { result += "*"; } result += "\r\n"; return result; } } <file_sep>package exercises.diamond; import exercises.util.Utils; /** * Created by wbzhao on 15-4-10. * ============================= * Diamond * * Given a number n, print a centered diamond. Example for n=3: * * * *** * ***** * *** * * * ============================= */ public class Diamond { public static void main(String[] args) { int amount = Utils.getInputInt(); String output = ""; int line; for (line = 0; line < amount; line++) { output += Utils.composeDiamondLine(line, amount); } for (; --line > 0;) { output += Utils.composeDiamondLine(line - 1, amount); } System.out.print(output); } } <file_sep>package exercises.triangle; import exercises.util.Utils; /** * Created by wbzhao on 15-4-10. * ============================= * Draw a vertical line * Given a number n, print n lines, each with one asterisks * Example when n=3: * * * * * * * ============================= */ public class DrawAVerticalLine { public static void main(String[] args) { int amount = 0; String output = ""; amount = Utils.getInputInt(); for (int i = 0; i < amount; i++) { output += "*\r\n"; } System.out.print(output); } } <file_sep>package exercises.triangle; /** * Created by wbzhao on 15-4-10. * ============================= * Easiest exercise ever * * Print one asterisk to the console. * Example: * * * ============================= */ public class EasiestExerciseEver { public static void main(String[] args) { System.out.println("*"); } } <file_sep>package exercises.fizzbuzz; /** * Created by wbzhao on 15-4-11. * ============================= * FizzBuzz Exercise * * FizzBuzz is a simple number game where you count, but say "Fizz" and/or "Buzz" instead of numbers adhering to certain rules. * * Create a FizzBuzz() method that prints out the numbers 1 through 100. * Instead of numbers divisible by three print "Fizz". * Instead of numbers divisible by five print "Buzz". * Instead of numbers divisible by three and five print "FizzBuzz". * ============================= */ public class FizzBuzz { private static void fizzBuzz() { for (int i = 1; i <= 100; i++) { System.out.println(fizzBuzzANumber(i)); } } private static String fizzBuzzANumber(int i) { String result = ""; if (i % 3 == 0) { result += "Fizz"; } if (i % 5 == 0) { result += "Buzz"; } if (result.equals("")) { result += i; } return result; } public static void main(String[] args) { fizzBuzz(); } }
bdde45ad7275f5182b5fda53bb505d9cc02e9d91
[ "Java" ]
6
Java
wzhao0928/IntroProgrammingExercises
6dad5896e6195de2faa880b77bd153a8fa3c621c
f5e4283b45aa5437d91abd89b6caeae05e0f333e
refs/heads/master
<repo_name>FrozenSid/ASCII-animation<file_sep>/ascii.js /*--ALEX Homework 6 ASCIIanimation*/ var TextFile; var CurrentFrame; var FrameCount; var FrameDelay; // Function to start the animation function StartAnimation(){ TextFile = document.getElementById("mytextarea").value; //save the contents of the textarea CurrentFrame = TextFile.split("=====\n"); //separator for the frames in the textarea if(CurrentFrame.length <= 1) { alert("No ASCII Animation selected! Please, select an ASCIImation from the ''Animation'' dropdown menu!"); return; } SetEnable(true); //this will enable the stop button FrameCount = 0; // set counter to 0 so that every time it is initialized to zero when we select start button. GetFrame(); // method to get the next frame FrameDelay = window.setInterval(GetFrame, 250); // set the frame time interval before it loops back } // Function to get the next frame. function GetFrame() { document.getElementById("mytextarea").value = CurrentFrame[FrameCount]; FrameCount = (FrameCount + 1) % CurrentFrame.length; //get the frames in the textarea by counting the first one and the remainder of the lenght of current frame } // Function to stop the animation function StopAnimation() { clearTimeout(FrameDelay); FrameDelay = null; document.getElementById("mytextarea").value = TextFile; SetEnable(false); // this will disable the stop button } // Function to disable and enable the controls function SetEnable(Value) { document.getElementById("mytextarea").readOnly = Value; document.getElementById("Animation").disabled = Value; document.getElementById("Stop").disabled =! Value; //if true --> Enable stop; if false --> Disable stop document.getElementById("Start").disabled = Value; //if true --> Disable Start; if false --> Enable start document.getElementById("turbo").disabled =! Value; // if true --> Enable turbo document.getElementById("turbo").checked =! Value; //if checked ---> Enable turbo } // Function to Select the animation and get the text into the text area function SelectAnimation() { var whichOne = document.getElementById("Animation").value; document.getElementById("mytextarea").value = ANIMATIONS[whichOne]; //get the animations from the animations.js file and apply them in the textarea } // Function to Select the size of the text function SelectSize() { var SizeChosen = document.getElementById("Size").value; (document.getElementById("mytextarea")).style.fontSize = SizeChosen; //get the sizes from the HTML document with id="Size" and apply them to the textarea } // Function to increase the speed of changing of frames (set Turbo) function SelectTurbo(){ var Delay = 50; if (document.getElementById("turbo").checked) //if turbo is checked { Delay = document.getElementById("turbo").value; //delay is 50ms } else { Delay = 250; } if(FrameDelay !== null) //if frame delay not empty { window.clearInterval(FrameDelay); //clear the interval FrameDelay = window.setInterval(GetFrame, Delay); //set interval before it loops back } }<file_sep>/README.md # ASCII-animation Funny animations of symbols combined that form people performing activities like exercising, biking, diving, juggling. In order to see the website, do the following: 1) Download WAMP (for Windows machines), LAMP (for Linux machines), MAMP (for Macintosh machines) 2) Save all the files from here (my github repository ASCII-animation) in one folder and name it anything you want (for example, "ASCII") 3) Put that "ASCII" folder in the "htdocs" or "www" directory when you open your WAMP, LAMP, MAMP folder 4) Run WAMP/LAMP/MAMP (if the icon is green everything works fine) 5) Open a web browser and type "localhost:8888/ASCII/ascii.html" and you will see the website 6) 8888 is the port number but for your machine it might be different - it could be 80 or 8080 7) Enjoy my website!
70f9af3d94eca1367a62bb983885fd34d154bbac
[ "JavaScript", "Markdown" ]
2
JavaScript
FrozenSid/ASCII-animation
199283440c0b592a7a17c05e19c771083db927ed
6d922ccb34f261e92c5f6ac65132c50a1be3a384
refs/heads/master
<file_sep>package exercises; import java.util.*; public class Alternating { public static LinkedList<String> mix(List<String> list1, List<String> list2){ LinkedList<String> retList = new LinkedList<String>(); ListIterator<String> it1 = list1.listIterator(); ListIterator<String> it2 = list2.listIterator(); while(it1.hasNext()){ retList.add(it1.next()); retList.add(it2.next()); } return retList; } public static void main(String[] args){ ArrayList<String> list1 = new ArrayList<String>(); ArrayList<String> list2 = new ArrayList<String>(); list1.add("y"); list1.add("i"); list1.add("k"); list2.add("o"); list2.add("n"); list2.add("s"); System.out.println(mix(list1, list2)); } } <file_sep>package exercises; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class Appending { public static <E> void append(List<E> list1, List<E> list2){ E[] arr = (E[])list2.toArray(); int len = arr.length; for(int i = 0; i < len; i++){ list1.add(list2.get(i)); } } public static <E> void append4a(List<E> list1, List<E> list2){ ListIterator it = list2.listIterator(); while(it.hasNext()){ list1.add((E)it.next()); } } public static <E> void append4b(List<E> list1, List<E> list2){ for(E x : list2){ list1.add(x); } } public static void main(String[] args){ List<Integer> l1 = new ArrayList<Integer>(); l1.add(-1); l1.add(0); List<Integer> l2 = new ArrayList<Integer>(); l2.add(1); l2.add(2); append4b(l1, l2); for(int x : l1){ System.out.println(x); } } } <file_sep>package exercises; public class A { //Z }
bfed8472d0a7f4179fef7fd7d0295da9c06fd81e
[ "Java" ]
3
Java
EatLentils/Test
6d1e0378444f448da8d3b9925f3173c7fff8b4e4
82337fec38460cd5c4907b3ab3c50462ea6c865a
refs/heads/master
<file_sep>#!/bin/bash op=$1 step=7 if [[ ${op} != "+" ]] && [[ ${op} != "-" ]]; then echo "Usage: $0 [+,-]." exit 1 fi current_brightness=$(cat /sys/class/backlight/intel_backlight/actual_brightness) max_brightness=$(cat /sys/class/backlight/intel_backlight/max_brightness) if [[ -z ${max_brightness} ]]; then echo "Could not detect maximum brightness." exit 1 fi if [[ -z ${current_brightness} ]]; then echo "Could not detect current brightness." exit 1 fi one_percent=$(echo "${max_brightness}/100" | bc) new_brightness=$(echo "${current_brightness}${op}${step}*${one_percent}" | bc) new_brightness=$(echo "define max(a, b) { if (a > b) { return (a); } return (b); } max(${new_brightness}, 1)" | bc) new_brightness=$(echo "define min(a, b) { if (a < b) { return (a); } return (b); } min(${new_brightness}, ${max_brightness})" | bc) echo "One percent means ${one_percent}." echo "Old brightness: ${current_brightness}." echo "New brightness: ${new_brightness}." echo ${new_brightness} > /sys/class/backlight/intel_backlight/brightness
0a953891b08c29a6868faf5bb14ada09a49dec6f
[ "Shell" ]
1
Shell
sasajib/dotfiles
f4be57d01f989c8d784fadcea773eb35033d2b44
590008af4e3518c13cec74f5feecc8c7e6f0cfdf
refs/heads/main
<repo_name>Zarzarius/Rick-and-Morty-API<file_sep>/main.js fetch("https://rickandmortyapi.com/api/character") .then((data) => data.json()) .then((data) => { console.log(data); data.results.forEach((character) => { const characterBox = document.createElement("div"); characterBox.setAttribute("class", "character-box"); const name = document.createElement("h2"); name.textContent = `${character.name}`; const species = document.createElement("h3"); species.textContent = `Specie: ${character.species}`; const status = document.createElement("h4"); status.textContent = `Status: ${character.status}`; const image = document.createElement("img"); image.src = character.image; chars.appendChild(characterBox); characterBox.appendChild(name); characterBox.appendChild(species); characterBox.appendChild(image); characterBox.appendChild(status); }); }) .catch((err) => { console.error(err); }); const chars = document.getElementById("chars"); <file_sep>/README.md # -Rick-and-Morty- Small class project fetching data from the Rick and Morty API
7485009d694628b82cf31724acfe59892656201d
[ "JavaScript", "Markdown" ]
2
JavaScript
Zarzarius/Rick-and-Morty-API
3316f44788a8caa767c14725d976aea15af05fa0
a9b52c8c7b972daac9c03d2ce8fdafa3604dc51e
refs/heads/main
<repo_name>Warkneo/erer<file_sep>/erdemcakiroglu.js const Discord = require("discord.js"); const client = new Discord.Client(); const ayarlar = require("./ayarlar.json"); const chalk = require("chalk"); const fs = require("fs"); const moment = require("moment"); const Jimp = require("jimp"); const db = require("quick.db"); const matthe = require('discord-buttons') matthe(client) var prefix = ayarlar.prefix; client.on("ready", () => { console.log(`[ Erdem 💙 Button ] bot başarıyla aktif edildi: ${client.user.tag}!`); }); const log = message => { console.log(`[${moment().format("YYYY-MM-DD HH:mm:ss")}] ${message}`); }; require("./util/eventLoader")(client); client.commands = new Discord.Collection(); client.aliases = new Discord.Collection(); fs.readdir("./komutlar/", (err, files) => { if (err) console.error(err); log(`[ Erdem 💙 Button ] ${files.length} adet komut yüklenecek.`); files.forEach(f => { let props = require(`./komutlar/${f}`); log(`[ Erdem 💙 Button ] yüklenen komut: ${props.help.name}`); client.commands.set(props.help.name, props); props.conf.aliases.forEach(alias => { client.aliases.set(alias, props.help.name); }); }); }); client.reload = command => { return new Promise((resolve, reject) => { try { delete require.cache[require.resolve(`./komutlar/${command}`)]; let cmd = require(`./komutlar/${command}`); client.commands.delete(command); client.aliases.forEach((cmd, alias) => { if (cmd === command) client.aliases.delete(alias); }); client.commands.set(command, cmd); cmd.conf.aliases.forEach(alias => { client.aliases.set(alias, cmd.help.name); }); resolve(); } catch (e) { reject(e); } }); }; client.load = command => { return new Promise((resolve, reject) => { try { let cmd = require(`./komutlar/${command}`); client.commands.set(command, cmd); cmd.conf.aliases.forEach(alias => { client.aliases.set(alias, cmd.help.name); }); resolve(); } catch (e) { reject(e); } }); }; client.unload = command => { return new Promise((resolve, reject) => { try { delete require.cache[require.resolve(`./komutlar/${command}`)]; let cmd = require(`./komutlar/${command}`); client.commands.delete(command); client.aliases.forEach((cmd, alias) => { if (cmd === command) client.aliases.delete(alias); }); resolve(); } catch (e) { reject(e); } }); }; client.login(ayarlar.token); client.elevation = message => { if (!message.guild) { return; } let permlvl = 0; if (message.member.hasPermission("BAN_MEMBERS")) permlvl = 2; if (message.member.hasPermission("ADMINISTRATOR")) permlvl = 3; if (ayarlar.sahip.includes(message.author.id)) permlvl = 4; return permlvl; }; var regToken = /[\w\d]{24}\.[\w\d]{6}\.[\w\d-_]{27}/g; client.on("warn", e => { console.log(chalk.bgYellow(e.replace(regToken, "that was redacted"))); }); client.on("error", e => { console.log(chalk.bgRed(e.replace(regToken, "that was redacted"))); }); client.on("message", (message) => { if (message.content !== ".buton" || message.author.bot) return; let EtkinlikKatılımcısı = new matthe.MessageButton() .setStyle('green') .setLabel('Etkinlik Katılımcısı') .setID('EtkinlikKatılımcısı'); let DuyuruKatılımcısı = new matthe.MessageButton() .setStyle('green') .setLabel('Duyuru Rolu') .setID('DuyuruKatılımcısı'); let ÇekilişKatılımcısı = new matthe.MessageButton() .setStyle('green') .setLabel('Çekiliş Katılımcısı') .setID('ÇekilişKatılımcısı'); let Partnerkatılımcısı = new matthe.MessageButton() .setStyle('green') .setLabel('Partner Katılımcısı') .setID('Partnerkatılımcısı'); let Youtubekatılımcısı = new matthe.MessageButton() .setStyle('green') .setLabel('YouTube Katılımcısı') .setID('Youtubekatılımcısı'); message.channel.send(` **Aşağıdaki Menüden Kendinize Rol Seçebilirsiniz. \`>\` <@&898447333052805131> Rolü Almak İçin Etkinlik Katılımcısı! Butonuna. \`>\` <@&898447341378498611> Rolü Almak İçin Çekiliş Katılımcısı! Butonuna. \`>\` <@&898447340657057822> Rolü Almak İçin Duyuru Katılımcısı! Butonuna. \`>\` <@&898456174201036822> Rolü Almak İçin Duyuru Katılımcısı! Butonuna. \`>\` <@&898464023010496554> Rolü Almak İçin Duyuru Katılımcısı! Butonuna. **`, { buttons: [ EtkinlikKatılımcısı, ÇekilişKatılımcısı, DuyuruKatılımcısı, Partnerkatılımcısı, Youtubekatılımcısı] }); }); client.on('clickButton', async (button) => { if (button.id === 'EtkinlikKatılımcısı') { if (button.clicker.member.roles.cache.get((ayarlar.EtkinlikKatılımcısı))) { await button.clicker.member.roles.remove((ayarlar.EtkinlikKatılımcısı)) await button.reply.think(true); await button.reply.edit("Etkinlik Katılımcısı rolü başarıyla üzerinizden alındı!") } else { await button.clicker.member.roles.add(((ayarlar.EtkinlikKatılımcısı))) await button.reply.think(true); await button.reply.edit("Etkinlik Katılımcısı rolünü başarıyla aldınız!") } } if (button.id === 'DuyuruKatılımcısı') { if (button.clicker.member.roles.cache.get((ayarlar.DuyuruKatılımcısı))) { await button.clicker.member.roles.remove((ayarlar.DuyuruKatılımcısı)) await button.reply.think(true); await button.reply.edit("Duyuru Katılımcısı rolü başarıyla üzerinizden alındı!") } else { await button.clicker.member.roles.add(((ayarlar.DuyuruKatılımcısı))) await button.reply.think(true); await button.reply.edit("Duyuru Katılımcısı rolünü başarıyla aldınız!") } } if (button.id === 'ÇekilişKatılımcısı') { if (button.clicker.member.roles.cache.get((ayarlar.ÇekilişKatılımcısı))) { await button.clicker.member.roles.remove((ayarlar.ÇekilişKatılımcısı)) await button.reply.think(true); await button.reply.edit(`Çekiliş Katılımcısı rolü başarıyla üzerinizden alındı!`) } else { await button.clicker.member.roles.add((ayarlar.ÇekilişKatılımcısı)) await button.reply.think(true); await button.reply.edit(`Çekiliş Katılımcısı rolünü başarıyla aldınız!`) } } if (button.id === 'Partnerkatılımcısı') { if (button.clicker.member.roles.cache.get((ayarlar.Partnerkatılımcısı))) { await button.clicker.member.roles.remove((ayarlar.Partnerkatılımcısı)) await button.reply.think(true); await button.reply.edit("Partner Katılımcısı rolü başarıyla üzerinizden alındı!") } else { await button.clicker.member.roles.add(((ayarlar.Partnerkatılımcısı))) await button.reply.think(true); await button.reply.edit("Partner Katılımcısı rolünü başarıyla aldınız!") } } if (button.id === 'Youtubekatılımcısı') { if (button.clicker.member.roles.cache.get((ayarlar.Youtubekatılımcısı))) { await button.clicker.member.roles.remove((ayarlar.Youtubekatılımcısı)) await button.reply.think(true); await button.reply.edit("YouTube Katılımcısı rolü başarıyla üzerinizden alındı!") } else { await button.clicker.member.roles.add(((ayarlar.Youtubekatılımcısı))) await button.reply.think(true); await button.reply.edit("YouTube Katılımcısı rolünü başarıyla aldınız!") } } });
3597fdf2d0c172be091372daed1b8a5777acbffe
[ "JavaScript" ]
1
JavaScript
Warkneo/erer
3fb6f76807380f39888bfe3ddd18770873c3a882
725eb3682ddcc1880568c41394e40d52d6c7f5d4
refs/heads/master
<repo_name>alexeluro/CardVerifier<file_sep>/app/src/main/java/com/inspiredcoda/cardverifier/data/repository/BaseRepository.kt package com.inspiredcoda.cardverifier.data.repository import com.inspiredcoda.cardverifier.utils.ApiException import retrofit2.Response abstract class BaseRepository { suspend fun<T> apiRequest(work: suspend (() -> Response<T?>)): T?{ val request = work.invoke() if (request.isSuccessful){ return request.body() }else{ throw ApiException("Error fetching card details!") } } }<file_sep>/app/src/test/java/com/inspiredcoda/cardverifier/ui/MainActivityTest.kt package com.inspiredcoda.cardverifier.ui import com.google.common.truth.Truth.assertThat import junit.framework.Assert.assertEquals import kotlinx.android.synthetic.main.activity_main.* import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class MainActivityTest { @Test fun properlySeparate_5_Digit_Serials() { val result = separateCardNumber("45713") assertEquals("4571 3", result) } @Test fun undoProperlySeparate_5_Digit_Serials() { val result = undoCardNumberSeparation("4571 3") assertEquals("45713", result) } @Test fun properlySeparate_6_Digit_Serials() { val result = separateCardNumber("457134") assertEquals("4571 34", result) } @Test fun undoProperlySeparate_6_Digit_Serials() { val result = undoCardNumberSeparation("4571 34") assertEquals("457134", result) } @Test fun properlySeparate_9_Digit_Serials() { val result = separateCardNumber("457134789") assertEquals("4571 3478 9", result) } @Test fun undoProperlySeparate_9_Digit_Serials() { val result = undoCardNumberSeparation("4571 3478 9") assertEquals("457134789", result) } fun separateCardNumber(serials: String): String { var newSerial = StringBuilder() for (x in serials.indices) { if (x % 4 == 0 && x != 0) { newSerial.append(" ${serials[x]}") } else { newSerial.append(serials[x]) } } return newSerial.toString() } fun undoCardNumberSeparation(spacedSerials: String): String{ val result = StringBuilder() for (x in spacedSerials.indices){ if (spacedSerials[x].toString() != " "){ result.append(spacedSerials[x]) } } return result.toString() } }<file_sep>/app/src/main/java/com/inspiredcoda/cardverifier/ui/ResultStateCallback.kt package com.inspiredcoda.cardverifier.ui interface ResultStateCallback { fun onLoading() fun onSuccess(message: String?) fun onFailure(message: String?) }<file_sep>/app/src/main/java/com/inspiredcoda/cardverifier/data/Api.kt package com.inspiredcoda.cardverifier.data import com.inspiredcoda.cardverifier.data.response.CardDetailsResponse import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Path interface Api { @GET("{serials}") suspend fun getCardDetails(@Path("serials") serials: String): Response<CardDetailsResponse?> }<file_sep>/app/src/main/java/com/inspiredcoda/cardverifier/ui/MainActivity.kt package com.inspiredcoda.cardverifier.ui import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.text.TextWatcher import androidx.activity.viewModels import com.inspiredcoda.cardverifier.R import com.inspiredcoda.cardverifier.data.response.CardDetailsResponse import com.inspiredcoda.cardverifier.utils.hide import com.inspiredcoda.cardverifier.utils.show import com.inspiredcoda.cardverifier.utils.toast import dagger.hilt.android.AndroidEntryPoint import kotlinx.android.synthetic.main.activity_main.* @AndroidEntryPoint class MainActivity : AppCompatActivity(), ResultStateCallback { private val mainViewModel: MainViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) observer() main_serial_input.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun afterTextChanged(value: Editable?) { if ((!value.isNullOrEmpty()) && value.toString().length > 3){ mainViewModel.setCardDetails(value.toString(), this@MainActivity) } } }) } private fun setValues(cardResponse: CardDetailsResponse) { main_bank_text.text = cardResponse.bank?.name ?: "???" main_card_number_length_text.text = cardResponse.number?.length.toString() main_card_scheme_text.text = cardResponse.scheme ?: "???" main_card_type.text = cardResponse.type ?: "???" main_country.text = cardResponse.country?.name ?: "???" main_prepaid_text.text = if (cardResponse.prepaid) "Yes" else "No" } private fun observer() { mainViewModel.cardDetailsLive.observe(this) { if (it != null) { setValues(it) } } } override fun onLoading() { main_progress_bar.show() } override fun onSuccess(message: String?) { main_progress_bar.hide() if (!message.isNullOrEmpty()) toast(message) } override fun onFailure(message: String?) { main_progress_bar.hide() toast(message ?: "") } }<file_sep>/app/src/androidTest/java/com/inspiredcoda/cardverifier/ui/MainActivityIntegrationTest.kt package com.inspiredcoda.cardverifier.ui import android.text.Editable import android.text.TextWatcher import android.widget.EditText import androidx.test.core.app.ActivityScenario import androidx.test.espresso.Espresso import androidx.test.espresso.action.ViewActions.* import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.filters.LargeTest import androidx.test.runner.AndroidJUnit4 import com.inspiredcoda.cardverifier.R import org.junit.After import org.junit.BeforeClass import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest class MainActivityIntegrationTest { @get:Rule var activityScenarioRule: ActivityScenarioRule<MainActivity>? = ActivityScenarioRule(MainActivity::class.java) @Test fun testCardVerificationProcess() { // Type in the sample card serial number Espresso.onView(withId(R.id.main_serial_input)) .perform(typeText("457133496"), closeSoftKeyboard()) .check(ViewAssertions.matches(withText("4571 3349 6"))) } @After fun tearDown(){ activityScenarioRule = null } }<file_sep>/app/src/main/java/com/inspiredcoda/cardverifier/di/AppModule.kt package com.inspiredcoda.cardverifier.di import android.app.Application import android.content.Context import com.facebook.stetho.okhttp3.StethoInterceptor import com.inspiredcoda.cardverifier.data.Api import com.inspiredcoda.cardverifier.data.CustomInterceptor import com.inspiredcoda.cardverifier.utils.Constant.Remote.BASE_URL import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ApplicationComponent import dagger.hilt.android.qualifiers.ApplicationContext import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module @InstallIn(ApplicationComponent::class) class AppModule { @Singleton @Provides fun getRetrofitInstance(@ApplicationContext context: Context): Retrofit { val client = OkHttpClient.Builder() .callTimeout(1000, TimeUnit.SECONDS) .connectTimeout(1000, TimeUnit.SECONDS) .readTimeout(1000, TimeUnit.SECONDS) .writeTimeout(1000, TimeUnit.SECONDS) .addInterceptor(CustomInterceptor(context)) .addNetworkInterceptor(StethoInterceptor()) .build() return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(CoroutineCallAdapterFactory.invoke()) .client(client) .build() } @Singleton @Provides fun getApiInstance(retrofit: Retrofit) = retrofit.create(Api::class.java) }<file_sep>/app/src/main/java/com/inspiredcoda/cardverifier/data/repository/MainRepository.kt package com.inspiredcoda.cardverifier.data.repository import com.inspiredcoda.cardverifier.data.Api import com.inspiredcoda.cardverifier.data.response.CardDetailsResponse import javax.inject.Inject class MainRepository @Inject constructor( private val api: Api ): BaseRepository() { suspend fun getCardDetails(serials: String): CardDetailsResponse?{ return apiRequest { api.getCardDetails(serials) } } }<file_sep>/app/src/main/java/com/inspiredcoda/cardverifier/utils/Constant.kt package com.inspiredcoda.cardverifier.utils class Constant { object Remote { const val BASE_URL = "https://lookup.binlist.net/" } }<file_sep>/settings.gradle include ':app' rootProject.name = "CardVerifier"<file_sep>/app/src/main/java/com/inspiredcoda/cardverifier/utils/Exceptions.kt package com.inspiredcoda.cardverifier.utils import java.io.IOException class NoInternetException(message: String): IOException(message) class ApiException(message: String): IOException(message)<file_sep>/app/src/main/java/com/inspiredcoda/cardverifier/ui/MainViewModel.kt package com.inspiredcoda.cardverifier.ui import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.inspiredcoda.cardverifier.data.repository.MainRepository import com.inspiredcoda.cardverifier.data.response.CardDetailsResponse import com.inspiredcoda.cardverifier.utils.ApiException import com.inspiredcoda.cardverifier.utils.NoInternetException import kotlinx.coroutines.launch class MainViewModel @ViewModelInject constructor( private val repository: MainRepository ) : ViewModel() { private var _cardDetails = MutableLiveData<CardDetailsResponse>() val cardDetailsLive: LiveData<CardDetailsResponse> get() = _cardDetails fun setCardDetails(serials: String, callback: ResultStateCallback) { viewModelScope.launch { try { callback.onLoading() _cardDetails.postValue(repository.getCardDetails(serials)) callback.onSuccess("checked successfully...") } catch (e: NoInternetException) { callback.onFailure(e.message) } catch (e: ApiException) { callback.onFailure(e.message) } } } }<file_sep>/app/src/main/java/com/inspiredcoda/cardverifier/data/CustomInterceptor.kt package com.inspiredcoda.cardverifier.data import android.content.Context import android.net.ConnectivityManager import android.net.Network import com.inspiredcoda.cardverifier.utils.NoInternetException import okhttp3.Interceptor import okhttp3.Response class CustomInterceptor(private val context: Context): Interceptor{ override fun intercept(chain: Interceptor.Chain): Response { if (!isInternetAvailable()){ throw NoInternetException("Check you Internet Connection and try again") } return chain.proceed(chain.request()) } private fun isInternetAvailable(): Boolean { val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager manager.activeNetworkInfo.let { return it != null && it.isConnectedOrConnecting } } }
dd5aac54516d5811dfd471f2fecb1edc55962a7a
[ "Kotlin", "Gradle" ]
13
Kotlin
alexeluro/CardVerifier
4a414a7072886e66579cf63741c916f59912bda3
de7f9f21cee51699b366df8d34f789b8bec27bc7
refs/heads/master
<repo_name>Gersain-Martinez/p4GMH<file_sep>/settings.gradle include ':app' rootProject.name='p4GMH' <file_sep>/app/src/main/java/com/gmh/itics/tesoem/edu/p4gmh/frmmenu.java package com.gmh.itics.tesoem.edu.p4gmh; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class frmmenu extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_frmmenu); } public void perro(View v){ Intent perro = new Intent(this,perroActivity.class); startActivity(perro); finish(); } public void tiburon(View v){ Intent tiburon = new Intent(this,tiburon2Activity.class); startActivity(tiburon); finish(); } public void perico(View v){ Intent perico = new Intent(this,pericoActivity.class); startActivity(perico); finish(); } public void oso(View v){ Intent oso = new Intent(this,osoActivity.class); startActivity(oso); finish(); } public void lobo(View v) { Intent lobo = new Intent(this, loboActivity.class); startActivity(lobo); finish(); } public void gato(View v) { Intent gato = new Intent(this, gatoActivity.class); startActivity(gato); finish(); } public void ardilla(View v){ Intent ardilla = new Intent(this, ardilla2Activity.class); startActivity(ardilla); finish(); } public void cobra(View v){ Intent cobra = new Intent(this, cobraActivity.class); startActivity(cobra); finish(); } }
7af116c6d887f68de541ca53ef4005f316c8bc7b
[ "Java", "Gradle" ]
2
Gradle
Gersain-Martinez/p4GMH
5d0432fbd86a02a71d618e54603951d7366c27d0
959319d4a91c33b2d987cb14be52e69fe555be03
refs/heads/master
<repo_name>aur-archive/vesta<file_sep>/PKGBUILD # Maintainer: karamaz0v <nihilum at gmail.com> # Contributor: <NAME> <<EMAIL>> pkgname=vesta pkgver=3.2.1 pkgrel=1 pkgdesc="Visualization for Electronic and Structural Analysis" url="http://jp-minerals.org/vesta/en" license=('custom') arch=("i686" "x86_64") depends=('cairo' 'gtk2' 'libpng' 'libpng12' 'mesa' 'java-environment' 'libxtst' 'libgnomeui') options=(!strip) source=('http://www.geocities.jp/kmo_mma/crystal/download/VESTA-i686.tar.bz2') [ "$CARCH" = "x86_64" ] && source=('http://www.geocities.jp/kmo_mma/crystal/download/VESTA-x86_64.tar.bz2') source=("${source[@]}" "${pkgname}.desktop" "vesta-exec") md5sums=('547528eaaf80f0cf6ddf20fb913331f7' 'fdacab295c4872ad4a8105e55eb0c797' '379a199e0e86d5cbbcb25fd99053d7e0') [ "$CARCH" = "x86_64" ] && md5sums=('c259ccf89e96aa67228826007391068d' 'fdacab295c4872ad4a8105e55eb0c797' '379a199e0e86d5cbbcb25fd99053d7e0') package(){ cd "${srcdir}" install -d "$pkgdir/opt/$pkgname" cp -R "$srcdir"/VESTA-$CARCH/* "$pkgdir/opt/$pkgname" # create Launcher install -d "$pkgdir/usr/bin/" install -D -m755 "$srcdir/vesta-exec" "$pkgdir/usr/bin/$pkgname" # Install Desktop File and Icon install -D -m644 "$srcdir/$pkgname.desktop" \ "$pkgdir/usr/share/applications/$pkgname.desktop" install -D -m644 "$pkgdir/opt/vesta/img/logo.png" \ "$pkgdir/usr/share/icons/$pkgname-icon.png" # Install license install -Dm 644 "$pkgdir"/opt/$pkgname/LICENSE "$pkgdir"/usr/share/licenses/$pkgname/license } <file_sep>/vesta-exec #!/bin/sh /opt/vesta/VESTA
316f4a2dc177bec38e26440a10c936d5dffa882c
[ "Shell" ]
2
Shell
aur-archive/vesta
8c6f350bc927c8f6e8110540e8a0db78f76298b3
73de30ee53e0270fc6174812f22449dd69202ab5
refs/heads/main
<repo_name>OrderLightXander/Mutations_pandas<file_sep>/README.md # Mutations_pandas In the year 3020 a new deadly superbug, <NAME>, was discovered in a human habitat on Mars. Superbug is a term for bacterias strains, viruses, or fungi resistant to most of the antibiotics and other medications commonly used in the 31st century. Martia Auris is a bacteria strain conducted only by humans, is highly infectious, gives symptoms very late and the mortality rate after infection exceeds 15%. It's currently estimated that about 5% of the Martian colony can be infected. The martian laboratories collected many samples and performed sequencing on the bacteria. Our task is to write scripts to support researchers by identifying common mutations and analyzing genomes for the existence of specific substrings. The script is written in Python. input_csv - Path to input CSV out_vis - Path to output pdf out_csv - Path to output CSV searched_domain - String to be searched reference_id - ID of the reference genome Upon execution, it should produce 2 files in total. ---out.csv ---plot.pdf <file_sep>/requirements.txt py -m pip install numpy py -m pip install pandas py -m pip install matplotlib py -m pip install itertools py -m pip install click<file_sep>/script.py import csv import re from reportlab.pdfgen.canvas import Canvas import pandas as pd import numpy as np import matplotlib.pyplot as plt import itertools import click iterator = 0 mutation_list = {} def filterByCharacters(df): allowed_characters = set('ACTGN-') for p in df['Genome']: if not set(p).issubset(allowed_characters): df.drop((df[df['Genome'] == p ].index), inplace=True) return df def detectMutation(dna, cdna): mutation_count = 1 mutations = [] for x, y in zip(dna, cdna): if x == y and x != '-' and y != '-': mutation_count += 1 elif x != y and(x != 'N' or y !='N'): #create mutation list for math plot if mutation_list.get(str(x)+str(mutation_count)+str(y)): mutation_list[str(x)+str(mutation_count)+str(y)] += 1 else: mutation_list[str(x)+str(mutation_count)+str(y)] = 1 #end instruction for plot mutations.append([x, mutation_count, y]) return mutations, mutation_list def selectGenomeByID(data, genome_id): genome = data.loc[data['ID'] == genome_id] return genome['Genome'].values[0] def isDomainPresent(domain, data): if not re.findall('[^ACTGN]', domain): search_request = '' iterator = 0 data['isDomainPresent'] = '' for character in domain: search_request += '[' + character + 'N]-*' for genome in data['Genome']: if re.findall(search_request, genome): data.at[iterator, 'isDomainPresent'] = True iterator+=1 else : data.at[iterator, 'isDomainPresent'] = False iterator+=1 else: pass #Add desc. for non valid domain data def buildVisualization(mutation_list, data, out_vis): sorted_mutations = dict(sorted(mutation_list.items(), key=lambda item: item[1], reverse=True)) slised_mutations = dict(itertools.islice(sorted_mutations.items(), 10)) for i in slised_mutations: slised_mutations[i] = slised_mutations[i]/len(data) f = plt.figure() plt.bar(*zip(*slised_mutations.items())) plt.show() f.savefig(out_vis, bbox_inches='tight') @click.command() @click.option('--input_csv', help='path to csv file') #'genomes.csv' @click.option('--out_vis', help='path to output pdf visualization') #'plot.pdf' @click.option('--out_csv', help='path to output csv file') #'out.csv' @click.option('--searched_domain', help='Searched domain') #'ACCCT' @click.option('--reference_id', help='Referenced id of genome') #'M_AURIS_581117' def main(input_csv, out_vis, out_csv, searched_domain, reference_id): iterator = 0 mutation_list = {} try: with open(input_csv, "r") as file: reader = csv.reader(file) df = pd.DataFrame(columns=['ID', 'Genome']) for row in reader: if row[0] != 'id': df = df.append({'ID': row[0], 'Genome' : row[1]}, ignore_index=True) except IOError: print("File not acceseble") df = filterByCharacters(df).sort_values(by=['ID']) ds_sorted = df.reset_index(drop=True) ds_sorted['Mutations'] = '' ds_mutated = ds_sorted for z in ds_sorted['Genome']: if selectGenomeByID(ds_sorted, reference_id) != z: ds_mutated.at[iterator, 'Mutations'] = detectMutation(selectGenomeByID(ds_sorted, reference_id), z)[0] mutation_list.update(detectMutation(selectGenomeByID(ds_sorted, reference_id), z)[1]) #print(detectMutation(selectGenomeByID(ds_sorted, reference_id), z)[1]) iterator+=1 else : ds_mutated.at[iterator, 'Mutations'] = 'Same DNA with referenced' iterator+=1 ds_mutated.to_csv(out_csv) #'out.csv' isDomainPresent(searched_domain,ds_mutated) buildVisualization(mutation_list, ds_mutated, out_vis) #'plot.pdf' if __name__ == '__main__': main()
499945e4c81239fb54110cfc1d0ed59bb3ee74cf
[ "Markdown", "Python", "Text" ]
3
Markdown
OrderLightXander/Mutations_pandas
741d14f86eeca1f5e07450b9b9b525ff0abd1ab2
84f48ab839e0450d3a78cf0198fed330e501cf1f
refs/heads/master
<repo_name>benlavalley/i18next-sprintf-postProcessor<file_sep>/src/index.js import {sprintf, vsprintf} from './sprintf'; export default { name: 'sprintf', type: 'postProcessor', process(value, key, options) { if (!options.sprintf) return value; if (Object.prototype.toString.apply(options.sprintf) === '[object Array]') { return vsprintf(value, options.sprintf); } else if (typeof options.sprintf === 'object') { return sprintf(value, options.sprintf); } return value; }, overloadTranslationOptionHandler(args) { let values = []; for (var i = 1; i < args.length; i++) { values.push(args[i]); } return { postProcess: 'sprintf', sprintf: values }; } };
68aba0720bb3a7d82f2cec92a721784dac8a4eda
[ "JavaScript" ]
1
JavaScript
benlavalley/i18next-sprintf-postProcessor
b85f7df11bbbda4fc596d99ae948aade760e2410
ee3585a6e79b57583025cc679aca3910a117a65d
refs/heads/master
<repo_name>Epicurean306/TIY-Chessboard<file_sep>/README.md # TIY-Chessboard a doubly-indexed array demonstration... <file_sep>/scripts/models.js ( function( window ) { 'use strict'; alert('JavaScript wired?'); var board = [ ['R','N','B','Q','K','B','N','R'], ['P','P','P','P','P','P','P','P'], [' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' '], ['p','p','p','p','p','p','p','p'], ['r','n','b','q','k','b','n','r'] ]; console.log(board.join('\n') + '\n\n'); /* first is new position, second is original position followed by clear first = Y-axis counting down from top 0-8 second = X-axis counting Right from the left 0-8 */ //trying out this function from @MStaehling to see how it works //I think some of the positions may be in the wrong places? Will need to check. function move(board, fromX, fromY, toX, toY){ board[fromX][fromY] = board[toX][toY]; board[toX][toY] = ' '; console.log(board.join('\n')); }; // 1move(initBoard, 6, 3, 4, 3); // 2move(initBoard, 0, 6, 2, 5); // 3move(initBoard, 6, 2, 4, 2); // 4move(initBoard, 1, 4, 2, 4); // 5move(initBoard, 6, 6, 5, 6); // 6move(initBoard, 1, 3, 3, 3); // 7move(initBoard, 7, 5, 6, 6); // 8move(initBoard, 0, 5, 1, 4); // 9move(initBoard, 7, 6, 5, 5); // 10move(initBoard, 0, 4, 0, 6); // 11move(initBoard, 0, 7, 0, 5); // 12move(initBoard, 7, 4, 7, 6); // 13move(initBoard, 7, 7, 7, 5); // 14move(initBoard, 3, 3, 4, 2); // 15move(initBoard, 7, 3, 6, 2); // 16move(initBoard, 1, 0, 2, 0); // 17move(initBoard, 6, 2, 4, 2); // 18move(initBoard, 1, 1, 3, 1); // 19move(initBoard, 4, 2, 6, 2); // 20move(initBoard, 0, 2, 1, 1); // 21move(initBoard, 7, 2, 6, 3); // 22move(initBoard, 1, 1, 4, 4); // 23move(initBoard, 6, 2, 7, 2); // 24move(initBoard, 4, 4, 1, 1); // 25move(initBoard, 6, 3, 5, 4); // 26move(initBoard, 2, 5, 3, 3); // 27move(initBoard, 7, 1, 5, 2); // 28move(initBoard, 0, 1, 1, 3); // 29move(initBoard, 7, 5, 7, 3); // 30move(initBoard, 0, 0, 0, 2); // 31move(initBoard, 5, 2, 3, 3); // 32move(initBoard, 1, 1, 3, 3); // 33move(initBoard, 5, 5, 7, 4); // 34move(initBoard, 1, 2, 2, 2); // 35move(initBoard, 7, 4, 5, 3); // 36move(initBoard, 0, 3, 2, 1); // 37move(initBoard, 7, 2, 5, 2); // 38move(initBoard, 3, 1, 4, 1); // 39move(initBoard, 5, 2, 6, 3); // 40move(initBoard, 2, 0, 3, 0); // 41move(initBoard, 7, 3, 7, 2); /* first is new position, second is original position followed by clear first = Y-axis counting down from top 0-8 second = X-axis counting Right from the left 0-8 */ // Move 1 — Queen's Pawn forward 2, d4 — begin Catalan opening, closed variation board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 2 — Nf6 board[2][5] = board[0][6]; board[0][6] = ' '; console.log(board.join('\n')); // Move 3 — c4 board[3][3] = board[6][2]; board[6][3] = ' '; console.log(board.join('\n')); // Move 4 — board[3][3] = board[1][4]; board[6][3] = ' '; console.log(board.join('\n')); // Move 5 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 6 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 7 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 8 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 9 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 10 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 11 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 12 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 13 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 14 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 15 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 16 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 17 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 18 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 19 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); // Move 20 — board[3][3] = board[6][3]; board[6][3] = ' '; console.log(board.join('\n')); })( window );
6b223700469e6046a986c8dbabf84e7cf579d169
[ "Markdown", "JavaScript" ]
2
Markdown
Epicurean306/TIY-Chessboard
7b7cbb73c359cb2928efd8a0c75724444f9ff644
c3d32a8cd1bc4f975df613034ee21f81baa77296
refs/heads/master
<repo_name>R1cardoX/python<file_sep>/qqmusic.py import time import re import requests from bs4 import BeautifulSoup from selenium.webdriver.chrome.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver from lxml import etree options = Options() options.add_argument("--headless") options.add_argument('--no-sandbox') options.add_argument('start-maximized') options.add_argument('window-size=1920x1080') options.add_argument("--mute-audio") options.add_argument('disable-infobars') options.add_argument("--disable-extensions") browser = webdriver.Chrome(executable_path = r'/usr/local/bin/chromedriver',options=options) name = input('输入要查找的歌曲名字:') base_search_url = 'https://y.qq.com/portal/search.html#remoteplace=txt.yqq.top&t=song&w='+name browser.get(base_search_url) browser.find_element_by_xpath('//*[@class="search_input__input"]').clear() browser.find_element_by_xpath('//*[@class="search_input__input"]').send_keys(name) time.sleep(1) browser.get("https://y.qq.com/portal/search.html#page=1&searchid=1&remoteplace=txt.yqq.top&t=song&w="+name) browser.find_element_by_xpath("//i").click() time.sleep(1) html = etree.HTML(browser.page_source) for i in range(1,21): result = html.xpath('//li['+str(i)+']//a[@class="js_song" or @class="singer_name" or @class="album_name"]/@title') print('序号',i,' 歌曲名:',result[0],' 歌手:',result[1],' 专辑:',result[2]) _id = input('输入要下载的歌曲:') if _id < '21' and _id > '0': song_url = html.xpath('//li['+ _id +']//a[@class="js_song"]/@href') else: song_url = html.xpath('//li//a[@title="'+ _id +'"]/@href') browser.get(song_url[0]) browser.find_element_by_link_text(u"播放").click() browser.close() try: browser.switch_to_window(browser.window_handles[0]) time.sleep(2) browser.find_element_by_id("btnplay").click() browser.find_element_by_id("simp_btn") wait.until html = browser.page_source soup = BeautifulSoup(html,'lxml') print(soup) source = soup.find("audio",{"src":re.compile(r'http://.+?')})['src'] except: print("Error") r = requests.get(source) source_name = source.split('?')[0].split('/')[-1] with open('./music/'+name+'.m4a', 'wb') as f: f.write(r.content) print('已下载') print('歌词:') for soup in soup.find_all(attrs={"class":"song_info__lyric_inner qrc_ctn"}): lyrics = soup.find_all("p",{"data-id":re.compile('line_\w+')}) for lyric in lyrics: print(lyric.get_text()) browser.quit() <file_sep>/hltv_data.py import re import pandas as pd import matplotlib.pyplot as plt import sys,time import requests import numpy as np from bs4 import BeautifulSoup from urllib.request import urlretrieve import os base_url_group = [r'https://www.hltv.org/events/archive?eventType=MAJOR&eventType=INTLLAN&prizeMin=247333&prizeMax=1500000',r'https://www.hltv.org/events/archive?offset=50&eventType=MAJOR&eventType=INTLLAN&prizeMin=247333&prizeMax=1500000'] bash_link = r'https://www.hltv.org' ranking_link = r'/ranking/teams' ranking_index = ['position','points','player1','player2','player3','player4','player5','link'] def get_ranking_soup(year,month,day): link = r'https://www.hltv.org/ranking/teams/'+year+'/'+month+'/'+day print('get ranking from ',link) html = requests.get(link).text soup = BeautifulSoup(html,'lxml') return soup def get_ranking_day(year,month): link = r'https://www.hltv.org/ranking/teams/2018/may/21' html = requests.get(link).text soup = BeautifulSoup(html,'lxml') day_url = soup.find_all("a",{"href":re.compile(r'/ranking/teams/'+year+r'/'+month+r'/(\d+)'),"class":re.compile(r'sidebar-single-line-item\s?(selected)?')}) _day = [] day_index = day_url[0] day_link = bash_link + day_index['href'] day_html = requests.get(day_link).text day_soup = BeautifulSoup(day_html,'lxml') all_day_url = day_soup.find_all("a",{"href":re.compile(r'/ranking/teams/'+year+r'/'+month+r'/(\d+)'),"class":re.compile(r'sidebar-single-line-item\s?(selected)?')}) for all_day_msg in all_day_url: all_day_num = all_day_msg['href'].split('/')[-1] _day.append(int(all_day_num)) _day = list(set(_day)) day = sorted(_day) return day def get_team_position(header): m = re.compile(r'#([0-9]{1,2})') position = m.search(str(header)) return position.group(1) def get_team_link(header): m = re.compile(r'class="name\sjs-link"\sdata-url="(/team/[0-9]{1,6}/.{2,15})">.{2,15}</span>') link = m.search(str(header)) if link: return bash_link + link.group(1) else: return None def get_team_num(header): m = re.compile(r'class="name\sjs-link"\sdata-url="/team/([0-9]{1,6})/.{2,15}">.{2,15}</span>') num = m.search(str(header)) if num: return num.group(1) else: return None def get_team_name(header): m = re.compile(r'class="name\sjs-link"\sdata-url="/team/[0-9]{1,6}/.{2,15}">(.{2,15})</span>') name = m.search(str(header)) if name: return name.group(1) else: return None def get_team_points(header): m = re.compile(r'\(([0-9]{1,4})\spoints\)') points = m.search(str(header)) if points: return points.group(1) else: return None def get_team_players(con): m = re.compile(r'data-url="/player/[0-9]{1,6}/.{1,20}">([^<>/]{1,20})<') players = m.findall(str(con)) if len(players) < 5: while 5-len(players): players.append('none') return players def get_team_data(soup): parents = soup.find_all("div",{"class":"bg-holder"}) flag = 0 for parent in parents: header = parent.find_all("div",{"class":"header"})[0] con = parent.find_all("div",{"class":"lineup-con"})[0] team_name = get_team_name(header) team_position = get_team_position(header) team_points = get_team_points(header) team_players = get_team_players(con) team_num = get_team_num(header) team_link = get_team_link(header) if flag == 0: data = pd.DataFrame([team_name,team_position,team_points,team_num,team_players[0],team_players[1],team_players[2],team_players[3],team_players[4],team_link],index=['name','position','points','num','player1','player2','player3','player4','player5','link'],columns=[team_name]) flag = 1 else: data[team_name] = pd.Series([team_name,team_position,team_points,team_num,team_players[0],team_players[1],team_players[2],team_players[3],team_players[4],team_link],index=['name','position','points','num','player1','player2','player3','player4','player5','link']) return data def RateOfWinning(_map,data): return data.get(_map+'_win')/(data.get(_map+'_win')-data.get(_map+'_lost')) def AllOfRate(data): datas = pd.Series([RateOfWinning('Cache',data),RateOfWinning('Train',data),RateOfWinning('Mirage',data),RateOfWinning('Inferno',data),RateOfWinning('Dust2',data),RateOfWinning('Overpass',data),RateOfWinning('Cobblestone',data),RateOfWinning('Nuke',data),],index=['Cache','Train','Mirage','Inferno','Dust2','Overpass','Cobblestone','Nuke']) return datas def get_team_result(link): #link = team_match_link html = requests.get(link).text soup = BeautifulSoup(html,'lxml') parents = soup.find_all("tr",{"class":re.compile("group-\d (first)?")}) _map = 'Cache|Train|Mirage|Inferno|Dust2|Overpass|Cobblestone|Nuke|Season' _lost = 'L|W|T' data = {'Cache_win':0,'Train_win':0,'Mirage_win':0,'Inferno_win':0,'Dust2_win':0,'Overpass_win':0,'Cobblestone_win':0,'Nuke_win':0,'Cache_lost':0,'Train_lost':0,'Mirage_lost':0,'Inferno_lost':0,'Dust2_lost':0,'Overpass_lost':0,'Cobblestone_lost':0,'Nuke_lost':0} for parent in parents: map_html = parent.find_all("td",{"class":"statsMapPlayed"})[0] time_html = parent.find_all("td",{"class":"time"})[0] lost_html = parent.find_all("td",{"class":re.compile("text-center match-(lost)?(won)?(tied)?\s?(lost)?(won)?")})[0] team_map = re.findall(_map,str(map_html))[0] if team_map == 'Season': continue team_lost = re.findall(_lost,str(lost_html))[0] team_time = re.findall(re.compile(r'\d{2}/\d{2}/\d{2}'),str(time_html)) print(team_map,' ',team_lost,' ' ,team_time) if team_lost == 'L': data.update({team_map+'_lost':data.get(team_map+'_lost')-1}) elif team_lost == 'W': data.update({team_map+'_win':data.get(team_map+'_win')+1}) return data def get_team_match_link(data,Team): if Team == 'Natus Vincere': return bash_link+"/stats/teams/matches/"+data.ix['num',Team]+'/'+'Natus%20Vincere' elif Team == 'Space Soldiers': return bash_link+"/stats/teams/matches/"+data.ix['num',Team]+'/'+'Space%20Soldiers' elif Team == 'ALTERNATE aTTaX': return bash_link+"/stats/teams/matches/"+data.ix['num',Team]+'/'+'ALTERNATE%20aTTaX' else: return bash_link+"/stats/teams/matches/"+data.ix['num',Team]+'/'+Team def get_stats_team(): url = r'https://www.hltv.org/stats/teams' html = requests.get(url).text soup = BeautifulSoup(html,'lxml') team_url = soup.find_all("a",{"href":re.compile(r'/stats/teams/[0-9]{1,6}/(.+)'),"data-tooltip-id":re.compile(r'.+')}) team_name = [] for team_link in team_url: team_link = team_link['href'].split('/')[-1] team_name.append(team_link) return team_name def get_team_plot(Team,data): link = get_team_match_link(data,Team) print('Connect From',link) datas = get_team_result(link) DATA = AllOfRate(datas) DATA.plot(kind = 'bar') plt.ylim((0,1)) plt.ylabel('Rate Of Win') plt.xlabel('Map') plt.xticks([0,1,2,3,4,5,6,7],[r'$Cache$',r'$Train$',r'$Mirage$',r'$Inferno$',r'$Dust2$',r'$Overpass$',r'$Cobblestone$',r'$Nuke$']) plt.show() def get_team_base(Team,data): print(data.ix[:,Team]) def get_match_data(base_url_group): flag = 1 for base_url in base_url_group: html = requests.get(base_url).text soup = BeautifulSoup(html,'lxml') img_url = soup.find_all("a",{"href":re.compile(r'/events/\d+/[\w\-]*'),"class":re.compile(r'[\s\-\w]*')}) for url in img_url: url = url['href'] match_url = url.split('/')[-1] match_name_group = match_url.split('-') match_num = url.split('/')[-2] match_name = '' for name in match_name_group: name = str.title(name) match_name = match_name + name + ' ' if flag == 1: match_data = pd.DataFrame([match_num,match_name,match_url],index=['num','match_name','match_url'],columns=[str(flag)]) else: match_data[str(flag)] = pd.Series([match_num,match_name,match_url],index=['num','match_name','match_url']) flag = flag + 1 return match_data.T def get_match_img_url(match_data,flag): return r'https://www.hltv.org/galleries?event=' + match_data.ix[str(flag),'num'] def get_team_img_url(team_data,team_name): return r'https://www.hltv.org/galleries?team=' + team_data.ix['num',team_name] #-------------------------------------------main--------------------------------------------- while True: allmonth = ['january','february','march','april','may','june','july','august','september','october','november','december'] somemonth = ['january','february','march','april','may'] allyear = ['2018','2017','2016','2015'] while True: year = input('输入要查看的年份:') if year in allyear: break else: print('重新输入') while True: month = input('输入要查看的月份:') if month == '1': month = 'january' elif month == '2': month = 'february' elif month == '3': month = 'march' elif month == '4': month = 'april' elif month == '5': month = 'may' elif month == '6': month = 'june' elif month == '7': month = 'july' elif month == '8': month = 'august' elif month == '9': month = 'september' elif month == '10': month = 'october' elif month == '11': month = 'november' elif month == '12': month = 'december' else: print('重新输入') continue if year == '2018' : if month not in somemonth: print('数据暂时不存在,重新输入') else: break else: break all_day = get_ranking_day(year,month) while True: print('日期仅限输入',end = '') for val in all_day: print(val,' ',end = '') print() day = '21' day = input('输入要查看的日期:') if int(day) in all_day: break else: print('重新输入') data = get_team_data(get_ranking_soup(year,month,day)) print('队伍排名') print(data.ix['position',:]) rule = input('输入要进行的操作1.查看Team的数据2.查看用户数据统计图3.下载图片') if rule == '1': print('30Ranking Team:\n',data.ix['position',:]) flag = 0 while True: Team = input('输入队名:') for val in range(30): if Team == data.ix['name',val]: get_team_base(Team,data) flag = 0 break flag = 1 if flag is 1: print('输入错误请重新输入') continue break break elif rule == '2': team_name = get_stats_team() print('stats Team:') i = 1 for name in get_stats_team(): if name == 'Space%20Soldiers': name = 'Space Soldiers' elif name == 'Natus%20Vincere': name = '<NAME>' elif name == 'ALTERNATE%20aTTaX': name = 'ALTERNATE aTTaX' print(i,' ',name) i = i+1 flag = 0 while True: Team = input('输入队名:') for val in range(30): if Team == data.ix['name',val]: get_team_plot(Team,data) flag = 0 break flag = 1 if flag is 1: print('现未支持,或输入错误') continue break elif rule == '3': match_data = get_match_data(base_url_group) flag = input('输入要查看的照片类别1.Team 2.Match:') while True: _flag = 0 if flag is '1': name = input('输入队伍名称:') for name in range(30): if name == data.ix['name',name]: print(get_team_img_url(data,name)) _flag = 0 break _flag = 1 if _flag is 1: print('现未支持,或输入错误') continue break elif flag is '2': while True: print(match_data.ix[:,'match_name']) _id = input('输入比赛ID:') if _id >= '0' and _id <= '51': print(get_match_img_url(match_data,_id)) break else: print('输入有误,重新输入') continue break break <file_sep>/imtool.py def imresize(im,sz): #resize pil_im = Image.fromarray(uint8(im)) return numpy.array(pil_im.resize(sz)) def histep(im,nbr_bins = 256): #直方图均衡化 imhist,bins = numpy.histogram(im.flatten(),nbr_bins,normed=True) cdf = imhist.cumsum() cdf = 255 * cdf /cdf[-1] im2 = np.interp(im.flatten,bins[:-1],cdf) return im2.reshape(im.shape),cdf def compute_average(imlist): averageim = numpy.array(Image.open(imlist[0]),'f') for imname in imlist[1:]: try: averageim += array(Image.open(imname)) except: print(imname+'...skipped') averageim /= len(imlist) return numpy.array(averageim,'uint8') <file_sep>/harris.py from scipy.ndimage import filters from PIL import Image from pylab import * from numpy import * def compute_harris_respose(im,sigma = 3): #对每个像素计算Harris角点检测器相应函数 #计算导数 imx = zeros(im.shape) filters.gaussian_filter(im,(sigma,sigma),(0,1),imx) imy = zeros(im.shape) filters.gaussian_filter(im,(sigma,sigma),(1,0),imy) Wxx = filters.gaussian_filter(imx*imx,sigma) Wxy = filters.gaussian_filter(imx*imy,sigma) Wyy = filters.gaussian_filter(imy*imy,sigma) Wdet = Wxx*Wyy - Wxy**2 Wtr = Wxx + Wyy return Wdet/Wtr def get_harris_points(harrisim,min_dist = 10,threshold = 0.1): #从一幅Harris相应图像中返回角点,min_dict为分割角点和图像边界的最少像素数目 #寻找高于阈值的候选角点 corner_threshold = harrisim.max() * threshold harrisim_t = (harrisim > corner_threshold) * 1 #得到候选点的坐标 coords = array(harrisim_t.nonzero()).T #以及他们的Harris响应值 candidate_values = [harrisim[c[0],c[1]] for c in coords] #对候选点按照Harris响应值进行排序 index = argsort(candidate_values) #将可行点的位置保存到数组中 allowed_locations = zeros(harrisim.shape) allowed_locations[min_dist:-min_dist,min_dist:-min_dist] = 1 #按照min_distance原则,选择最佳Harris点 filtered_corrds = [] for i in index: if allowed_locations[coords[i,0],coords[i,1]] == 1: filtered_corrds.append(coords[i]) allowed_locations[(coords[i,0]-min_dist):(coords[i,0]+min_dist),(coords[i,0]-min_dist):(coords[i,0]+min_dist)] = 0 return filtered_corrds def plot_harris_points(image,filtered_corrds): figure() gray() imshow(image) plot([p[1] for p in filtered_corrds],[p[0] for p in filtered_corrds],'*') axis('off') show() im = array(Image.open('./res/1.jpg').convert('L')) harrisim = compute_harris_respose(im) filtered_corrds = get_harris_points(harrisim,6) plot_harris_points(im,filtered_corrds)
3e8d9da76d2bf93bf76526975a85e7f049348f48
[ "Python" ]
4
Python
R1cardoX/python
a3481d1a4d475c3bcc37cf840b4c0dcb44ec69ee
9bd50778a1bebcdaa3944b530e198c6eaa673aab
refs/heads/master
<repo_name>stedy/seattle-parks-complete<file_sep>/spc.js var visitedCount = 0; for(var i=0; i < geojson.features.length; i++){ parkName = geojson.features[i]['properties']['name'] if(parkName in localStorage){ geojson.features[i]['properties']['visit'] = '#89959C' visitedCount++; } } updateProgress(); var map = L.map('map').setView([47.6031447,-122.3285673], 12); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); function getProgress(numOfParks, visited) { if (numOfParks === 0 || isNaN(numOfParks)) return 0; var result = parseInt(visited, 10) / parseInt(numOfParks, 10) * 100; console.log(result); return result.toFixed(2) + '%'; } function updateProgress() { document.getElementById("myModalLabel").innerHTML = getProgress(geojson.features.length, visitedCount); } function onEachFeature(feature, layer) { layer.bindPopup(feature.properties.name, { closeButton: false, offset: L.point(0, -10) }); layer.on('mouseover', function (e) { this.openPopup(); }); layer.on('mouseout', function (e) { this.closePopup(); }); layer.on('click', function (e) { placeName = feature.properties.name; if(placeName in localStorage){ localStorage.removeItem(placeName); this.setStyle({fillColor: '#8EDD65', stroke: '#8EDD65'}); visitedCount--; } else { localStorage.setItem(placeName, this.getLatLng().toString()); this.setStyle({fillColor: '#89959C', stroke: '#000000'}); visitedCount++; } updateProgress(); }); } geojsonLayer = L.geoJson(geojson, { style: function(feature) { return {color: feature.properties.visit}; }, pointToLayer: function(feature, latlng) { var currentZoom = map.getZoom(); return new L.CircleMarker(latlng, {radius: 10, fillOpacity: 0.85}); }, onEachFeature: onEachFeature }); map.addLayer(geojsonLayer); <file_sep>/README.md # Seattle Parks Complete I had a goal of visiting every park in Seattle but I had no good way of tracking them and the official [City of Seattle Parks Department site](https://www.seattle.gov/parks/find/parks) was not very user-friendly which lead me to create this site. I'm just using a [Leaflet map layer](https://leafletjs.com/) and [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) to keep track of individual parks visited. The basic framework of this site could easily be transformed into other location based checklists such as libraries, baseball stadiums, etc.
d4130669e5953fd2f4b7cf7cc4846e299e0c216a
[ "JavaScript", "Markdown" ]
2
JavaScript
stedy/seattle-parks-complete
53f6879287d3257c1191935c6e292486961851f5
a639163f6f3d6bdacbe38122960710b95fe5d962
refs/heads/master
<repo_name>MarcoPQ270/PruebaRecyclerview<file_sep>/app/src/main/java/com/example/prueba/MainActivity.kt package com.example.prueba import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.GridLayout import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.prueba.Adapters.AdapterRVest import com.example.prueba.dataclasses.Estudiantes class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setTheme(R.style.AppTheme) setContentView(R.layout.activity_main) //llenamos la lista val lista= listOf<Estudiantes>( Estudiantes("Marco","7", "Tics", "21"), Estudiantes("Mauricio","7", "Tics", "21"), Estudiantes("Didiere","7", "Tics", "21"), Estudiantes("Juan","7", "Tics", "21"), Estudiantes("Marco","7", "Tics", "21"), Estudiantes("Mauricio","7", "Tics", "21"), Estudiantes("Didiere","7", "Tics", "21"), Estudiantes("Juan","7", "Tics", "21") ) val recycler = findViewById<RecyclerView>(R.id.recyclerest) val adapter=AdapterRVest(this) recycler.adapter=adapter recycler.layoutManager = LinearLayoutManager(this) //recycler.layoutManager=GridLayoutManager(this,2) adapter.setDataToList(lista) } } <file_sep>/app/src/main/java/com/example/prueba/dataclasses/Estudiantes.kt package com.example.prueba.dataclasses //Modelos de datos data class Estudiantes ( val nombreest:String, val semestre:String, val carrera:String, val edad:String )<file_sep>/app/src/main/java/com/example/prueba/Adapters/AdapterRVest.kt package com.example.prueba.Adapters import android.app.Activity import android.content.Context import android.content.Intent 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.example.prueba.Activity2 import com.example.prueba.R import com.example.prueba.dataclasses.Estudiantes class AdapterRVest internal constructor(context: Context): RecyclerView.Adapter<AdapterRVest.estviewHolder>() { private val inflater:LayoutInflater= LayoutInflater.from(context) private var ListaEst= emptyList<Estudiantes>() fun setDataToList(lista:List<Estudiantes>){ this.ListaEst=lista notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): estviewHolder { val itemView=inflater.inflate(R.layout.recycler_item,parent,false) return estviewHolder(itemView) } override fun getItemCount(): Int { return ListaEst.size } override fun onBindViewHolder(holder: estviewHolder, position: Int) { holder.nombre.text=ListaEst.get(position).nombreest holder.semestre.text=ListaEst.get(position).semestre holder.carrera.text=ListaEst.get(position).carrera holder.edad.text=ListaEst.get(position).edad var intent = Intent(inflater.context, Activity2::class.java) holder.card.setOnClickListener{ val context=inflater.context as Activity context.startActivity(intent) } } //primero creamos la inner class inner class estviewHolder(itemView: View):RecyclerView.ViewHolder(itemView){ val card= itemView.findViewById<ConstraintLayout>(R.id.itemCard) val nombre= itemView.findViewById<TextView>(R.id.item_nom) val semestre=itemView.findViewById<TextView>(R.id.item_semestre) val carrera=itemView.findViewById<TextView>(R.id.item_carrera) val edad=itemView.findViewById<TextView>(R.id.item_edad) } }
503429e4bfba3ec6dfe85d38757575bed7d1df2a
[ "Kotlin" ]
3
Kotlin
MarcoPQ270/PruebaRecyclerview
353a80988f284b20fcd7e6c5e7c56bf256762301
3a35ee1d1023873b5f778c3f1e6eab8e27318e9d
refs/heads/master
<repo_name>Oneandthreeconsulting/CacheCowAndBrowser<file_sep>/CacheCowAndBrowser/Controllers/ValuesController.cs using System.Net.Http; using System.Web.Http; namespace CacheCowAndBrowser.Controllers { using System.Net.Http.Formatting; public class MyResponse { public string Name { get; set; } public string Title { get; set; } } public class ValuesController : ApiController { private MyResponse obj; public ValuesController() { this.obj = new MyResponse() { Name = "Test", Title = "Test" }; } public HttpResponseMessage GetDefaultHeaders() { var response = new HttpResponseMessage() { Content = new ObjectContent<MyResponse>(obj, new JsonMediaTypeFormatter()) }; return response; } public HttpResponseMessage GetWithNoCache() { var response = new HttpResponseMessage() { Content = new ObjectContent<MyResponse>(obj, new JsonMediaTypeFormatter()) }; response.Headers.Add("Cache-Control", "no-cache"); return response; } public HttpResponseMessage GetWithPragmaExpires() { var response = new HttpResponseMessage() { Content = new ObjectContent<MyResponse>(obj, new JsonMediaTypeFormatter()) }; response.Headers.Add("Pragma", "no-cache"); response.Content.Headers.TryAddWithoutValidation("Expires", "-1"); return response; } } }<file_sep>/CacheCowAndBrowser/App_Start/WebApiConfig.cs using System.Web.Http; namespace CacheCowAndBrowser { using System; using System.Net.Http.Headers; using CacheCow.Server; public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}"); //config.MessageHandlers.Add(new CachingHandler()); // Comment this in to make IE work correctly config.MessageHandlers.Add( new CachingHandler { CacheControlHeaderProvider = message => new CacheControlHeaderValue { Private = true, MustRevalidate = true, NoTransform = true, MaxAge = TimeSpan.Zero } }); } } }
71fc7be4bff0580e103a557df5245a6c88439a09
[ "C#" ]
2
C#
Oneandthreeconsulting/CacheCowAndBrowser
dd218984c6207ecffa72cfc0de7258deaa5442b9
7c230c4cd7d16720d6a6eb86b4bc571c757a0835
refs/heads/master
<repo_name>tgxworld/singlish<file_sep>/singlish.gemspec Gem::Specification.new do |s| s.name = "singlish" s.version = "0.0.1" s.date = "2015-03-18" s.summary = "Singlish from Singapore" s.description = "Write Your Ruby Code in Singlish!" s.authors = ["<NAME>"] s.email = "<EMAIL>" s.files = ["lib/singlish.rb"] s.homepage = "https://github.com/tgxworld/singlish" s.license = "MIT" end <file_sep>/lib/singlish.rb class Object def method_missing(method_name, *args, &block) if(method_name =~ /(.*)_(lah|lor|leh|ah|meh|hor|bo?)/) $1.chomp!('?') send($1, *args, &block) end end end <file_sep>/README.md # Learn Singlish with Ruby ## Install `gem install singlish` ## Usage ```ruby >> require 'singlish' >> [1, 2, 3].empty_ah? # Is it empty? I'm not very sure. => false >> [1, 2, 3].empty_lah # It is really empty. => false >> [1, 2, 3].empty_lor # Even if it is empty, I don't really care. => false >> [1, 2, 3].empty_leh # For some reason, it is empty. => false ``` ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request
59f370ff6a4fab975fff701023d8b0af3463381b
[ "Markdown", "Ruby" ]
3
Ruby
tgxworld/singlish
e45f399d31b9a98eda5066c24e0cebbcf3ad7777
83f2922b6295caefb6387b87dae56f155883329a
refs/heads/master
<repo_name>anil3a/monitorix<file_sep>/docs/monitorix.sql -- The following queries can help you setup the database for monitorix -- Please read all comments in this file before executing anything -- $Id: monitorix.sql 51 2011-09-20 00:07:57Z <EMAIL> $ -- Create a database called monitorix CREATE DATABASE `monitorix` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; -- Create a table called logentries with the needed columns CREATE TABLE IF NOT EXISTS `logentries` ( `entryID` int(11) NOT NULL AUTO_INCREMENT, `logType` varchar(50) NOT NULL DEFAULT 'default', `projectName` varchar(20) NOT NULL DEFAULT 'not available', `environment` varchar(15) NOT NULL DEFAULT 'not available', `priority` int(11) NOT NULL, `errorNumber` int(11) DEFAULT NULL, `message` text NOT NULL, `file` varchar(255) DEFAULT NULL, `line` int(11) DEFAULT NULL, `context` longtext, `stacktrace` longtext, `timestamp` varchar(30) NOT NULL, `priorityName` varchar(15) NOT NULL, PRIMARY KEY (`entryID`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ; -- Create a specific monitorix user and grant access to monitorix database -- You have to replace the *** with your password CREATE USER 'monitorix'@'localhost' IDENTIFIED BY '***'; -- Don't grant any global privileges -- You have to replace the *** with your password GRANT USAGE ON * . * TO 'monitorix'@'localhost' IDENTIFIED BY '***' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ; -- Grant all privileges on the monitorix database GRANT ALL PRIVILEGES ON `monitorix` . * TO 'monitorix'@'localhost';<file_sep>/README.markdown # DEPRECATED **This package is not compatible with ZF2, I am not going to rewrite this for ZF2, we implemented a wastly superior solution for which we wrote https://github.com/cloud-solutions/zend-sentry.** Monitorix is released under the New BSD License. The current version is Monitorix 1.2.1. ## What's nice about monitorix * integrated logging of php errors, exceptions, javascript errors, slow queries and more for your Zend Framework apps * log entries of all your apps in one filterable, sortable, queryable place (database) * very easy to set up * doesn't interfere with your default error reporting settings ## Features Monitorix is meant to offer a **light but free** alternative to the commercial monitoring solution integrated in Zend Server. ### Current Features * easy setup and integration with your existing Zend Framework applications * minimal bootstrapping and configuration * simple message logging * automated logging of php errors (optional) * automated logging of fatal php errors (optional) * automated logging of uncaught exceptions (optional) * automated logging of slow database queries (optional) * automated logging of javascript errors (optional) * fully unit tested ## Prerequisites * Zend Framework 1.10 or newer * PHP 5.3 or newer Needed for javascript error logging: * ZendX_JQuery or your own implementation of jQuery (more specifially, the jQuery Ajax plugin is needed.) Needed for running the unit tests: * phpUnit * [Mockery](https://github.com/padraic/mockery) ## Installation and usage ### Install as Composer package If you would like to install Monitorix as a [Composer](http://packagist.org/) package, add a file called `composer.json` to the root of your project and add the following: { "require": { "monitorix/monitorix": "1.2.1" } } If you already have a `composer.json` file, just add an attitional requirement for monitorix. ### Manual installation In case of a manual installation, we advise you to place monitorix in your app's `library/`folder or somewhere on your php include path. For example: docs |_LICENSE |_monitorix.sql library |_Monitorix |_Controller |_Plugin |_MonitorExceptions.php |_MonitorJavascript.php |_MonitorSlowQueries.php |_Monitor.php |_Version.php |_Zend <- your Zend Framework library ### Setup steps If you use Composer, skip to step 3. 1. Add the 'Monitorix' folder to your library folder or use a Symlink 2. Add 'Monitorix_' to your namespaces. 3. Create the database, the table and the user with the help of docs/monitorix.sql 4. Add the following connection block to your application.ini resources.monitor.db.adapter = "Pdo_Mysql" resources.monitor.db.params.username = "monitorix" resources.monitor.db.params.password = "<PASSWORD>" resources.monitor.db.params.dbname = "monitorix" 5. Add the following lines of code to your Bootstrap.php protected function _initMonitor() { $config = Zend_Registry::get('config'); $monitorDb = Zend_Db::factory($config->resources->monitor->db->adapter, $config->resources->monitor->db->params); $monitor = new Monitorix_Monitor(new Zend_Log_Writer_Db($monitorDb, 'logentries'), "yourProjectName"); //if you want to monitor php errors $monitor->registerErrorHandler(); //if you want to monitor fatal errors and syntax errors $monitor->logFatalErrors(); //if you want to log exceptions $monitor->logExceptions(); //if you want to monitor javascript errors $monitor->logJavascriptErrors(); //if you want to log slow database queries $monitor->logSlowQueries(array($dbAdapter)); } monitorix provides a fluid interface, so you could also write: $monitor->registerErrorHandler()->logFatalErrors()->logExceptions()->logSlowQueries(array($dbAdapter)); ### Usage #### General monitorix will attempt to set the 'environment' field automatically by using the APPLICATION_ENV constant. If this constant is not defined (should be) it will log everything with the default value of "undefined". You can also set the value in your bootstrap or elsewhere with: $monitor->setEnvironment('development'); Also, if you don't pass a project name when you setup the monitorix instance, you can later set it with: $monitor->setProjectName('myProjectName'); #### Logging PHP errors monitorix automatically logs PHP errors for you, if you use: $monitor->registerErrorHandler(); PHP errors are logged according to the 8 priorities documented in Zend_Log. monitorix has a field 'logType'. For logged PHP errors this field will contain the string "php error". #### Logging fatal PHP errors monitorix automatically logs the last PHP error before shutdown/exit, if you use: $monitor->logFatalErrors(); Such errors are a subclass of the "php error" type with a special context information "Last error before shutdown. Fatal or syntax.". #### Logging Exceptions monitorix automagically logs all Exceptions that bubble up to the surface (ancaught Exceptions) if you set: $monitor->logExceptions(); Exceptions are logged with priority '2 = CRIT'. The field 'logType' will contain the string "exception". #### Logging Javascript Errors monitorix automagically logs all javascript errors that are not caught during execution, if you set: $monitor->logJavascriptErrors(); monitorix will attempt to automatically: 1. init the view, if it can't be retrieved from the viewRenderer 2. register the jQuery view helper, if not registered already 3. enable jQuery, if it is not enabled yet If monitorix should fail to enable jQuery, it will throw a Monitorix_Exception. If you have a custom implementation of jQuery, you can suppress step 2 and 3 of this list by passing FALSE as second parameter. $monitor->logJavascriptErrors(TRUE, FALSE); The view has to be available though, so that monitorix can prepend its 'window.onerror' script. #### Logging Slow Database Queries monitorix automagically logs all database queries that take longer than 1 second or any other value you pass, if you set: $monitor->logSlowQueries(array($myDbAdapter, $myOtherDbAdapter), 0.5); As first parameter you can pass an array of as many Zend_Db_Adapter instances as you wish. Normally you'll probably have one. As second argument, you can pass a limit in seconds. Every query which takes longer than that, will be logged. #### Logging other events With monitorix you can log whaterver you want, wherever you want. Here a few examples: //get the monitorix instance from the registry $monitor = Zend_Registry::get('monitor'); //log a simple message, it will be logged with the default priority 7 = DEBUG and the 'logType' "simpleLog" $monitor->writeLog('A simple message'); //log a message with a custom 'logType' and a custom priority $monitor->writeLog('A special message', 5, 'myCustomLogType'); //set your own default log type $monitor->setDefaultLogType('myDefault'); //and then log to this type simply with $monitor->writeLog('this will be logged with my new default logType'); ## Contributions This project is developed by the team of www.cloud-solutions.net. Additional contributions have been made by: * <NAME> - Fatal error logging through use of register_shutdown_function You're welcome to contribute to the component! Just contact us, if you're interested! <file_sep>/tests/library/Monitorix/Controller/Plugin/MonitorExceptionsTest.php <?php /** * cloud solutions monitorix * * This source file is part of the cloud solutions monitorix package * * @category Monitorix * @package Tests * @license New BSD License {@link /docs/LICENSE} * @copyright Copyright (c) 2011, cloud solutions O� * @version $Id: MonitorExceptionsTest.php 51 2011-09-20 00:07:57Z <EMAIL> $ */ use Mockery\Mock; require_once 'Zend/Controller/Plugin/Abstract.php'; require_once 'Zend/Registry.php'; require_once 'Monitorix/Controller/Plugin/MonitorExceptions.php'; use \Mockery as m; /** * Monitorix_Controller_Plugin_MonitorExceptions test case. */ class Monitorix_Controller_Plugin_MonitorExceptionsTest extends PHPUnit_Framework_TestCase { /** * @var monitorExceptions */ private $monitorExceptions; /** * Prepares the environment before running a test. */ protected function setUp () { $response = m::mock('Zend_Controller_Response_Abstract'); $response->shouldReceive('isException')->andReturn(TRUE); $this->monitorExceptions = new Monitorix_Controller_Plugin_MonitorExceptions(); $this->monitorExceptions->setResponse($response); $monitor = m::mock('monitor'); $monitor->shouldReceive('writeLog')->once(); Zend_Registry::set('monitor', $monitor); } /** * Cleans up the environment after running a test. */ protected function tearDown() { $this->monitorExceptions = null; Zend_Registry::_unsetInstance(); m::close(); } /** * Tests MonitorExceptions->dispatchLoopShutdown() * Doesn't test the actual writeLog method, that is covered by {@see Monitorix_MonitorTest} */ public function testDispatchLoopShutdown() { try { $this->monitorExceptions->dispatchLoopShutdown(); } catch (Exception $exception) { $this->fail('An exception was thrown: ' . $exception->getMessage()); } } } <file_sep>/tests/library/Monitorix/MonitorTest.php <?php /** * cloud solutions monitorix * * This source file is part of the cloud solutions monitorix package * * @category Monitorix * @package Tests * @license New BSD License {@link /docs/LICENSE} * @copyright Copyright (c) 2011, cloud solutions O� * @version $Id: MonitorTest.php 51 2011-09-20 00:07:57Z <EMAIL> $ */ require_once 'Zend/Log.php'; require_once 'Zend/Controller/Plugin/Abstract.php'; require_once 'Zend/Log/Writer/Mock.php'; require_once 'Zend/Registry.php'; require_once 'Zend/Controller/Front.php'; require_once 'Monitorix/Monitor.php'; require_once 'Monitorix/Controller/Plugin/MonitorExceptions.php'; require_once 'Monitorix/Controller/Plugin/MonitorSlowQueries.php'; require_once 'Monitorix/Controller/Plugin/MonitorJavascript.php'; use \Mockery as m; /** * Test class for Monitorix_Monitor. * Generated by PHPUnit on 2011-04-18 at 12:16:31. */ class Monitorix_MonitorTest extends PHPUnit_Framework_TestCase { /** * @var Monitorix_Monitor */ protected $monitor; protected $writer; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->writer = new Zend_Log_Writer_Mock(); $this->monitor = new Monitorix_Monitor($this->writer, 'testproject'); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { restore_error_handler(); Zend_Controller_Front::getInstance()->resetInstance(); m::close(); } /** * testWriteLog(). */ public function testWriteSimpleLogMessage() { //prepare $this->monitor->writeLog('test'); //assertions $this->assertContains('test', $this->writer->events[0]['message']); $this->assertContains('simplelog', $this->writer->events[0]['logType']); $this->assertContains('testing', $this->writer->events[0]['environment']); $this->assertContains('testproject', $this->writer->events[0]['projectName']); $this->assertEquals(7, $this->writer->events[0]['priority']); } /** * testWriteLog(). */ public function testWriteCustomLogMessage() { //prepare $this->monitor->setEnvironment('nextenv'); $this->monitor->setProjectName('monitorix'); $this->monitor->writeLog('nexttest', 1, 'nexttype'); //assertions $this->assertContains('nexttest', $this->writer->events[0]['message']); $this->assertContains('nexttype', $this->writer->events[0]['logType']); $this->assertContains('nextenv', $this->writer->events[0]['environment']); $this->assertContains('monitorix', $this->writer->events[0]['projectName']); $this->assertEquals(1, $this->writer->events[0]['priority']); } /** * testWriteLog(). * * @runInSeparateProcess */ public function testWriteException() { $exception = m::mock('alias:Zend_Exception'); $exception->shouldReceive('getMessage')->once()->andReturn('testmessage'); $exception->shouldReceive('getCode')->once()->andReturn('10'); $exception->shouldReceive('getFile')->once()->andReturn('/testpath/'); $exception->shouldReceive('getLine')->once()->andReturn('0'); $exception->shouldReceive('getTrace')->once()->andReturn(array()); $response = m::mock('alias:Zend_Controller_Response_Http'); $response->shouldReceive('getException')->once()->andReturn(array($exception)); $this->monitor->writeLog($response); //assertions $this->assertContains('testmessage', $this->writer->events[0]['message']); $this->assertContains('exception', $this->writer->events[0]['logType']); $this->assertContains('10', $this->writer->events[0]['errorNumber']); $this->assertEquals(2, $this->writer->events[0]['priority']); } /** * testLogExceptions(). */ public function testRegisterMonitorExceptionsPlugin() { $this->runTestInSeparateProcess = TRUE; $frontController = Zend_Controller_Front::getInstance(); $this->monitor->logExceptions(TRUE); $this->assertContains('Monitorix_Controller_Plugin_MonitorExceptions', get_class($frontController->getPlugin('Monitorix_Controller_Plugin_MonitorExceptions'))); $this->assertTrue($this->monitor->loggingExceptions); return $frontController; } /** * testLogExceptions(). * * @depends testRegisterMonitorExceptionsPlugin */ public function testRemoveMonitorExceptionsPlugin($frontController) { $this->runTestInSeparateProcess = TRUE; $this->runTestInSeparateProcess = TRUE; $this->monitor->logExceptions(FALSE); $this->assertFalse($frontController->getPlugin('Monitorix_Controller_Plugin_MonitorExceptions')); $this->assertFalse($this->monitor->loggingExceptions); } /** * testLogSlowQueries(). */ public function testRegisterSlowQueriesPlugin() { $frontController = Zend_Controller_Front::getInstance(); $adapter = m::mock('alias:Zend_Db_Adapter_Pdo_Mysql'); $profiler = m::mock('alias:Zend_Db_Profiler'); $adapter->shouldReceive('getProfiler->setEnabled')->andReturn($profiler); $this->monitor->logSlowQueries(array($adapter)); $this->assertContains('Monitorix_Controller_Plugin_MonitorSlowQueries', get_class($frontController->getPlugin('Monitorix_Controller_Plugin_MonitorSlowQueries'))); $this->assertTrue($this->monitor->loggingSlowQueries); $profilers = Zend_Registry::get('profilers'); $this->assertTrue($profilers[0] instanceof Zend_Db_Profiler); return $frontController; } /** * testLogSlowQueries(). * * @depends testRegisterSlowQueriesPlugin */ public function testRemoveSlowQueriesPlugin($frontController) { $this->monitor->logSlowQueries(array(), null, FALSE); $this->assertFalse($frontController->getPlugin('Monitorix_Controller_Plugin_MonitorSlowQueries')); $this->assertFalse($this->monitor->loggingSlowQueries); } /** * testLogJavascriptErrors() * */ public function testRegisterJavascriptPlugin() { if (getenv('TRAVIS')) { $this->markTestSkipped('ZendX is not available on Travis CI at the moment.'); } $frontController = Zend_Controller_Front::getInstance(); $this->monitor->logJavascriptErrors(); $this->assertContains('Monitorix_Controller_Plugin_MonitorJavascript', get_class($frontController->getPlugin('Monitorix_Controller_Plugin_MonitorJavascript'))); $this->assertTrue($this->monitor->loggingJavascriptErrors); $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); $view = $viewRenderer->view; $this->assertTrue(strpos($view->headScript()->toString(), 'window.onerror') <> FALSE); return $frontController; } /** * testLogJavascriptErrors() * * @depends testRegisterJavascriptPlugin */ public function testRemoveJavascriptPlugin($frontController) { $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); $view = $viewRenderer->view; $this->monitor->logJavascriptErrors(FALSE); $this->assertFalse($frontController->getPlugin('Monitorix_Controller_Plugin_MonitorJavascript')); $this->assertFalse($this->monitor->loggingJavascriptErrors); $this->assertNull($view); } /** * Tests Monitorix_Monitor->setDefaultLogType() */ public function testSetDefaultLogType () { $this->monitor->setDefaultLogType('newdefault'); $this->monitor->writeLog('test'); $this->assertContains('newdefault', $this->writer->events[0]['logType']); } /** * Tests Monitorix_Monitor->getProjectName() */ public function testGetProjectName () { $projectName = $this->monitor->getProjectName(); $this->assertContains('testproject', $projectName); } /** * Tests Monitorix_Monitor->getEnvironment() */ public function testGetEnvironment () { $environment = $this->monitor->getEnvironment(); $this->assertContains('testing', $environment); } /** * testErrorHandler() */ public function testErrorHandlerWritesToLog() { //prepare set_error_handler(array($this->monitor, 'errorHandler')); trigger_error('testerror'); //assertions $this->assertContains('testerror', $this->writer->events[0]['message']); $this->assertContains('php_error', $this->writer->events[0]['logType']); $this->assertContains('testing', $this->writer->events[0]['environment']); $this->assertContains('testproject', $this->writer->events[0]['projectName']); $this->assertEquals(6, $this->writer->events[0]['priority']); restore_error_handler(); } } ?> <file_sep>/tests/bootstrap.php <?php /** * cloud solutions monitorix * * This source file is part of the cloud solutions monitorix package * * @category Monitorix * @package Tests * @license New BSD License {@link /docs/LICENSE} * @copyright Copyright (c) 2011, cloud solutions O� * @version $Id: bootstrap.php 51 2011-09-20 00:07:57Z <EMAIL> $ */ // Define application environment defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( dirname(dirname( __FILE__ )) . '/library/', dirname(__FILE__) . '/library/', get_include_path() ))); date_default_timezone_set('Europe/Zurich'); if (getenv('TRAVIS') == true) { require 'vendor/.composer/autoload.php'; } else { require_once 'Mockery/Loader.php'; require_once 'Hamcrest/Hamcrest.php'; } $loader = new \Mockery\Loader; $loader->register();<file_sep>/tests/library/Monitorix/Controller/Plugin/MonitorSlowQueriesTest.php <?php /** * cloud solutions monitorix * * This source file is part of the cloud solutions monitorix package * * @category Monitorix * @package Tests * @license New BSD License {@link /docs/LICENSE} * @copyright Copyright (c) 2011, cloud solutions O� * @version $Id: MonitorSlowQueriesTest.php 50 2011-09-16 14:54:07Z <EMAIL> $ */ require_once 'Zend/Controller/Plugin/Abstract.php'; require_once 'Zend/Controller/Request/Abstract.php'; require_once 'Zend/Controller/Response/Abstract.php'; require_once 'Zend/Registry.php'; require_once 'Monitorix/Controller/Plugin/MonitorSlowQueries.php'; use \Mockery as m; /** * Monitorix_Controller_Plugin_MonitorSlowQueries test case. */ class Monitorix_Controller_Plugin_MonitorSlowQueriesTest extends PHPUnit_Framework_TestCase { /** * @var $monitorSlowQueries */ private $monitorSlowQueries; /** * Prepares the environment before running a test. */ protected function setUp () { $monitor = m::mock('monitor'); $monitor->shouldReceive('writeLog')->once(); $monitor->shouldReceive('getSlowQueryLimitSeconds')->andReturn(1.5); $queryOne = m::mock('queryone'); $queryOne->shouldReceive('getElapsedSecs')->andReturn(1); $queryTwo = m::mock('querytwo'); $queryTwo->shouldReceive('getElapsedSecs')->twice()->andReturn(2); $queryTwo->shouldReceive('getQuery')->once(); $queryTwo->shouldReceive('getQueryParams')->once()->andReturn(array()); $profiler = m::mock('profiler'); $profiler->shouldReceive('getTotalNumQueries')->andReturn(TRUE); $profiler->shouldReceive('getQueryProfiles')->andReturn(array($queryOne, $queryTwo)); $profiler->shouldReceive('clear'); $this->monitorSlowQueries = new Monitorix_Controller_Plugin_MonitorSlowQueries(); Zend_Registry::set('monitor', $monitor); Zend_Registry::set('profilers', array($profiler)); } /** * Cleans up the environment after running a test. */ protected function tearDown () { $this->monitorExceptions = null; Zend_Registry::_unsetInstance(); m::close(); } /** * Tests MonitorExceptions->dispatchLoopShutdown() * Doesn't test the actual writeLog method, that is covered by {@see Monitorix_MonitorTest} */ public function testDispatchLoopShutdown() { try { $this->monitorSlowQueries->dispatchLoopShutdown(); } catch (Exception $exception) { $this->fail('An exception was thrown: ' . $exception->getMessage()); } } } <file_sep>/tests/library/Monitorix/Controller/Plugin/MonitorJavascriptTest.php <?php /** * cloud solutions monitorix * * This source file is part of the cloud solutions monitorix package * * @category Monitorix * @package Tests * @license New BSD License {@link /docs/LICENSE} * @copyright Copyright (c) 2011, cloud solutions O� * @version $Id: MonitorJavascriptTest.php 54 2011-09-20 00:19:05Z <EMAIL> $ */ require_once 'Zend/Registry.php'; require_once 'Monitorix/Controller/Plugin/MonitorJavascript.php'; use \Mockery as m; /** * Monitorix_Controller_Plugin_MonitorSlowQueries test case. */ class Monitorix_Controller_Plugin_MonitorJavascriptTest extends PHPUnit_Framework_TestCase { /** * @var $monitorSlowQueries */ private $monitorJavascriptErrors; /** * Prepares the environment before running a test. */ protected function setUp () { $monitor = m::mock('monitor'); $monitor->shouldReceive('writeLog')->once(); Zend_Registry::set('monitor', $monitor); $_POST['message'] = 'testmessage'; $_POST['errorUrl'] = 'noRealUrl'; $_POST['errorLine'] = '777'; $this->monitorJavascriptErrors = new Monitorix_Controller_Plugin_MonitorJavascript(); } /** * Cleans up the environment after running a test. */ protected function tearDown () { $this->monitorJavascriptErrors = null; Zend_Registry::_unsetInstance(); unset($_POST['message']); unset($_POST['errorUrl']); unset($_POST['errorLine']); m::close(); } /** * Tests MonitorJavascriptErrors->routeStartup() * Doesn't test the actual writeLog method, that is covered by {@see Monitorix_MonitorTest} */ public function testRouteStartup() { $request = m::mock('Zend_Controller_Request_Abstract'); $request->shouldReceive('__get')->with('monitori')->once()->andReturn('x'); $request->shouldReceive('isXmlHttpRequest')->once()->andReturn(TRUE); try { $this->monitorJavascriptErrors->routeStartup($request); } catch (Exception $exception) { $this->fail('An exception was thrown: ' . $exception->getMessage()); } } }
9c2dff6c503a2fe84c23da0d9aa0e4e33791091b
[ "Markdown", "SQL", "PHP" ]
7
SQL
anil3a/monitorix
e2e7a3aefcf5491b1019365cdf845ef5217f8ff5
0df944747a0e322374164af9c117f20d1d3326af
refs/heads/master
<file_sep>package com.advertisementproject.userservice.api.exception; /** * Custom RuntimeException for when an email is already registered in the database */ public class EmailAlreadyRegisteredException extends RuntimeException { /** * Constructor * * @param message the error message to be shown */ public EmailAlreadyRegisteredException(String message) { super(message); } } <file_sep>package com.advertisementproject.zuulgateway.ZuulFilter; import com.advertisementproject.zuulgateway.security.Utils.JwtUtils; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import javax.servlet.http.HttpServletRequest; /** * Zuul Filter that extracts the user id from a bearer token in the request header and attaches the user id to be * forwarded to the requested endpoint. Also logs which type of request is being routed and to which endpoint. */ @Slf4j @RequiredArgsConstructor public class ZuulRequestFilter extends ZuulFilter { /** * Service that handles JWT related tasks such as extracting the subject from a JWT token. */ private final JwtUtils jwtUtils; /** * Sets the type of filter * * @return string indicating the type of filter */ @Override public String filterType() { return "pre"; } /** * Sets the filter order * * @return integer indicating the filter order */ @Override public int filterOrder() { return 1; } /** * Sets whether filters should be run * * @return always returns true */ @Override public boolean shouldFilter() { return true; } /** * Runs the filter. Extracts user id from jwt token in header using JwtUtils and attaches it to the header of the * request which is about to be forwarded. Logs which type of request has been sent and to which endpoint. * * @return null */ @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString())); String header = request.getHeader("Authorization"); if (header == null || !header.startsWith("Bearer ")) { return null; } String token = header.replace("Bearer ", ""); String userId = jwtUtils.extractSubject(token); ctx.addZuulRequestHeader("userId", userId); return null; } } <file_sep>import React from "react"; import Dialog from "@material-ui/core/Dialog"; import Button from "@material-ui/core/Button"; import InputAdornment from "@material-ui/core/InputAdornment"; import TextField from "@material-ui/core/TextField"; import AssignmentIcon from "@material-ui/icons/Assignment"; import { withStyles, makeStyles } from "@material-ui/core/styles"; import Card from "@material-ui/core/Card"; import CardActions from "@material-ui/core/CardActions"; import CardContent from "@material-ui/core/CardContent"; import CardMedia from "@material-ui/core/CardMedia"; import Typography from "@material-ui/core/Typography"; import StandardImg from "../../../resources/campaignMicro.png"; const DarkerDisabledTextField = withStyles({ root: { marginRight: 8, "& .MuiInputBase-root.Mui-disabled": { color: "rgba(0, 0, 0, 0.8)", // (default alpha is 0.38) }, }, })(TextField); const useStyles = makeStyles({ root: { maxWidth: 340, }, image: { height: 140, opacity: 0.8, }, buttons: { justifyContent: "center", }, discountCode: { justifyContent: "center", display: "flex", }, textInModal: { marginTop: 10, marginBottom: 10, }, // companyName: { // transform: 'Translate(-50%, -50%)', // textAlign: 'center', // top: 130, // left: '50%', // fontWeight: 'bold', // position: 'absolute' // }, dialog: {}, }); const CampaignModal = (props) => { const classes = useStyles(); const handleRedirect = () => { navigator.clipboard.writeText(props.discountCode); props.onHide(); }; const handleClose = () => { props.onHide(); }; return ( <> <Dialog onClose={handleClose} aria-labelledby="dialog-title" open={props.show} className={classes.dialog} > <Card className={classes.root}> <CardMedia className={classes.image} component="img" alt="company image" image={ props.campaign.image ? props.campaign.image : StandardImg } title="company imageurur" /> <CardContent className={classes.cardContent}> <Typography align="center" variant="h5" fontWeight="bold" className={classes.companyName} > {props.campaign.company_name} </Typography> <Typography align="center" variant="h4" className={classes.textInModal} > {props.campaign.title} </Typography> <Typography align="center" className={classes.textInModal}> {props.campaign.discount} {props.campaign.isPercentage === true ? " % Discount" : props.campaign.currency + " Discount"} </Typography> <Typography className={classes.textInModal} align="center"> Description??? {props.campaign.description} </Typography> <div className={classes.discountCode}> <DarkerDisabledTextField id="input-with-icon-textfield" label="Discount code" align="center" InputProps={{ startAdornment: ( <InputAdornment position="start"> <AssignmentIcon /> </InputAdornment> ), }} disabled value={props.discountCode} variant="outlined" /> </div> </CardContent> <CardActions className={classes.buttons}> <Button variant="contained" color="primary" onClick={handleRedirect} > Copy discount & Close </Button> </CardActions> </Card> </Dialog> </> ); }; export default CampaignModal; <file_sep>package com.advertisementproject.zuulgateway.db.entity; import lombok.Data; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import java.time.Instant; import java.util.UUID; /** * Permissions are kept up-to-date by receiving messages from Permission Service application and then updating the * table accordingly whenever a permission object is created, updated or deleted. Permission includes which user id, * whether permission is granted and timestamps for creation and latest update. */ @Data @Entity public class Permission { /** * Primary id for Permission entity, matching the user id */ @Id private UUID userId; /** * Whether the user has permission to use the system. Can be revoked by an admin user if needed to indirectly * invalidate jwt tokens and block user in the case of suspicious activity. True if the user has permission, * otherwise false. */ private boolean hasPermission; /** * Timestamp for when the permission was created. */ @Column(columnDefinition = "TIMESTAMP WITH TIME ZONE") private Instant createdAt; /** * Timestamp for when the permission was last updated. */ @Column(columnDefinition = "TIMESTAMP WITH TIME ZONE") private Instant updatedAt; } <file_sep>export const UserReducer = (state, action) => { switch (action.type) { case "LOAD_USER": console.log(action.payload.role); return { isLoggedIn: action.payload.token ? true : false, role: action.payload.role ? action.payload.role : "", }; case "LOGIN": return { isLoggedIn: action.payload.token ? true : false, role: action.payload.role ? action.payload.role : "", }; case "LOGOUT": return { isLoggedIn: false, role: "", }; default: return; } }; <file_sep>package com.advertisementproject.campaignservice.service; import com.advertisementproject.campaignservice.db.repository.CampaignRepository; import com.advertisementproject.campaignservice.service.interfaces.ScheduledJobsService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.time.Instant; /** * Service implementation for running scheduled jobs to keep the database in desired state and removing unwanted data. */ @Service @RequiredArgsConstructor @Slf4j @EnableScheduling public class ScheduledJobsServiceImpl implements ScheduledJobsService { /** * JPA Repository for Campaigns. */ private final CampaignRepository campaignRepository; /** * Runs scheduled jobs every 10 minutes */ @Scheduled(cron = "0 */10 * * * *") @Override public void runScheduledJobs() { log.info("Running scheduled jobs"); publishScheduledCampaigns(); removeExpiredCampaigns(); } /** * Publishes scheduled campaigns and logs the number of campaigns that were published */ @Override public void publishScheduledCampaigns() { int nrOfPublishedCampaigns = campaignRepository.publishScheduledCampaigns(Instant.now()); log.info("[SCHEDULED] Published " + nrOfPublishedCampaigns + " scheduled campaign(s)"); } /** * Removes expired campaigns and logs the number of campaigns that were removed */ @Override public void removeExpiredCampaigns() { int nrOfExpiredCampaigns = campaignRepository.removeExpiredCampaigns(Instant.now()); log.info("[SCHEDULED] Removed " + nrOfExpiredCampaigns + " expired campaign(s)"); } } <file_sep>package com.advertisementproject.zuulgateway.RepositoryTest; import com.advertisementproject.zuulgateway.db.repositories.UserRepository; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @ActiveProfiles("test") @Testcontainers @DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) public class LoginTest { @Container static PostgreSQLContainer<?> postgreSQLContainer = new PostgreSQLContainer<>("postgres:13.0"); @Autowired UserRepository repository; @DynamicPropertySource static void postgresProperties(DynamicPropertyRegistry registry) { registry.add("spring.datasource.url", postgreSQLContainer::getJdbcUrl); registry.add("spring.datasource.username", postgreSQLContainer::getUsername); registry.add("spring.datasource.password", postgreSQLContainer::getPassword); } // We need to create a utility class that mocks our data // We also need to find a better solution to not repeat code in every test class @Test public void shouldRegisterUser() { // User user = new User(); // user.setId(UUID.randomUUID()); // user.setEmail("<EMAIL>"); // user.setHashedPassword("<PASSWORD>"); // user.setPhoneNumber("0709724042"); // user.setEnabled(true); // repository.save(user); // Optional<User> userFromDB = repository.findById(user.getId()); // Assertions.assertThat(user.getId()).isEqualTo(userFromDB.get().getId()); } } <file_sep>package com.advertisementproject.userservice.api.response; import com.advertisementproject.userservice.db.entity.Customer; import com.advertisementproject.userservice.db.entity.User; import lombok.AllArgsConstructor; import lombok.Getter; /** * Response object including a user and customer, in other words a customer user */ @AllArgsConstructor @Getter public class CustomerUserResponse { /** * The core user details for the customer user. */ private final User user; /** * Customer information for the customer user. */ private final Customer customer; } <file_sep>package com.advertisementproject.campaignservice.swagger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; /** * Swagger configuration file. Defines a docket bean that includes basic configurations such as base package as well as * API information to display. */ @Configuration public class SwaggerConfig { /** * Docket configuration bean * @return docket with basic configuration and api information */ @Bean public Docket docket() { return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.advertisementproject")) .paths(PathSelectors.any()) .build(); } /** * Defines api information for swagger api documentation * @return ApiInfo object with hard coded api information for this application */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Campaign Service API") .description("Campaign Service allows for creation and management of campaigns for company users and " + "allows all users to view all published campaigns with limited information. Discount code is hidden and requires logging in " + "to retrieve from a separate endpoint. " + "This service receives updates about company information via message broker.") .contact(new Contact("Campaign Company", "http://campaign-company.com", "<EMAIL>")) .version("3.0") .build(); } } <file_sep>import { useState } from "react"; import { FormWithRedirect, TextInput, Toolbar, SaveButton, DeleteButton, DateTimeInput, SelectInput, ImageInput, ImageField, } from "react-admin"; import { Typography, Box } from "@material-ui/core"; import CreateCampaignCard from "./createCampaignCard.component"; const CreateForm = (props) => { const [campaign, setCampaign] = useState({ title: "", description: "", category: "", discount: "", publishedAt: "", expiresAt: "", isPercentage: "", image: "", discountCode: "", }); const handleChange = (prop) => (e) => { setCampaign({ ...campaign, [prop]: e.target.value }); }; const handleImage = (img) => { let reader = new FileReader(); reader.onload = function (event) { setCampaign({ ...campaign, image: event.target.result }); }; reader.readAsDataURL(img[0]); }; return ( <FormWithRedirect {...props} render={(formProps) => ( <form> <Box p="1em" display="flex" justifyContent="center"> <Box display="flex"> <Box flex={2} mr="1em"> <Typography variant="h6" gutterBottom> Campaign </Typography> <Box display="flex"> <Box flex={1} mr="0.5em"> <TextInput source="title" fullWidth required value={campaign.title} onChange={handleChange("title")} /> </Box> <Box flex={1} ml="0.5em"> <TextInput source="category" fullWidth required value={campaign.category} onChange={handleChange("category")} /> </Box> </Box> <TextInput source="description" fullWidth multiline value={campaign.description} onChange={handleChange("description")} /> <ImageInput accept="image/*" source="image" options={{onDrop: image => handleImage(image)}}> <ImageField source="url" title="Title or url" /> </ImageInput> <Typography variant="h6" gutterBottom> Discount </Typography> <Box display="flex"> <Box flex={1} mr="0.5em"> <TextInput source="discount" type="number" fullWidth required value={campaign.discount} onChange={handleChange("discount")} /> </Box> <Box> <SelectInput source="isPercentage" label="Discount Type" onChange={handleChange("isPercentage")} choices={[ { id: true, name: "Percentage" }, { id: false, name: "SEK" }, ]} /> </Box> <Box flex={1} ml="0.5em"> <TextInput source="discountCode" fullWidth required value={campaign.discountCode} onChange={handleChange("discountCode")} /> </Box> </Box> <Box mt="1em" /> <Typography variant="h6" gutterBottom> Publish Info, Leave empty if you wanna publish now </Typography> <Box display="flex"> <Box flex={1} mr="0.5em"> <DateTimeInput source="publishAt" fullWidth value={campaign.publishedAt} onChange={handleChange("publishedAt")} /> </Box> <Box flex={2} ml="0.5em"> <DateTimeInput source="expiresAt" fullWidth value={campaign.expiresAt} onChange={handleChange("expiresAt")} /> </Box> </Box> </Box> <Box flex={1} ml="1em"> <CreateCampaignCard {...campaign} /> </Box> </Box> </Box> <Toolbar> <Box display="flex" justifyContent="center" width="100%"> <SaveButton saving={formProps.saving} handleSubmitWithRedirect={formProps.handleSubmitWithRedirect} /> <DeleteButton record={formProps.record} /> </Box> </Toolbar> </form> )} /> ); }; export default CreateForm; <file_sep>FROM maven:3.6.3-openjdk-15-slim as jreBuilder RUN mkdir /usr/src/project COPY . /usr/src/project WORKDIR /usr/src/project RUN mvn package -DskipTests FROM adoptopenjdk/openjdk15:x86_64-alpine-jre-15.0.2_7 RUN mkdir /project COPY --from=jreBuilder /usr/src/project/target/permission-service-0.0.1-SNAPSHOT.jar /project/ WORKDIR /project CMD java -jar permission-service-0.0.1-SNAPSHOT.jar <file_sep>package com.advertisementproject.userservice.db.entity; import com.advertisementproject.userservice.api.request.CustomerRegistrationRequest; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.Id; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.UUID; /** * Customer entity for customer users with personal information about the user */ @Data @Entity @AllArgsConstructor @NoArgsConstructor @Builder public class Customer { /** * Primary id for Customer entity that matches user id. */ @Id private UUID userId; /** * The first name of the customer. */ @NotNull @Size(min = 2, max = 20, message = "First name must be 2-20 characters long") private String firstName; /** * The last name of the customer. */ @NotNull @Size(min = 2, max = 20, message = "Last name must be 2-20 characters long") private String lastName; /** * Personal identification number for the customer according to the Swedish system. */ @NotNull(message = "Personal ID number must not be null") private String personalIdNumber; /** * Builder method for constructing a customer from relevant fields in a supplied CustomerRegistrationRequest for a * supplied user id * * @param userId the user id for which to create a customer entity * @param request request including all the relevant fields needed to make a customer entity * @return a new customer object based on the supplied user id and request object fields */ public static Customer toCustomer(UUID userId, CustomerRegistrationRequest request) { return Customer.builder() .userId(userId) .firstName(request.getFirstName()) .lastName(request.getLastName()) .personalIdNumber(request.getPersonalIdNumber()) .build(); } } <file_sep>package com.advertisementproject.zuulgateway.db.repositories; import com.advertisementproject.zuulgateway.db.entity.Permission; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.UUID; /** * Standard JPA Repository for getting and modifying permissions in the database */ @Repository public interface PermissionRepository extends JpaRepository<Permission, UUID> { } <file_sep>package com.advertisementproject.userservice.service; import com.advertisementproject.userservice.api.request.CompanyRegistrationRequest; import com.advertisementproject.userservice.api.request.CustomerRegistrationRequest; import com.advertisementproject.userservice.api.response.CompanyUserResponse; import com.advertisementproject.userservice.api.response.CustomerUserResponse; import com.advertisementproject.userservice.db.entity.Company; import com.advertisementproject.userservice.db.entity.Customer; import com.advertisementproject.userservice.db.entity.User; import com.advertisementproject.userservice.messagebroker.dto.EmailDetailsMessage; import com.advertisementproject.userservice.service.interfaces.RegistrationService; import com.advertisementproject.userservice.service.interfaces.UserService; import com.advertisementproject.userservice.service.interfaces.ValidationService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.UUID; /** * Registration Service implementation that registers customer users or company users, as well as retrieves email * details. This service enables registration controller to function. */ @Service @RequiredArgsConstructor public class RegistrationServiceImpl implements RegistrationService { /** * Service for managing CRUD operations for Users. */ private final UserService userService; /** * Service for validating customer/company users. */ private final ValidationService validationService; /** * Registers a customer user using the information supplied in the registration request. The user and customer object * are validated before saved in the database. * * @param registrationRequest request object with all information needed to register a customer user. * @return the newly registered customer user */ @Override @Transactional public CustomerUserResponse registerCustomer(CustomerRegistrationRequest registrationRequest) { userService.validateNotAlreadyRegistered(registrationRequest.getEmail()); User user = User.toUser(registrationRequest); validationService.validateUser(user); Customer customer = Customer.toCustomer(user.getId(), registrationRequest); validationService.validateCustomer(customer); return userService.saveCustomerUser(user, customer); } /** * Registers a company user using the information supplied in the registration request. The user and company object * are validated before saved in the database. * * @param registrationRequest request object with all information needed to register a company user. * @return the newly registered company user */ @Override @Transactional public CompanyUserResponse registerCompany(CompanyRegistrationRequest registrationRequest) { userService.validateNotAlreadyRegistered(registrationRequest.getEmail()); User user = User.toUser(registrationRequest); validationService.validateUser(user); Company company = Company.toCompany(user.getId(), registrationRequest); validationService.validateCompany(company); return userService.saveCompanyUser(user, company); } /** * Retrieves email details for a customer/company user with the supplied email * * @param email the email for which to retrieve email details * @return email details for the supplied email */ @Override public EmailDetailsMessage getEmailDetails(String email) { Object userInfo = userService.getFullUserInfoByEmail(email); UUID userId; String name; if (userInfo instanceof CustomerUserResponse) { CustomerUserResponse customerUser = (CustomerUserResponse) userInfo; userId = customerUser.getUser().getId(); name = customerUser.getCustomer().getFirstName() + " " + customerUser.getCustomer().getLastName(); } else if (userInfo instanceof CompanyUserResponse) { CompanyUserResponse companyUser = (CompanyUserResponse) userInfo; userId = companyUser.getUser().getId(); name = companyUser.getCompany().getName(); } else throw new IllegalStateException("Invalid user type"); return new EmailDetailsMessage(userId, name, email); } } <file_sep>package com.advertisementproject.campaignservice.db.entity; import com.advertisementproject.campaignservice.db.entity.view.View; import com.advertisementproject.campaignservice.request.CampaignRequest; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import javax.persistence.*; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.time.Instant; import java.time.Period; import java.util.Currency; import java.util.UUID; /** * Campaigns are the main responsibility of the Campaign Service application and contain information about the campaign * itself for advertising products or services to customers. Fields include validation. * Each campaign is tied to a company, which are updated when the application receives messages from the User Service * application. If a company is removed then all related campaigns are also removed. * * @JsonView restricts the response information shown to only the annotated fields if a controller has set a view. */ @Entity @Data @Builder @AllArgsConstructor @NoArgsConstructor public class Campaign { /** * Primary id for Campaign entity. */ @Id @NotNull @JsonView(value = {View.publicInfo.class}) private UUID id; /** * Title for the campaign. */ @NotNull @Size(min = 2, max = 20, message = "Title must be between 2-20 characters long") @JsonView(value = {View.publicInfo.class}) private String title; /** * Optional description for the campaign. */ @JsonView(value = {View.publicInfo.class}) private String description; /** * Discount which can either be a fixed amount or a percentage, determined by the field "isPercentage". */ @NotNull @Min(value = 1, message = "Discount must be at least 1 (percent or in currency)") @JsonView(value = {View.publicInfo.class}) private double discount; /** * Currency for the campaign. Currently is automatically set to SEK but is available as a field for future * market expansion which will prevent lots of potential issues from database migration. */ @JsonView(value = {View.publicInfo.class}) private Currency currency; /** * Determines whether field "discount" is a percentage (true) or a fixed amount (false). */ @NotNull @JsonProperty(value = "isPercentage") @JsonView(value = {View.publicInfo.class}) private boolean isPercentage; /** * Image file stored as a base64 formatted string (text type in the database). */ @Column(columnDefinition = "text") @JsonView(value = {View.publicInfo.class}) @Size(min = 1000, message = "Too short. Image must be in base64 string format") @Pattern(regexp = "^data:image/.*$", message = "image string must begin with 'data:image/' image descriptor") private String image; /** * Category that declares the type of campaign, for example "clothing" or "travel". */ @NotNull @Size(min = 2, max = 20, message = "Category must be between 2-20 characters long") @JsonView(value = {View.publicInfo.class}) private String category; /** * Timestamp for when the campaign is created. */ @Column(columnDefinition = "TIMESTAMP WITH TIME ZONE") @NotNull @JsonView(value = {View.publicInfo.class}) private Instant createdAt; /** * Timestamp for when the campaign is published. Can be set to publish immediately by not supplying a publishedAt * value in the request when creating a campaign. Must be a valid future date when explicitly set by a request. */ @Column(columnDefinition = "TIMESTAMP WITH TIME ZONE") @NotNull @JsonView(value = {View.publicInfo.class}) private Instant publishedAt; /** * Timestamp for when the campaign expires. Must be a later date than "publishAt" field if supplied in the request. * Set by default to 60 days after "publishAt" date if no value is set in the request. */ @Column(columnDefinition = "TIMESTAMP WITH TIME ZONE") @NotNull @JsonView(value = {View.publicInfo.class}) private Instant expiresAt; /** * Timestamp for when the campaign is updated. */ @Column(columnDefinition = "TIMESTAMP WITH TIME ZONE") @JsonView(value = {View.publicInfo.class}) private Instant updatedAt; /** * Field for quickly checking if a campaign is published without needing to check dates when fetching published * campaigns. Is set to true if current timestamp is after "publishAt", otherwise false. * There is a scheduled job that automatically sets campaigns to published if "publishAt" is in the past. */ @JsonProperty(value = "isPublished") @JsonView(value = {View.publicInfo.class}) private boolean isPublished; /** * Discount code to be used to partake in whatever offer the campaign is about and is hidden from users who are not * logged in. Logged in customers may fetch the discount code via a separate endpoint. */ @NotNull @Size(min = 2, max = 20, message = "Discount code must be between 2-20 characters long") private String discountCode; /** * The company that created the campaign and manages it. Company id is hidden from non logged in users. Company * table gets updated via messages from User Service application. */ @ManyToOne @OnDelete(action = OnDeleteAction.CASCADE) @JoinColumn(name = "company_id") @JsonView(value = {View.publicInfo.class}) private Company company; /** * Builder method for constructing a campaign from a company and a campaign request. * If publishedAt timestamp is provided in the request and it's a future timestamp then the campaign is set to be * published at that later time, otherwise it will be set to published with the current timestamp. * If expiredAt timestamp is provided in the request and it's at a later timestamp than the publishAt timestamp * then that expiredAt timestamp is set, otherwise expiredAt is set to 60 days after publishAt by default. * * @param company the company that created the campaign * @param request request object containing information for making the campaign * @return campaign with information provided from the request, belonging to the company provided */ public static Campaign toCampaign(Company company, CampaignRequest request) { Instant publishedAt; boolean isPublished = false; if (request.getPublishedAt() != null && request.getPublishedAt().isAfter(Instant.now())) { publishedAt = request.getPublishedAt(); } else { publishedAt = Instant.now(); isPublished = true; } Instant expiresAt = publishedAt.plus(Period.ofDays(60)); if (request.getExpiresAt() != null && request.getExpiresAt().isAfter(publishedAt)) { expiresAt = request.getExpiresAt(); } return Campaign.builder() .id(UUID.randomUUID()) .title(request.getTitle()) .description(request.getDescription()) .discount(request.getDiscount()) .currency(Currency.getInstance("SEK")) .isPercentage(request.getIsPercentage()) .image(request.getImage()) .category(request.getCategory()) .createdAt(Instant.now()) .publishedAt(publishedAt) .isPublished(isPublished) .expiresAt(expiresAt) .updatedAt(null) .discountCode(request.getDiscountCode()) .company(company) .build(); } } <file_sep>import React from "react"; import HeaderImage from "../Components/header/header.component"; const Email = () => ( <> <HeaderImage headerText="We sent you an email, verify to enable your account" /> </> ); export default Email; <file_sep>FROM node:12-alpine AS BUILD_IMAGE # couchbase sdk requirements RUN apk update && apk add yarn curl bash python g++ make && rm -rf /var/cache/apk/* # install node-prune (https://github.com/tj/node-prune) RUN curl -sfL https://install.goreleaser.com/github.com/tj/node-prune.sh | bash -s -- -b /usr/local/bin WORKDIR /usr/src/app COPY package.json yarn.lock ./ # install dependencies RUN yarn --frozen-lockfile COPY . . # lint & test # RUN yarn lint # build application RUN yarn build # remove development dependencies RUN npm prune --production # run node prune RUN /usr/local/bin/node-prune # remove unused dependencies RUN rm -rf node_modules/rxjs/src/ RUN rm -rf node_modules/rxjs/bundles/ RUN rm -rf node_modules/rxjs/_esm5/ RUN rm -rf node_modules/rxjs/_esm2015/ RUN rm -rf node_modules/swagger-ui-dist/*.map RUN rm -rf node_modules/couchbase/src/ FROM node:12-alpine WORKDIR /usr/src/app # copy from build image COPY --from=BUILD_IMAGE /usr/src/app/ . COPY --from=BUILD_IMAGE /usr/src/app/node_modules ./node_modules EXPOSE 3000 CMD [ "npm", "start" ]<file_sep># Microservices graduation project ## Developers: <NAME>, <NAME>, <NAME> # Documentation ### Swagger API Documentation If the project is up and running, Swagger API documentation for all services that have a controller can be viewed at: http://localhost:8080/swagger-ui/ ### Java Docs Javadocs can be found in the folder: ``` /documentation/javadocs ``` View javadocs by opening the file "index.html" in that folder. # Getting Started To download this project and make it runnable, you'll need to clone the repository from the root folder Create a new **folder** and **cd folderName** then run the following command: ``` git clone https://github.com/EliasMehr/Microservices-with-jwt.git ``` You can run the project more easily using docker compose as described in the next section. The project may also be run locally by creating an empty database for each application, entering environment variables and running RabbitMQ from a docker image with the following command: ``` docker run -d -p 5672:5672 -p 15672:15672 --name my-rabbit rabbitmq:3-management ``` ## Docker Compose To build the project run the following: ``` docker-compose build ``` To run docker compose, run the following: ``` docker-compose-up ``` ## Eureka dashboard To see that everything is running and all services has connected to the **eureka-server** Paste this URL into your web browser ``` http://localhost:8761/eureka ``` ## Frontend ***Company*** have access to a dashboard where the company can view, create, delete & edit their campaigns. ***Customer*** can view all published campaigns and retrieve the discount code. ``` http://localhost:3000 ``` If you get the message below during build time you have to navigate to frontend package and run `yarn install` ``` warning <DEPENDENCIE>: Package relocated. Please install and migrate to @<DEPENDENCIE>. error Your lockfile needs to be updated, but yarn was run with `--frozen-lockfile` ``` ## RabbitMQ dashboard You can inspect the RabbitMQ message broker by going to this address and logging in as 'guest' with the password ' <PASSWORD>': ``` http://localhost:15672/ ``` ## Zuul API Gateway Zuul gateway proxy will route all requests to concerned services, the gateway is JWT Authentication based and all requests requires a valid JWT token. The only exposed API endpoints that are non-auth required are the following: ``` http://localhost:8080/login ``` ``` http://localhost:8080/user/register/company http://localhost:8080/user/register/customer ``` ``` http://localhost:8080/campaign/all/published ``` ## Environment variables To add environment variables open .env file which is stored in the root folder of the project. If you're running on macOS you may need to store the variables on your computer so that docker-compose can read the variables. On macOS, run the following in your terminal to store variables: ``` export VARIABLE-NAME=VALUE ``` Then you can run the following in your terminal to verify that the variable has been stored successfully: ``` echo $VARIABLE-NAME ``` # Project Structure ![Project Structure](https://i.imgur.com/RCBCLYf.png) # Project Overview ![Project Overview](https://i.imgur.com/v6eIXzu.png) ## Eureka Server Eureka allows services to register so that Zuul Gateway may handle routing correctly. ## Zuul Gateway When running the project through docker compose, all applications are inside a closed docker network. Zuul Gateway application at port 8080 is responsible for routing and security. After a user is registered, they must confirm their email and then login. After a successful login, Zuul returns a jwt token along with the user role. The jwt token must be supplied as a Bearer token to any request that requires authentication. Zuul Gateway application supplies the currently logged in user id to the services. ## User Service Users may register as a company user or customer user and some details may differ, but most importantly the access rights are different. A company user may create and modify campaigns while a customer user may only view campaigns. User Service allows users to create, update and remove their account. User service informs other services about what happens to the user database so they can update relevant information in their own databases. ## Campaign Service Company users may create campaigns which customers will be able to view and get a discount code for. Published campaigns are open to view for the public, but login is required to access the discount code. Company users may create, update and delete campaigns, which may be set as immediately published or to be automatically published at a later date. ## Confirmation Token Service When a user registers, a confirmation token is created. This token is sent to email service. When a user clicks the link in their confirmation email, Confirmation Token Service confirms the token and informs other services that the user should be enabled and permissions should be created. ## Email Service Email Service awaits name and email from User Service as well as a token from Confirmation Token Service. Once all information has been received for a user id, a confirmation link email is sent to the newly registered user. ## Permissions Service When a user has confirmed their email, Permissions Service is notified and will create a permissions object for that user id. Zuul Gateway is informed so it may track permissions. ## Additional Information For more information, see the java docs for each service. <file_sep>package com.advertisementproject.confirmationtokenservice; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ConfirmationTokenServiceApplicationTests { @Test void contextLoads() { } } <file_sep>package com.advertisementproject.userservice.db.repository; import com.advertisementproject.userservice.db.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; import java.util.UUID; /** * Standard JPA Repository for doing CRUD operations for users in the database. Includes some custom queries to find * a user by email or to enable a specific user. */ public interface UserRepository extends JpaRepository<User, UUID> { /** * Retrieves an optional user by email * * @param email the email for which to retrieve an optional user * @return a user optional or an empty optional if the supplied email doesn't match any user in the database */ Optional<User> findByEmail(String email); /** * Sets enabled = true for a specific user * * @param userId the user id for which to set enabled = true */ @Transactional @Modifying @Query("UPDATE User user " + "SET user.enabled = TRUE " + "WHERE user.id = ?1") void enableUser(UUID userId); } <file_sep>FROM maven:3.6.3-openjdk-15-slim as jreBuilder RUN mkdir /usr/src/project COPY . /usr/src/project WORKDIR /usr/src/project RUN mvn package -DskipTests FROM adoptopenjdk/openjdk15:x86_64-alpine-jre-15.0.2_7 RUN mkdir /project COPY --from=jreBuilder /usr/src/project/target/zuulgateway-0.0.1-SNAPSHOT.jar /project/ WORKDIR /project CMD java -jar zuulgateway-0.0.1-SNAPSHOT.jar # FROM maven:3.6.3-openjdk-15-slim as jreBuilder # RUN jlink \ # --add-modules jdk.unsupported,java.sql,java.desktop,java.naming,java.management,java.instrument,java.security.jgss,java.rmi \ # --verbose \ # --strip-java-debug-attributes \ # --compress 2 \ # --no-header-files \ # --no-man-pages \ # --output /jre # FROM openjdk:15.0-slim # ARG JAR_FILE # COPY --from=jreBuilder /jre /usr/lib/jre # ENTRYPOINT ["/usr/lib/jre/bin/java", "-jar", "./app.jar"] # COPY ./target/${JAR_FILE} ./app.jar #FROM openjdk:15-jdk-slim as bulid # #WORKDIR application # #COPY mvnw . #COPY .mvn .mvn #COPY pom.xml . #COPY src src # #RUN --mount=type=cache,target=/root/.m2 ./mvnw install -DskipTests # #RUN cp /application/target/*.jar app.jar #RUN java -Djarmode=layertools -jar app.jar extract # #FROM openjdk:15-jdk-slim #WORKDIR application #COPY --from=bulid application/dependencies/ ./ #COPY --from=bulid application/spring-boot-loader/ ./ #COPY --from=bulid application/snapshot-dependencies/ ./ #COPY --from=bulid application/application/ ./ #ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]<file_sep>package com.advertisementproject.campaignservice.service; import com.advertisementproject.campaignservice.db.entity.Campaign; import com.advertisementproject.campaignservice.db.entity.Company; import com.advertisementproject.campaignservice.db.repository.CampaignRepository; import com.advertisementproject.campaignservice.exception.EntityNotFoundException; import com.advertisementproject.campaignservice.exception.UnauthorizedAccessException; import com.advertisementproject.campaignservice.request.CampaignRequest; import com.advertisementproject.campaignservice.service.interfaces.CampaignService; import com.advertisementproject.campaignservice.service.interfaces.ValidationService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.time.Instant; import java.time.Period; import java.util.List; import java.util.UUID; /** * Service implementation for Campaign Service to manage campaigns */ @Service @RequiredArgsConstructor public class CampaignServiceImpl implements CampaignService { /** * JPA Repository for Campaigns. */ private final CampaignRepository campaignRepository; /** * Service to validate Campaigns. */ private final ValidationService validationService; /** * Retrieves all campaigns for a specific company id * * @param companyId the company id for which to retrieve campaigns * @return list of companies related to the supplied company id */ @Override @Transactional public List<Campaign> getAllCampaignsByCompanyId(UUID companyId) { return campaignRepository.findAllByCompanyUserId(companyId); } /** * Deletes all campaigns for a specific company id * * @param companyId the company id for which to delete campaigns */ @Override @Transactional public void deleteAllCampaignsByCompanyId(UUID companyId) { campaignRepository.deleteByCompanyUserId(companyId); } /** * Retrieves a specific campaign * * @param campaignId the id of the campaign to retrieve * @param companyId the company id for the campaign. Used to verify that the company client has ownership of the * campaign in question * @return the requested campaign */ @Override @Transactional public Campaign getCampaignById(UUID campaignId, UUID companyId) { return getCampaignAndAuthorize(campaignId, companyId); } /** * Validates and creates a new campaign * * @param company the company that the campaign belongs to * @param campaignRequest information from which to generate the new campaign * @return the newly created campaign */ @Override @Transactional public Campaign createCampaign(Company company, CampaignRequest campaignRequest) { Campaign campaign = Campaign.toCampaign(company, campaignRequest); validationService.validateCampaign(campaign); campaignRepository.save(campaign); return campaign; } /** * Validates and updates a specific campaign * * @param campaignId the id of the campaign to be updated * @param companyId the company id for the campaign. Used to verify that the company client has ownership of the * campaign in question * @param campaignRequest information from which to update the campaign * @return the newly updated campaign */ @Override @Transactional public Campaign updateCampaignById(UUID campaignId, UUID companyId, CampaignRequest campaignRequest) { Campaign campaign = getCampaignAndAuthorize(campaignId, companyId); updateCampaignFields(campaign, campaignRequest); validationService.validateCampaign(campaign); campaignRepository.save(campaign); return campaign; } /** * Deletes a specific campaign * * @param campaignId the id of the campaign to delete * @param companyId the company id for the campaign. Used to verify that the company client has ownership of the */ @Override @Transactional public void deleteCampaignById(UUID campaignId, UUID companyId) { Campaign campaign = getCampaignAndAuthorize(campaignId, companyId); campaignRepository.delete(campaign); } /** * Retrieves the discount code for a specific campaign * * @param campaignId the id of the campaign to get the discount code from * @return the discount code for the campaign with the supplied campaign id * @throws EntityNotFoundException if the campaign is not found * @throws UnauthorizedAccessException if the campaign is not published for the requested discount code */ @Override public String getDiscountCode(UUID campaignId) { Campaign campaign = campaignRepository.findById(campaignId) .orElseThrow(() -> new EntityNotFoundException("Campaign not found for id: " + campaignId)); if (!campaign.isPublished()) { throw new UnauthorizedAccessException("Access to discountCode for unpublished campaigns is not allowed"); } return campaign.getDiscountCode(); } /** * Retrieves all campaigns * * @return list of all campaigns */ @Override @Transactional public List<Campaign> getAllCampaigns() { return campaignRepository.findAll(); } /** * Retrieves all published campaigns * * @return list of all published campaigns */ @Override @Transactional public List<Campaign> getAllPublishedCampaigns() { return campaignRepository.findAllByIsPublishedTrue(); } /** * Helper method to retrieve a campaign and verify that the supplied company id matches the company id of the * requested campaign. * * @param campaignId the id of the campaign to retrieve * @param companyId the company id to verify ownership * @return the requested campaign * @throws EntityNotFoundException if the campaign is not found. * @throws UnauthorizedAccessException if the supplied company id does not match the campaign's company id */ private Campaign getCampaignAndAuthorize(UUID campaignId, UUID companyId) { Campaign campaign = campaignRepository.findById(campaignId) .orElseThrow(() -> new EntityNotFoundException("Campaign not found for id: " + campaignId)); if (!campaign.getCompany().getUserId().equals(companyId)) { throw new UnauthorizedAccessException("Unauthorized access not allowed"); } return campaign; } /** * Helper method to update a campaign. Updates not null fields in the supplied request. * Campaigns may be set to be published immediately or set to be published at a later time. The timestamp fields * publishedAt and expiredAt are validated here, but the other fields must still be validated. * * @param campaign the campaign to update * @param request request object containing fields to update in the supplied campaign */ private void updateCampaignFields(Campaign campaign, CampaignRequest request) { if (request.getTitle() != null) { campaign.setTitle(request.getTitle()); } if (request.getDescription() != null) { campaign.setDescription(request.getDescription()); } if (request.getDiscount() != null) { campaign.setDiscount(request.getDiscount()); } if (request.getIsPercentage() != null) { campaign.setPercentage(request.getIsPercentage()); } if (request.getImage() != null) { campaign.setImage(request.getImage()); } if (request.getCategory() != null) { campaign.setCategory(request.getCategory()); } if (!campaign.isPublished() && request.isPublishNow()) { campaign.setPublished(true); campaign.setPublishedAt(Instant.now()); } if (request.getPublishedAt() != null && request.getPublishedAt().isAfter(Instant.now().plus(Period.ofDays(1)))) { campaign.setPublished(false); campaign.setPublishedAt(request.getPublishedAt()); } if (request.getExpiresAt() != null && request.getExpiresAt().isAfter(campaign.getPublishedAt())) { campaign.setExpiresAt(request.getExpiresAt()); } if (request.getDiscountCode() != null) { campaign.setDiscountCode(request.getDiscountCode()); } campaign.setUpdatedAt(Instant.now()); } } <file_sep>import React from "react"; import { UserReducer } from "../reducers/UserReducer"; export const UserContext = React.createContext(); const initialState = { isLoggedIn: false, role: "", }; export const UserProvider = (props) => { const [user, userDispatch] = React.useReducer(UserReducer, initialState); return ( <UserContext.Provider value={[user, userDispatch]}> {props.children} </UserContext.Provider> ); }; <file_sep>package com.advertisementproject.permissionservice.db.repository; import com.advertisementproject.permissionservice.db.entity.Permission; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.UUID; /** * Standard JPA Repository for getting and modifying permissions in the database */ @Repository public interface PermissionRepository extends JpaRepository<Permission, UUID> { }<file_sep>import { Edit } from "react-admin"; import EditForm from "./editForm"; import React from "react"; export const CampaignEdit = (props) => { const transform = async (data) => { if (!data.image) { return { ...data, }; } if(data.image) { const promiseImgToBase64 = await readFileAsDataURL(data.image); console.log(promiseImgToBase64); if (promiseImgToBase64) { return { ...data, image: promiseImgToBase64, }; } } }; async function readFileAsDataURL(file) { let result_base64 = await new Promise((resolve) => { if(typeof file === "string") { return resolve(file); } const fileReader = new FileReader(); fileReader.onload = (e) => resolve(fileReader.result); fileReader.readAsDataURL(file.rawFile); }); return result_base64; } return ( <Edit {...props} transform={transform}> <EditForm redirect="list" /> </Edit> ); }; <file_sep>package com.advertisementproject.userservice.messagebroker.publisher; import com.advertisementproject.userservice.db.entity.Company; import com.advertisementproject.userservice.db.entity.User; import com.advertisementproject.userservice.messagebroker.dto.EmailDetailsMessage; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.stereotype.Service; import java.util.UUID; /** * MessagePublisher is a service for publishing messages asynchronously to other microservices via RabbitMQ. * RabbitTemplate is used to send the message and ObjectMapper is used to convert objects to JSON */ @Slf4j @Service @RequiredArgsConstructor public class MessagePublisher { /** * Used for sending messages to other microservices via RabbitMQ message broker. */ private final RabbitTemplate rabbitTemplate; /** * Sends a message including a user id to a fanout exchange with the name "user.delete" which informs other * microservices that they should delete any information related to that user id. * * @param userId the user id to be sent to "user.delete" fanout exchange */ public void sendUserDeleteMessage(UUID userId) { rabbitTemplate.convertAndSend("user.delete", "", userId); } /** * Sends a message including a user id to a direct messaging queue with the supplied name which informs another * microservice that they should do something related to that user id. * * @param queueName the name of the queue to send a user id to * @param userId the user id to be sent */ public void sendUserIdMessage(String queueName, UUID userId) { log.info("[MESSAGE BROKER] Sending userId to " + queueName + ": " + userId); rabbitTemplate.convertAndSend(queueName, userId); } /** * Sends a message including email details to a direct messaging queue "emailDetails" which informs the Email * Service application that an email should be sent using the email details in the message. * * @param message email details message to be sent to Email Service application. */ public void sendEmailDetailsMessage(EmailDetailsMessage message) { String queueName = "emailDetails"; String messageString = null; try { messageString = new ObjectMapper().writeValueAsString(message); } catch (JsonProcessingException e) { e.printStackTrace(); } log.info("[MESSAGE BROKER] Sending message to " + queueName + ": " + messageString); rabbitTemplate.convertAndSend(queueName, messageString); } /** * Sends a message including a user object to a fanout exchange with the name "user" which informs other * microservices that a user has been added/updated and they should update their copy of the user table. * * @param user the user to be sent to "user" fanout exchange */ public void sendUserMessage(User user) { String exchangeName = "user"; String companyString = null; try { companyString = new ObjectMapper().writeValueAsString(user); } catch (JsonProcessingException e) { e.printStackTrace(); } log.info("[MESSAGE BROKER] Sending user info to exchange " + exchangeName + ": " + companyString); rabbitTemplate.convertAndSend(exchangeName, "", companyString); } /** * Sends a message including a company object to a fanout exchange with the name "company" which informs other * microservices that a company has been added/updated and they should update their copy of the company table. * * @param company the company to be sent to "company" fanout exchange */ public void sendCompanyMessage(Company company) { String exchangeName = "company"; String companyString = null; try { companyString = new ObjectMapper().writeValueAsString(company); } catch (JsonProcessingException e) { e.printStackTrace(); } log.info("[MESSAGE BROKER] Sending company info to exchange " + exchangeName + ": " + companyString); rabbitTemplate.convertAndSend(exchangeName, "", companyString); } } <file_sep>package com.advertisementproject.campaignservice.exception.response; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.ToString; import org.springframework.http.HttpStatus; import java.util.List; /** * Api Error report object that shows an error report to the client. Only includes errors in JSON if not null. */ @AllArgsConstructor @Getter @Builder @ToString public class ApiError { /** * The error status of the exception. */ private final HttpStatus status; /** * The error message for the exception. */ private final String message; /** * Timestamp for when the exception occurred. */ private final String timestamp; /** * List of sub-errors such as field errors. Only shown in JSON if not null. */ @JsonInclude(JsonInclude.Include.NON_NULL) private final List<String> errors; } <file_sep>package com.advertisementproject.zuulgateway.api; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; /** * Controller for a user to view the their logged in security status from the security context holder */ @RequiredArgsConstructor @RestController public class MeController { /** * Lets a logged in user see the security principal that they are logged in with. Includes user information. * * @return principal from the security context holder */ @GetMapping("/me") public ResponseEntity<?> me() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return ResponseEntity.ok(principal); } } <file_sep>package com.advertisementproject.zuulgateway.security.model; import com.advertisementproject.zuulgateway.db.entity.User; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.Collections; /** * Custom implementation of user details including a user object and whether the user is enabled and has permissions. */ @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class UserDetailsImpl implements UserDetails { /** * User object including user account details such as user id, email etc. */ private User user; /** * Whether the user has permission (true) or not (false) to use the system. Can be revoked by an admin user if there * is suspicious activity, thereby indirectly invalidating any jwt token connected to the user. */ private boolean hasPermission; /** * Gets a singleton list of the user's role as a granted authority * * @return a singleton list of the user's role as a granted authority */ @Override public Collection<? extends GrantedAuthority> getAuthorities() { SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(user.getRole().name()); return Collections.singletonList(simpleGrantedAuthority); } /** * Gets the hashed password for the user * * @return the hashed password for the user */ @Override public String getPassword() { return user.getHashedPassword(); } /** * Gets the username (email) for the user * * @return the username (email) for the user */ @Override public String getUsername() { return user.getEmail(); } /** * Gets a true or false value for whether the account is non-expired * * @return always true, since we don't have expiration dates on accounts */ @Override public boolean isAccountNonExpired() { return true; } /** * Gets a true or false value for whether the account is non-locked, determined in our case by whether the user * has valid permissions * * @return true if the user has valid permissions, otherwise false */ @Override public boolean isAccountNonLocked() { return hasPermission; } /** * Gets a true or false value for whether the credentials are non-expired * * @return always true, since we don't have expiration dates on credentials */ @Override public boolean isCredentialsNonExpired() { return true; } /** * Gets a true or false value for whether the user is enabled * * @return true if the user is enabled, otherwise false */ @Override public boolean isEnabled() { return user.isEnabled(); } }<file_sep>import axios from "axios"; import headerRequest from "../utils/headerRequest"; const campaignService = { getAllPublishedCampaigns, getDiscountCode, getAllCompanyCampaigns, }; function getAllPublishedCampaigns() { return axios .get("http://localhost:8080/campaign/all/published") .then((res) => res.data) .catch((err) => { console.log("ERROR"); return err; }); } function getDiscountCode(campaignId) { console.log("in discount code " + new headerRequest().Authorization); return axios .get("http://localhost:8080/campaign/discount-code/" + campaignId, { headers: headerRequest(), }) .then((res) => res.data) .catch((err) => { console.log("ERROR" + err); }); } function getAllCompanyCampaigns() { return axios.get("http://localhost:8080/campaign", { headers: headerRequest(), }); } export default campaignService; <file_sep><!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (15) on Thu Feb 11 17:22:46 CET 2021 --> <title>H-Index</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="dc.created" content="2021-02-11"> <meta name="description" content="index: H"> <meta name="generator" content="javadoc/SplitIndexWriter"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../script-dir/jquery-ui.min.css" title="Style"> <link rel="stylesheet" type="text/css" href="../jquery-ui.overrides.css" title="Style"> <script type="text/javascript" src="../script.js"></script> <script type="text/javascript" src="../script-dir/jquery-3.5.1.min.js"></script> <script type="text/javascript" src="../script-dir/jquery-ui.min.js"></script> </head> <body class="split-index-page"> <script type="text/javascript">var pathtoroot = "../"; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="flex-box"> <header role="banner" class="flex-header"> <nav role="navigation"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="top-nav" id="navbar.top"> <div class="skip-nav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <ul id="navbar.top.firstrow" class="nav-list" title="Navigation"> <li><a href="../index.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="nav-bar-cell1-rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="sub-nav"> <div class="nav-list-search"><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </div> </div> <!-- ========= END OF TOP NAVBAR ========= --> <span class="skip-nav" id="skip.navbar.top"> <!-- --> </span></nav> </header> <div class="flex-content"> <main role="main"> <div class="header"> <h1>Index</h1> </div> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">J</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">Z</a>&nbsp;<br><a href="../allclasses-index.html">All&nbsp;Classes</a><span class="vertical-separator">|</span><a href="../allpackages-index.html">All&nbsp;Packages</a> <h2 class="title" id="I:H">H</h2> <dl class="index"> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html#handleBadRequest(java.lang.Exception)">handleBadRequest(Exception)</a></span> - Method in class com.advertisementproject.campaignservice.exception.handler.<a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.campaignservice.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing illegal argument exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/confirmationtokenservice/exception/handler/CustomRestExceptionHandler.html#handleConfirmationTokenException(com.advertisementproject.confirmationtokenservice.exception.ConfirmationTokenException)">handleConfirmationTokenException(ConfirmationTokenException)</a></span> - Method in class com.advertisementproject.confirmationtokenservice.exception.handler.<a href="../com/advertisementproject/confirmationtokenservice/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.confirmationtokenservice.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles confirmation token related exceptions</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html#handleConflictError(java.lang.Exception)">handleConflictError(Exception)</a></span> - Method in class com.advertisementproject.userservice.api.exception.handler.<a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.userservice.api.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing email already registered exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html#handleConstraintViolation(javax.validation.ConstraintViolationException)">handleConstraintViolation(ConstraintViolationException)</a></span> - Method in class com.advertisementproject.campaignservice.exception.handler.<a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.campaignservice.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing constraint violation exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html#handleConstraintViolation(javax.validation.ConstraintViolationException)">handleConstraintViolation(ConstraintViolationException)</a></span> - Method in class com.advertisementproject.userservice.api.exception.handler.<a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.userservice.api.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing constraint violation exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html#handleCustomBadRequestException(java.lang.Exception)">handleCustomBadRequestException(Exception)</a></span> - Method in class com.advertisementproject.userservice.api.exception.handler.<a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.userservice.api.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing bad request exceptions related to personal id number or organization number to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html#handleForbiddenAccessException(java.lang.Exception)">handleForbiddenAccessException(Exception)</a></span> - Method in class com.advertisementproject.campaignservice.exception.handler.<a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.campaignservice.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing forbidden access exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html#handleInternalServerError(java.lang.Exception)">handleInternalServerError(Exception)</a></span> - Method in class com.advertisementproject.campaignservice.exception.handler.<a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.campaignservice.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing internal server error exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html#handleInternalServerError(java.lang.Exception)">handleInternalServerError(Exception)</a></span> - Method in class com.advertisementproject.userservice.api.exception.handler.<a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.userservice.api.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing internal server exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html#handleMethodArgumentNotValid(org.springframework.web.bind.MethodArgumentNotValidException,org.springframework.http.HttpHeaders,org.springframework.http.HttpStatus,org.springframework.web.context.request.WebRequest)">handleMethodArgumentNotValid(MethodArgumentNotValidException, HttpHeaders, HttpStatus, WebRequest)</a></span> - Method in class com.advertisementproject.campaignservice.exception.handler.<a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.campaignservice.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing invalid method argument exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html#handleMethodArgumentNotValid(org.springframework.web.bind.MethodArgumentNotValidException,org.springframework.http.HttpHeaders,org.springframework.http.HttpStatus,org.springframework.web.context.request.WebRequest)">handleMethodArgumentNotValid(MethodArgumentNotValidException, HttpHeaders, HttpStatus, WebRequest)</a></span> - Method in class com.advertisementproject.userservice.api.exception.handler.<a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.userservice.api.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing invalid method argument exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html#handleNotFoundException(java.lang.Exception)">handleNotFoundException(Exception)</a></span> - Method in class com.advertisementproject.campaignservice.exception.handler.<a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.campaignservice.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing not found exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/permissionservice/exception/handler/CustomRestExceptionHandler.html#handleNotFoundException(java.lang.Exception)">handleNotFoundException(Exception)</a></span> - Method in class com.advertisementproject.permissionservice.exception.handler.<a href="../com/advertisementproject/permissionservice/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.permissionservice.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles exception reporting for PermissionNotFoundException with status 404 Not Found</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html#handleNotFoundException(java.lang.Exception)">handleNotFoundException(Exception)</a></span> - Method in class com.advertisementproject.userservice.api.exception.handler.<a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.userservice.api.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing user not found exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html#handleTypeMismatch(org.springframework.beans.TypeMismatchException,org.springframework.http.HttpHeaders,org.springframework.http.HttpStatus,org.springframework.web.context.request.WebRequest)">handleTypeMismatch(TypeMismatchException, HttpHeaders, HttpStatus, WebRequest)</a></span> - Method in class com.advertisementproject.campaignservice.exception.handler.<a href="../com/advertisementproject/campaignservice/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.campaignservice.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing invalid type mismatch exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html#handleTypeMismatch(org.springframework.beans.TypeMismatchException,org.springframework.http.HttpHeaders,org.springframework.http.HttpStatus,org.springframework.web.context.request.WebRequest)">handleTypeMismatch(TypeMismatchException, HttpHeaders, HttpStatus, WebRequest)</a></span> - Method in class com.advertisementproject.userservice.api.exception.handler.<a href="../com/advertisementproject/userservice/api/exception/handler/CustomRestExceptionHandler.html" title="class in com.advertisementproject.userservice.api.exception.handler">CustomRestExceptionHandler</a></dt> <dd> <div class="block">Handles showing invalid type mismatch exceptions to the client</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/db/entity/User.html#hashedPassword">hashedPassword</a></span> - Variable in class com.advertisementproject.userservice.db.entity.<a href="../com/advertisementproject/userservice/db/entity/User.html" title="class in com.advertisementproject.userservice.db.entity">User</a></dt> <dd> <div class="block">Hashed password from the raw password the user submitted upon registration.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/zuulgateway/db/entity/User.html#hashedPassword">hashedPassword</a></span> - Variable in class com.advertisementproject.zuulgateway.db.entity.<a href="../com/advertisementproject/zuulgateway/db/entity/User.html" title="class in com.advertisementproject.zuulgateway.db.entity">User</a></dt> <dd> <div class="block">Hashed password from the raw password the user submitted upon registration.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/permissionservice/db/entity/Permission.html#hasPermission">hasPermission</a></span> - Variable in class com.advertisementproject.permissionservice.db.entity.<a href="../com/advertisementproject/permissionservice/db/entity/Permission.html" title="class in com.advertisementproject.permissionservice.db.entity">Permission</a></dt> <dd> <div class="block">Whether the user has permission to use the system.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/permissionservice/request/UpdatePermissionRequest.html#hasPermission">hasPermission</a></span> - Variable in class com.advertisementproject.permissionservice.request.<a href="../com/advertisementproject/permissionservice/request/UpdatePermissionRequest.html" title="class in com.advertisementproject.permissionservice.request">UpdatePermissionRequest</a></dt> <dd> <div class="block">Whether the user should have permission.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/zuulgateway/db/entity/Permission.html#hasPermission">hasPermission</a></span> - Variable in class com.advertisementproject.zuulgateway.db.entity.<a href="../com/advertisementproject/zuulgateway/db/entity/Permission.html" title="class in com.advertisementproject.zuulgateway.db.entity">Permission</a></dt> <dd> <div class="block">Whether the user has permission to use the system.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/zuulgateway/security/model/UserDetailsImpl.html#hasPermission">hasPermission</a></span> - Variable in class com.advertisementproject.zuulgateway.security.model.<a href="../com/advertisementproject/zuulgateway/security/model/UserDetailsImpl.html" title="class in com.advertisementproject.zuulgateway.security.model">UserDetailsImpl</a></dt> <dd> <div class="block">Whether the user has permission (true) or not (false) to use the system.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/ValidationServiceImpl.html#hasValidControlNumber(java.lang.String)">hasValidControlNumber(String)</a></span> - Static method in class com.advertisementproject.userservice.service.<a href="../com/advertisementproject/userservice/service/ValidationServiceImpl.html" title="class in com.advertisementproject.userservice.service">ValidationServiceImpl</a></dt> <dd> <div class="block">Helper method to check if a personal id number or organization number has a correct control number according to the luhn algorithm.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/ValidationServiceImpl.html#hasValidThirdDigit(java.lang.String)">hasValidThirdDigit(String)</a></span> - Static method in class com.advertisementproject.userservice.service.<a href="../com/advertisementproject/userservice/service/ValidationServiceImpl.html" title="class in com.advertisementproject.userservice.service">ValidationServiceImpl</a></dt> <dd> <div class="block">Helper method to check if the third digit of a organization number is 2 or higher to differentiate from a personal id number.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/db/entity/type/CompanyType.html#HEALTH">HEALTH</a></span> - com.advertisementproject.campaignservice.db.entity.type.<a href="../com/advertisementproject/campaignservice/db/entity/type/CompanyType.html" title="enum in com.advertisementproject.campaignservice.db.entity.type">CompanyType</a></dt> <dd> <div class="block">The company is in the health industry</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/db/entity/types/CompanyType.html#HEALTH">HEALTH</a></span> - com.advertisementproject.userservice.db.entity.types.<a href="../com/advertisementproject/userservice/db/entity/types/CompanyType.html" title="enum in com.advertisementproject.userservice.db.entity.types">CompanyType</a></dt> <dd> <div class="block">The company is in the health industry</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/db/config/DataSourceConfig.html#hikariDataSource()">hikariDataSource()</a></span> - Method in class com.advertisementproject.campaignservice.db.config.<a href="../com/advertisementproject/campaignservice/db/config/DataSourceConfig.html" title="class in com.advertisementproject.campaignservice.db.config">DataSourceConfig</a></dt> <dd> <div class="block">HikariDataSource configuration bean.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/confirmationtokenservice/db/config/DataSourceConfig.html#hikariDataSource()">hikariDataSource()</a></span> - Method in class com.advertisementproject.confirmationtokenservice.db.config.<a href="../com/advertisementproject/confirmationtokenservice/db/config/DataSourceConfig.html" title="class in com.advertisementproject.confirmationtokenservice.db.config">DataSourceConfig</a></dt> <dd> <div class="block">HikariDataSource configuration bean.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/emailservice/db/config/DataSourceConfig.html#hikariDataSource()">hikariDataSource()</a></span> - Method in class com.advertisementproject.emailservice.db.config.<a href="../com/advertisementproject/emailservice/db/config/DataSourceConfig.html" title="class in com.advertisementproject.emailservice.db.config">DataSourceConfig</a></dt> <dd> <div class="block">HikariDataSource configuration bean.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/permissionservice/db/config/DataSourceConfig.html#hikariDataSource()">hikariDataSource()</a></span> - Method in class com.advertisementproject.permissionservice.db.config.<a href="../com/advertisementproject/permissionservice/db/config/DataSourceConfig.html" title="class in com.advertisementproject.permissionservice.db.config">DataSourceConfig</a></dt> <dd> <div class="block">HikariDataSource configuration bean.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/db/config/DataSourceConfig.html#hikariDataSource()">hikariDataSource()</a></span> - Method in class com.advertisementproject.userservice.db.config.<a href="../com/advertisementproject/userservice/db/config/DataSourceConfig.html" title="class in com.advertisementproject.userservice.db.config">DataSourceConfig</a></dt> <dd> <div class="block">HikariDataSource configuration bean.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/zuulgateway/db/config/DataSourceConfig.html#hikariDataSource()">hikariDataSource()</a></span> - Method in class com.advertisementproject.zuulgateway.db.config.<a href="../com/advertisementproject/zuulgateway/db/config/DataSourceConfig.html" title="class in com.advertisementproject.zuulgateway.db.config">DataSourceConfig</a></dt> <dd> <div class="block">HikariDataSource configuration bean.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/confirmationtokenservice/exception/ConfirmationTokenException.html#httpStatus">httpStatus</a></span> - Variable in exception com.advertisementproject.confirmationtokenservice.exception.<a href="../com/advertisementproject/confirmationtokenservice/exception/ConfirmationTokenException.html" title="class in com.advertisementproject.confirmationtokenservice.exception">ConfirmationTokenException</a></dt> <dd> <div class="block">Error status for the exception</div> </dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">J</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">Z</a>&nbsp;<br><a href="../allclasses-index.html">All&nbsp;Classes</a><span class="vertical-separator">|</span><a href="../allpackages-index.html">All&nbsp;Packages</a></main> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottom-nav" id="navbar.bottom"> <div class="skip-nav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <ul id="navbar.bottom.firstrow" class="nav-list" title="Navigation"> <li><a href="../index.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="nav-bar-cell1-rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <span class="skip-nav" id="skip.navbar.bottom"> <!-- --> </span></nav> </footer> </div> </div> </body> </html> <file_sep>package com.advertisementproject.campaignservice.db.repository; import com.advertisementproject.campaignservice.db.entity.Campaign; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.UUID; /** * Repository for managing the campaign table in the database. Includes some custom methods beyond typical CRUD. */ @Repository public interface CampaignRepository extends JpaRepository<Campaign, UUID> { /** * Retrieve all campaigns from the database for a specific company id * * @param companyId the company id to retrieve campaigns from * @return list of campaigns with the supplied company id */ List<Campaign> findAllByCompanyUserId(UUID companyId); /** * Deletes all campaigns with the supplied company id * * @param companyId the company id for which to delete campaigns */ void deleteByCompanyUserId(UUID companyId); /** * Retrieve all campaigns that are published, in other words where isPublished == true * * @return list of all published campaigns */ List<Campaign> findAllByIsPublishedTrue(); /** * Sets isPublished = true for campaigns that have a publishedAt timestamp in the past and that are not already set * to published. This is run as a scheduled job in ScheduledJobsService. * * @param instant a timestamp for which to compare the publishedAt timestamp. Normally set to Instant.now() * @return the number of campaigns that were set to published */ @Transactional @Modifying @Query("UPDATE Campaign campaign SET campaign.isPublished = true WHERE campaign.isPublished = false AND campaign.publishedAt < ?1") int publishScheduledCampaigns(Instant instant); /** * Removes all campaigns that have a expiredAt timestamp in the past. This is run as a scheduled job in * ScheduledJobsService. * * @param instant a timestamp for which to compare the expiredAt timestamp. Normally set to Instant.now() * @return the number of expired campaigns that were removed */ @Transactional @Modifying @Query("DELETE FROM Campaign campaign WHERE campaign.expiresAt < ?1") int removeExpiredCampaigns(Instant instant); } <file_sep>package com.advertisementproject.userservice.utilities; public class TestDataSource { } <file_sep>package com.advertisementproject.campaignservice.service.interfaces; import com.advertisementproject.campaignservice.db.entity.Campaign; import org.springframework.web.bind.annotation.RequestBody; import javax.validation.Valid; /** * Validates Entities */ public interface ValidationService { /** * Validates that a campaign has all fields valid * * @param campaign the campaign to be validated */ void validateCampaign(@Valid @RequestBody Campaign campaign); } <file_sep>package com.advertisementproject.zuulgateway.api.exceptions; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.ToString; /** * Error report object for showing exceptions to the client */ @AllArgsConstructor @Getter @Builder @ToString public class ApiError { /** * Error status code for the exception. */ private final int statusCode; /** * Timestamp for when the error occurred. */ private final String timestamp; /** * The error message for the exception. */ private final String message; } <file_sep>import CopyRight from "../copyright/copyright.component"; export const Footer = () => { return ( <div> <CopyRight/> </div> ); }; export default Footer;<file_sep>package com.advertisementproject.confirmationtokenservice.service; import com.advertisementproject.confirmationtokenservice.db.entity.ConfirmationToken; import com.advertisementproject.confirmationtokenservice.db.repository.ConfirmationTokenRepository; import com.advertisementproject.confirmationtokenservice.exception.ConfirmationTokenException; import com.advertisementproject.confirmationtokenservice.service.interfaces.ConfirmationTokenService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.UUID; /** * Service implementation for managing confirmation tokens in the database */ @Slf4j @Service @AllArgsConstructor public class ConfirmationTokenServiceImpl implements ConfirmationTokenService { /** * JPA Repository for confirmation tokens. */ private final ConfirmationTokenRepository confirmationTokenRepository; /** * Generates and saves a confirmation token object in the database for a supplied user id, then returns token string * * @param userId the user id for which to create and save a confirmation token. * @return the token string for the generated confirmation token. */ @Override public String generateAndSaveToken(UUID userId) { ConfirmationToken confirmationToken = ConfirmationToken.toConfirmationToken(userId); confirmationTokenRepository.save(confirmationToken); log.info("New Confirmation token saved for userId: " + userId); return confirmationToken.getToken(); } /** * Finds a confirmation token based on token string, sets the token to confirmed and retrieves user id. * * @param token the token string for the confirmation token to set to confirmed * @return the user id of the newly confirmed token * @throws ConfirmationTokenException if confirmation token is not found, token has expired or the user id already * has a confirmed token */ @Override @Transactional public UUID confirmTokenAndGetUserId(String token) { ConfirmationToken confirmationToken = getTokenFromDatabase(token); validateNoTokenConfirmedForUserId(confirmationToken.getUserId()); validateTokenNotExpired(confirmationToken); confirmationTokenRepository.updateConfirmedAt(confirmationToken.getToken(), LocalDateTime.now()); return confirmationToken.getUserId(); } /** * Deletes all tokens for the supplied user id * * @param userId the user id for which to delete all confirmation tokens */ @Override public void deleteAllConfirmationTokensByUserId(UUID userId) { confirmationTokenRepository.deleteAllByUserId(userId); log.info("Confirmation tokens deleted for userId: " + userId); } /** * Helper method to retrieve confirmation token from database * * @param token the token string for which to retrieve a confirmation token object * @return the confirmation token for the supplied token string * @throws ConfirmationTokenException with status NOT_FOUND if token is not found */ private ConfirmationToken getTokenFromDatabase(String token) { return confirmationTokenRepository.findByToken(token) .orElseThrow(() -> new ConfirmationTokenException("Token not found in database", HttpStatus.NOT_FOUND)); } /** * Helper method to validate that the user doesn't have any confirmed tokens already * * @param userId the user id for which to validate that no tokens have been confirmed * @throws ConfirmationTokenException with status CONFLICT if any confirmed token is found for the supplied user id */ private void validateNoTokenConfirmedForUserId(UUID userId) { if (!confirmationTokenRepository.findConfirmationTokenByConfirmedAtNotNullAndUserId(userId).isEmpty()) { throw new ConfirmationTokenException("Email is already confirmed", HttpStatus.CONFLICT); } } /** * Helper method to validate that a token is not expired * * @param confirmationToken the confirmation token to validate not expired * @throws ConfirmationTokenException with status GONE if token is not valid */ private void validateTokenNotExpired(ConfirmationToken confirmationToken) { if (confirmationToken.getExpiresAt().isBefore(LocalDateTime.now())) { throw new ConfirmationTokenException("Token is expired", HttpStatus.GONE); } } } <file_sep>package com.advertisementproject.campaignservice; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class CampaignServiceApplicationTests { @Test void contextLoads() { } } <file_sep>package com.advertisementproject.eurekaserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; /** * Eureka Server Application is an application that relies on spring-cloud-starter-netflix-eureka-server as a * dependency. With the annotation @EnableEurekaServer and some configuration in application.yml, the application has * all it needs to act as a Eureka server. This means that this application will register and keep track of all our * microservices assuming they connect with this application. * * @author <NAME>, <NAME>, <NAME> */ @EnableEurekaServer @SpringBootApplication public class EurekaServerApplication { /** * Runs the application * * @param args optional command line arguments that are currently not implemented */ public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } } <file_sep>package com.advertisementproject.zuulgateway.security.filters; import com.advertisementproject.zuulgateway.security.model.UserDetailsImpl; import com.advertisementproject.zuulgateway.security.Utils.JwtUtils; import com.advertisementproject.zuulgateway.services.UserDetailsServiceImpl; import io.jsonwebtoken.JwtException; import lombok.RequiredArgsConstructor; import org.springframework.lang.NonNull; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.UUID; import static com.advertisementproject.zuulgateway.security.Utils.ServletResponseUtility.sendErrorResponse; import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; /** * A once per request filter that verifies that the user id from the jwt token in the Authorization header is a valid * user that is enabled, has permissions and allows the ant matchers in WebSecurityConfiguration to verify the user's * role. Creates a UsernamePasswordAuthenticationToken that is set in the SecurityContextHolder with details from the * request. Sends error response if something fails authentication via ServletResponseUtility. */ @Component @RequiredArgsConstructor public class JwtTokenValidationFilter extends OncePerRequestFilter { /** * Service that handles JWT related tasks such as extracting the subject from a JWT token. */ private final JwtUtils jwtUtils; /** * Service for managing user details, which is checked to see that a user exists, is enabled and has appropriate * permission. */ private final UserDetailsServiceImpl userDetailsService; /** * Runs the filter, verifying that the user id from the jwt token in the Authorization header is a valid * user that is enabled, has permissions and allows the ant matchers in WebSecurityConfiguration to verify the user's * role. Creates a UsernamePasswordAuthenticationToken that is set in the SecurityContextHolder with details from the * request. Sends error response if something fails authentication via ServletResponseUtility. * * @param request the request to be filtered * @param response the response to be sent * @param filterChain the chain of filters to be continued * @throws ServletException if an servlet related exception occurs * @throws IOException if data reading/writing fails */ @Override protected void doFilterInternal(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException { String authorizationHeader = request.getHeader("Authorization"); if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) { filterChain.doFilter(request, response); return; } String token = authorizationHeader.replace("Bearer ", ""); try { String userId = jwtUtils.extractSubject(token); UserDetailsImpl userDetails = userDetailsService.loadUserById(UUID.fromString(userId)); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } catch (JwtException | UsernameNotFoundException e) { sendErrorResponse(response, e.getMessage(), SC_UNAUTHORIZED); return; } filterChain.doFilter(request, response); } } <file_sep>package com.advertisementproject.campaignservice.service.interfaces; import com.advertisementproject.campaignservice.db.entity.Campaign; import com.advertisementproject.campaignservice.db.entity.Company; import com.advertisementproject.campaignservice.request.CampaignRequest; import java.util.List; import java.util.UUID; /** * Service for managing campaigns in the database with CRUD operations and enabling the controller endpoints to work. */ public interface CampaignService { /** * Retrieves all campaigns * * @return list of all campaigns */ List<Campaign> getAllCampaigns(); /** * Retrieves all published campaigns * * @return list of all campaigns that are published */ List<Campaign> getAllPublishedCampaigns(); /** * Retrieves all campaigns for a specific company id * * @param companyId the company id for which to retrieve campaigns * @return list of all campaigns related to the supplied company id */ List<Campaign> getAllCampaignsByCompanyId(UUID companyId); /** * Deletes all campaigns for a specific company id * * @param companyId the company id for which to delete campaigns */ void deleteAllCampaignsByCompanyId(UUID companyId); /** * Retrieves a specific campaign * * @param campaignId the id of the campaign to retrieve * @param companyId the company id for the campaign. Used to verify that the company client has ownership of the * campaign in question * @return the requested campaign */ Campaign getCampaignById(UUID campaignId, UUID companyId); /** * Creates a new campaign and saves to database * * @param company the company that the campaign belongs to * @param campaignRequest information from which to generate the new campaign * @return the newly created campaign */ Campaign createCampaign(Company company, CampaignRequest campaignRequest); /** * Updates a campaign in the database * * @param campaignId the id of the campaign to be updated * @param companyId the company id for the campaign. Used to verify that the company client has ownership of the * campaign in question * @param campaignRequest information from which to update the campaign * @return the newly updated campaign */ Campaign updateCampaignById(UUID campaignId, UUID companyId, CampaignRequest campaignRequest); /** * Deletes a specific campaign * * @param campaignId the id of the campaign to delete * @param companyId the company id for the campaign. Used to verify that the company client has ownership of the * campaign in question */ void deleteCampaignById(UUID campaignId, UUID companyId); /** * Retrieves the discount code for a specific campaign * * @param campaignId the id of the campaign to get the discount code from * @return the discount code from the campaign with the supplied campaign id */ String getDiscountCode(UUID campaignId); } <file_sep>import React, { useState, useEffect, useRef } from "react"; import CampaignList from "../Components/campaign/cardList/campaignCardList.component"; import HeaderImage from "../Components/header/header.component"; import campaignService from "../services/campaignService"; export default function Home() { const [campaigns, setCampaigns] = useState([]); const didRun = useRef(false); useEffect(() => { if (didRun.current) { return; } didRun.current = true; campaignService.getAllPublishedCampaigns().then((campaigns) => { setCampaigns(campaigns); }); }, []); return ( <> <HeaderImage headerText="Special deals, just for you (and everyone else)" /> <CampaignList campaigns={campaigns} /> </> ); } <file_sep>package com.advertisementproject.emailservice.messagebroker.dto; import lombok.Data; import java.util.UUID; /** * Data transfer object received from User Service application including all email details except token */ @Data public class EmailDetailsMessage { /** * The id of the user to send a confirmation link email to. */ private UUID userId; /** * The name of the user to send a confirmation link email to. */ private String name; /** * The email address to send a confirmation link email to. */ private String email; } <file_sep>package com.advertisementproject.permissionservice.request; import lombok.Data; import javax.validation.constraints.NotNull; /** * Simple request object for updating permission for a user. Has a true/false value for whether the user should have * permission or not. */ @Data public class UpdatePermissionRequest { /** * Whether the user should have permission. */ @NotNull private final Boolean hasPermission; } <file_sep><!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (15) on Thu Feb 11 17:22:46 CET 2021 --> <title>F-Index</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="dc.created" content="2021-02-11"> <meta name="description" content="index: F"> <meta name="generator" content="javadoc/SplitIndexWriter"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../script-dir/jquery-ui.min.css" title="Style"> <link rel="stylesheet" type="text/css" href="../jquery-ui.overrides.css" title="Style"> <script type="text/javascript" src="../script.js"></script> <script type="text/javascript" src="../script-dir/jquery-3.5.1.min.js"></script> <script type="text/javascript" src="../script-dir/jquery-ui.min.js"></script> </head> <body class="split-index-page"> <script type="text/javascript">var pathtoroot = "../"; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="flex-box"> <header role="banner" class="flex-header"> <nav role="navigation"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="top-nav" id="navbar.top"> <div class="skip-nav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <ul id="navbar.top.firstrow" class="nav-list" title="Navigation"> <li><a href="../index.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="nav-bar-cell1-rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="sub-nav"> <div class="nav-list-search"><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </div> </div> <!-- ========= END OF TOP NAVBAR ========= --> <span class="skip-nav" id="skip.navbar.top"> <!-- --> </span></nav> </header> <div class="flex-content"> <main role="main"> <div class="header"> <h1>Index</h1> </div> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">J</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">Z</a>&nbsp;<br><a href="../allclasses-index.html">All&nbsp;Classes</a><span class="vertical-separator">|</span><a href="../allpackages-index.html">All&nbsp;Packages</a> <h2 class="title" id="I:F">F</h2> <dl class="index"> <dt><span class="member-name-link"><a href="../com/advertisementproject/zuulgateway/ZuulFilter/ZuulRequestFilter.html#filterOrder()">filterOrder()</a></span> - Method in class com.advertisementproject.zuulgateway.ZuulFilter.<a href="../com/advertisementproject/zuulgateway/ZuulFilter/ZuulRequestFilter.html" title="class in com.advertisementproject.zuulgateway.ZuulFilter">ZuulRequestFilter</a></dt> <dd> <div class="block">Sets the filter order</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/zuulgateway/ZuulFilter/ZuulRequestFilter.html#filterType()">filterType()</a></span> - Method in class com.advertisementproject.zuulgateway.ZuulFilter.<a href="../com/advertisementproject/zuulgateway/ZuulFilter/ZuulRequestFilter.html" title="class in com.advertisementproject.zuulgateway.ZuulFilter">ZuulRequestFilter</a></dt> <dd> <div class="block">Sets the type of filter</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/db/repository/CampaignRepository.html#findAllByCompanyUserId(java.util.UUID)">findAllByCompanyUserId(UUID)</a></span> - Method in interface com.advertisementproject.campaignservice.db.repository.<a href="../com/advertisementproject/campaignservice/db/repository/CampaignRepository.html" title="interface in com.advertisementproject.campaignservice.db.repository">CampaignRepository</a></dt> <dd> <div class="block">Retrieve all campaigns from the database for a specific company id</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/db/repository/CampaignRepository.html#findAllByIsPublishedTrue()">findAllByIsPublishedTrue()</a></span> - Method in interface com.advertisementproject.campaignservice.db.repository.<a href="../com/advertisementproject/campaignservice/db/repository/CampaignRepository.html" title="interface in com.advertisementproject.campaignservice.db.repository">CampaignRepository</a></dt> <dd> <div class="block">Retrieve all campaigns that are published, in other words where isPublished == true</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/interfaces/UserService.html#findAllUsers()">findAllUsers()</a></span> - Method in interface com.advertisementproject.userservice.service.interfaces.<a href="../com/advertisementproject/userservice/service/interfaces/UserService.html" title="interface in com.advertisementproject.userservice.service.interfaces">UserService</a></dt> <dd> <div class="block">Retrieves all customer/company users</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/UserServiceImpl.html#findAllUsers()">findAllUsers()</a></span> - Method in class com.advertisementproject.userservice.service.<a href="../com/advertisementproject/userservice/service/UserServiceImpl.html" title="class in com.advertisementproject.userservice.service">UserServiceImpl</a></dt> <dd> <div class="block">Retrieves all customer/company users</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/db/repository/UserRepository.html#findByEmail(java.lang.String)">findByEmail(String)</a></span> - Method in interface com.advertisementproject.userservice.db.repository.<a href="../com/advertisementproject/userservice/db/repository/UserRepository.html" title="interface in com.advertisementproject.userservice.db.repository">UserRepository</a></dt> <dd> <div class="block">Retrieves an optional user by email</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/zuulgateway/db/repositories/UserRepository.html#findByEmail(java.lang.String)">findByEmail(String)</a></span> - Method in interface com.advertisementproject.zuulgateway.db.repositories.<a href="../com/advertisementproject/zuulgateway/db/repositories/UserRepository.html" title="interface in com.advertisementproject.zuulgateway.db.repositories">UserRepository</a></dt> <dd> <div class="block">Retrieves an optional for a user including the user if the email matches, otherwise an empty optional.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/confirmationtokenservice/db/repository/ConfirmationTokenRepository.html#findByToken(java.lang.String)">findByToken(String)</a></span> - Method in interface com.advertisementproject.confirmationtokenservice.db.repository.<a href="../com/advertisementproject/confirmationtokenservice/db/repository/ConfirmationTokenRepository.html" title="interface in com.advertisementproject.confirmationtokenservice.db.repository">ConfirmationTokenRepository</a></dt> <dd> <div class="block">Retrieves an optional confirmation token object for a supplied token string</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/interfaces/UserService.html#findCompanyById(java.util.UUID)">findCompanyById(UUID)</a></span> - Method in interface com.advertisementproject.userservice.service.interfaces.<a href="../com/advertisementproject/userservice/service/interfaces/UserService.html" title="interface in com.advertisementproject.userservice.service.interfaces">UserService</a></dt> <dd> <div class="block">Retrieve a company object for the supplied id</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/UserServiceImpl.html#findCompanyById(java.util.UUID)">findCompanyById(UUID)</a></span> - Method in class com.advertisementproject.userservice.service.<a href="../com/advertisementproject/userservice/service/UserServiceImpl.html" title="class in com.advertisementproject.userservice.service">UserServiceImpl</a></dt> <dd> <div class="block">Retrieve a company object for the supplied id</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/confirmationtokenservice/db/repository/ConfirmationTokenRepository.html#findConfirmationTokenByConfirmedAtNotNullAndUserId(java.util.UUID)">findConfirmationTokenByConfirmedAtNotNullAndUserId(UUID)</a></span> - Method in interface com.advertisementproject.confirmationtokenservice.db.repository.<a href="../com/advertisementproject/confirmationtokenservice/db/repository/ConfirmationTokenRepository.html" title="interface in com.advertisementproject.confirmationtokenservice.db.repository">ConfirmationTokenRepository</a></dt> <dd> <div class="block">Retrieves all confirmation tokens that have been confirmed for a supplied user id.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/interfaces/UserService.html#findCustomerById(java.util.UUID)">findCustomerById(UUID)</a></span> - Method in interface com.advertisementproject.userservice.service.interfaces.<a href="../com/advertisementproject/userservice/service/interfaces/UserService.html" title="interface in com.advertisementproject.userservice.service.interfaces">UserService</a></dt> <dd> <div class="block">Retrieve a customer object for the supplied id</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/UserServiceImpl.html#findCustomerById(java.util.UUID)">findCustomerById(UUID)</a></span> - Method in class com.advertisementproject.userservice.service.<a href="../com/advertisementproject/userservice/service/UserServiceImpl.html" title="class in com.advertisementproject.userservice.service">UserServiceImpl</a></dt> <dd> <div class="block">Retrieve a customer object for the supplied id</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/interfaces/UserService.html#findUserById(java.util.UUID)">findUserById(UUID)</a></span> - Method in interface com.advertisementproject.userservice.service.interfaces.<a href="../com/advertisementproject/userservice/service/interfaces/UserService.html" title="interface in com.advertisementproject.userservice.service.interfaces">UserService</a></dt> <dd> <div class="block">Retrieve a user object for the supplied id</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/UserServiceImpl.html#findUserById(java.util.UUID)">findUserById(UUID)</a></span> - Method in class com.advertisementproject.userservice.service.<a href="../com/advertisementproject/userservice/service/UserServiceImpl.html" title="class in com.advertisementproject.userservice.service">UserServiceImpl</a></dt> <dd> <div class="block">Retrieve a user object for the supplied id</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/api/request/CustomerRegistrationRequest.html#firstName">firstName</a></span> - Variable in class com.advertisementproject.userservice.api.request.<a href="../com/advertisementproject/userservice/api/request/CustomerRegistrationRequest.html" title="class in com.advertisementproject.userservice.api.request">CustomerRegistrationRequest</a></dt> <dd> <div class="block">The first name of the customer to be registered.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/api/request/UpdateUserRequest.html#firstName">firstName</a></span> - Variable in class com.advertisementproject.userservice.api.request.<a href="../com/advertisementproject/userservice/api/request/UpdateUserRequest.html" title="class in com.advertisementproject.userservice.api.request">UpdateUserRequest</a></dt> <dd> <div class="block">The first name of the customer user to update.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/db/entity/Customer.html#firstName">firstName</a></span> - Variable in class com.advertisementproject.userservice.db.entity.<a href="../com/advertisementproject/userservice/db/entity/Customer.html" title="class in com.advertisementproject.userservice.db.entity">Customer</a></dt> <dd> <div class="block">The first name of the customer.</div> </dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">J</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">Z</a>&nbsp;<br><a href="../allclasses-index.html">All&nbsp;Classes</a><span class="vertical-separator">|</span><a href="../allpackages-index.html">All&nbsp;Packages</a></main> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottom-nav" id="navbar.bottom"> <div class="skip-nav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <ul id="navbar.bottom.firstrow" class="nav-list" title="Navigation"> <li><a href="../index.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="nav-bar-cell1-rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <span class="skip-nav" id="skip.navbar.bottom"> <!-- --> </span></nav> </footer> </div> </div> </body> </html> <file_sep>import authService from "../services/authService"; export default function headerRequest() { const currentUser = authService.currentUserValue; if (currentUser && currentUser.token) { return { Authorization: `Bearer ${currentUser.token}` }; } else { return {}; } } <file_sep>package com.advertisementproject.confirmationtokenservice.exception; import lombok.Getter; import org.springframework.http.HttpStatus; /** * Custom RuntimeException for exceptions related to confirmation tokens. Includes an http status and an error message. */ @Getter public class ConfirmationTokenException extends RuntimeException { /** * Error status for the exception */ private final HttpStatus httpStatus; /** * Constructor * * @param message the message for the exception * @param httpStatus the error status for the exception */ public ConfirmationTokenException(String message, HttpStatus httpStatus) { super(message); this.httpStatus = httpStatus; } } <file_sep>import React, { useState } from "react"; import Avatar from "@material-ui/core/Avatar"; import Button from "@material-ui/core/Button"; import CssBaseline from "@material-ui/core/CssBaseline"; import TextField from "@material-ui/core/TextField"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import Checkbox from "@material-ui/core/Checkbox"; import Link from "@material-ui/core/Link"; import Grid from "@material-ui/core/Grid"; import Box from "@material-ui/core/Box"; import LockOutlinedIcon from "@material-ui/icons/LockOutlined"; import Typography from "@material-ui/core/Typography"; import { makeStyles } from "@material-ui/core/styles"; import Container from "@material-ui/core/Container"; import Radio from "@material-ui/core/Radio"; import RadioGroup from "@material-ui/core/RadioGroup"; import FormControl from "@material-ui/core/FormControl"; import FormLabel from "@material-ui/core/FormLabel"; import { Link as RouterLink, useHistory } from "react-router-dom"; import TextareaAutosize from "@material-ui/core/TextareaAutosize"; import { InputLabel, Select } from "@material-ui/core"; import MenuItem from "@material-ui/core/MenuItem"; import authService from "../services/authService"; import CircularProgress from "@material-ui/core/CircularProgress"; const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: "flex", flexDirection: "column", alignItems: "center", }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: "100%", // Fix IE 11 issue. marginTop: theme.spacing(3), }, submit: { margin: theme.spacing(3, 0, 2), }, formControl: { margin: theme.spacing(1), minWidth: 120, }, })); export default function SignUp() { const classes = useStyles(); let history = useHistory(); const [open, setOpen] = useState(false); const [value, setSelectedValue] = useState(""); const [loading, setLoading] = useState(false); const [user, setUser] = useState({ name: "", organizationNumber: "", companyType: "", firstName: "", lastName: "", email: "", password: "", address: "", city: "", zipCode: "", phoneNumber: "", personalIdNumber: "", }); const handleUserChange = (prop) => (e) => { setUser({ ...user, [prop]: e.target.value }); }; const handleChange = (event) => { setSelectedValue(event.target.value); console.log(event.target.value); }; const attemptRegisterUser = (e) => { e.preventDefault(); setLoading(true); if (value === "customer") { authService .registerCustomer(user) .then((res) => { if (res.status === 200) { setLoading(false); console.log("WE MADE IT?"); history.push("/verify/email"); } else { console.log("TODO HANDLE ERRORS?"); setLoading(false); } }) .catch((err) => { console.log(err); setLoading(false); }); } else if (value === "company") { authService .registerCompany(user) .then((res) => { if (res.status === 200) { setLoading(false); console.log("COMPANY MADE IT?"); history.push("/verify/email"); } else { setLoading(false); console.log("TODO HANDLE ERRORS"); } }) .catch((err) => { console.log(err); setLoading(false); }); } else { console.log("NO USER SELECTED"); setLoading(false); } }; return ( <Container component="main" maxWidth="xs"> <CssBaseline /> <div className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign up </Typography> <form className={classes.form} noValidate> <Grid container spacing={2}> <Grid item xs={12}> <TextField variant="outlined" required fullWidth value={user.email} onChange={handleUserChange("email")} id="email" label="Email Address" name="email" autoComplete="email" /> </Grid> <Grid item xs={12}> <TextField variant="outlined" required fullWidth value={user.password} onChange={handleUserChange("password")} name="password" label="Password" type="password" id="password" autoComplete="current-password" /> </Grid> <Grid item xs={12}> <FormControl component="fieldset"> <FormLabel component="legend">Sign up as</FormLabel> <RadioGroup row aria-label="type" name="type1" value={value} onChange={handleChange} > <FormControlLabel value="customer" control={<Radio />} label="Customer" /> <FormControlLabel value="company" control={<Radio />} label="Company" /> </RadioGroup> </FormControl> </Grid> {console.log(user)} {value === "customer" ? ( <Grid container spacing={2}> <Grid item xs={12} sm={6}> <TextField autoComplete="fname" name="firstName" variant="outlined" value={user.firstName} onChange={handleUserChange("firstName")} required fullWidth id="firstName" label="<NAME>" autoFocus /> </Grid> <Grid item xs={12} sm={6}> <TextField variant="outlined" required fullWidth value={user.lastName} onChange={handleUserChange("lastName")} id="lastName" label="<NAME>" name="lastName" autoComplete="lname" /> </Grid> <Grid item xs={12} sm={6}> <TextField autoComplete="phoneNr" name="phoneNr" variant="outlined" required value={user.phoneNumber} onChange={handleUserChange("phoneNumber")} fullWidth id="phoneNr" label="Phone Number" /> </Grid> <Grid item xs={12} sm={6}> <TextField variant="outlined" required fullWidth value={user.personalIdNumber} onChange={handleUserChange("personalIdNumber")} id="personalID" label="Personal ID" name="personalID" autoComplete="personalID" /> </Grid> <Grid item xs={12} sm={8}> <TextField autoComplete="street" name="street" variant="outlined" value={user.address} onChange={handleUserChange("address")} required fullWidth id="street" label="Street" /> </Grid> <Grid item xs={12} sm={8}> <TextField variant="outlined" required fullWidth value={user.city} onChange={handleUserChange("city")} id="city" label="City" name="city" autoComplete="city" /> </Grid> <Grid item xs={12} sm={4}> <TextField variant="outlined" required fullWidth value={user.zipCode} onChange={handleUserChange("zipCode")} id="zipCode" label="Zip Code" name="zipCode" autoComplete="zipCode" /> </Grid> </Grid> ) : null} {value === "company" ? ( <Grid container spacing={2}> <Grid item xs={12} sm={6}> <TextField autoComplete="companyName" name="companyName" variant="outlined" value={user.name} onChange={handleUserChange("name")} required fullWidth id="companyName" label="Company Name" autoFocus /> </Grid> <Grid item xs={12} sm={6}> <TextField autoComplete="phoneNr" name="phoneNr" variant="outlined" required value={user.phoneNumber} onChange={handleUserChange("phoneNumber")} fullWidth id="phoneNr" label="Phone Number" /> </Grid> <Grid item xs={12} sm={6}> <TextField variant="outlined" required fullWidth value={user.organizationNumber} onChange={handleUserChange("organizationNumber")} id="organizationNr" label="Organization Numer" name="organizationNr" autoComplete="organizationNr" /> </Grid> <Grid item xs={12} sm={6}> <TextField variant="outlined" required fullWidth value={user.city} onChange={handleUserChange("city")} id="city" label="City" name="city" autoComplete="city" /> </Grid> <Grid item xs={12} sm={6}> <TextField autoComplete="street" name="street" variant="outlined" required value={user.address} onChange={handleUserChange("address")} fullWidth id="street" label="Street" /> </Grid> <Grid item xs={12} sm={4}> <TextField variant="outlined" required fullWidth value={user.zipCode} onChange={handleUserChange("zipCode")} id="zipCode" label="Zip Code" name="zipCode" autoComplete="zipCode" /> </Grid> <Grid item xs={12} sm={6}> <TextareaAutosize aria-label="minimum height" rowsMin={5} placeholder="Company description" /> </Grid> <Grid item xs={12} sm={6}> <FormControl className={classes.formControl}> <InputLabel id="select-label">Company Type</InputLabel> <Select labelId="select-label" open={open} onClose={() => setOpen(false)} onOpen={() => setOpen(true)} value={user.companyType} onChange={handleUserChange("companyType")} > <MenuItem value={"RETAIL"}>Retail</MenuItem> <MenuItem value={"TELECOM"}>Telecom</MenuItem> <MenuItem value={"HEALTH"}>Health</MenuItem> <MenuItem value={"RESTAURANT"}>Restaurant</MenuItem> <MenuItem value={"TRANSPORTATION"}> Transportation </MenuItem> <MenuItem value={"SOFTWARE"}>Software</MenuItem> <MenuItem value={"OTHER"}>Other</MenuItem> </Select> </FormControl> </Grid> </Grid> ) : null} <Grid item xs={12}> <FormControlLabel control={<Checkbox value="allowExtraEmails" color="primary" />} label="I want to receive spam from Elias and updates via email." /> </Grid> </Grid> {!loading ? ( <Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit} onClick={attemptRegisterUser} > Sign Up </Button> ) : ( <CircularProgress /> )} <Grid container justify="flex-end"> <Grid item> <Link component={RouterLink} to={"/login"} href="#" variant="body2" > Already have an account? Sign in </Link> </Grid> </Grid> </form> </div> <Box mt={5}></Box> </Container> ); } <file_sep><!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (15) on Thu Feb 11 17:22:46 CET 2021 --> <title>I-Index</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="dc.created" content="2021-02-11"> <meta name="description" content="index: I"> <meta name="generator" content="javadoc/SplitIndexWriter"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../script-dir/jquery-ui.min.css" title="Style"> <link rel="stylesheet" type="text/css" href="../jquery-ui.overrides.css" title="Style"> <script type="text/javascript" src="../script.js"></script> <script type="text/javascript" src="../script-dir/jquery-3.5.1.min.js"></script> <script type="text/javascript" src="../script-dir/jquery-ui.min.js"></script> </head> <body class="split-index-page"> <script type="text/javascript">var pathtoroot = "../"; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="flex-box"> <header role="banner" class="flex-header"> <nav role="navigation"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="top-nav" id="navbar.top"> <div class="skip-nav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <ul id="navbar.top.firstrow" class="nav-list" title="Navigation"> <li><a href="../index.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="nav-bar-cell1-rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="sub-nav"> <div class="nav-list-search"><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </div> </div> <!-- ========= END OF TOP NAVBAR ========= --> <span class="skip-nav" id="skip.navbar.top"> <!-- --> </span></nav> </header> <div class="flex-content"> <main role="main"> <div class="header"> <h1>Index</h1> </div> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">J</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">Z</a>&nbsp;<br><a href="../allclasses-index.html">All&nbsp;Classes</a><span class="vertical-separator">|</span><a href="../allpackages-index.html">All&nbsp;Packages</a> <h2 class="title" id="I:I">I</h2> <dl class="index"> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/db/entity/Campaign.html#id">id</a></span> - Variable in class com.advertisementproject.campaignservice.db.entity.<a href="../com/advertisementproject/campaignservice/db/entity/Campaign.html" title="class in com.advertisementproject.campaignservice.db.entity">Campaign</a></dt> <dd> <div class="block">Primary id for Campaign entity.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/confirmationtokenservice/db/entity/ConfirmationToken.html#id">id</a></span> - Variable in class com.advertisementproject.confirmationtokenservice.db.entity.<a href="../com/advertisementproject/confirmationtokenservice/db/entity/ConfirmationToken.html" title="class in com.advertisementproject.confirmationtokenservice.db.entity">ConfirmationToken</a></dt> <dd> <div class="block">Primary id for the ConfirmationToken entity.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/db/entity/User.html#id">id</a></span> - Variable in class com.advertisementproject.userservice.db.entity.<a href="../com/advertisementproject/userservice/db/entity/User.html" title="class in com.advertisementproject.userservice.db.entity">User</a></dt> <dd> <div class="block">Primary id for User entity.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/zuulgateway/db/entity/User.html#id">id</a></span> - Variable in class com.advertisementproject.zuulgateway.db.entity.<a href="../com/advertisementproject/zuulgateway/db/entity/User.html" title="class in com.advertisementproject.zuulgateway.db.entity">User</a></dt> <dd> <div class="block">Primary id for User entity.</div> </dd> <dt><a href="../com/advertisementproject/userservice/api/exception/IdentificationNumberException.html" title="class in com.advertisementproject.userservice.api.exception"><span class="type-name-link">IdentificationNumberException</span></a> - Exception in <a href="../com/advertisementproject/userservice/api/exception/package-summary.html">com.advertisementproject.userservice.api.exception</a></dt> <dd> <div class="block">Custom IllegalArgumentException thrown when a personal id number or organization number has invalid format</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/api/exception/IdentificationNumberException.html#%3Cinit%3E(java.lang.String)">IdentificationNumberException(String)</a></span> - Constructor for exception com.advertisementproject.userservice.api.exception.<a href="../com/advertisementproject/userservice/api/exception/IdentificationNumberException.html" title="class in com.advertisementproject.userservice.api.exception">IdentificationNumberException</a></dt> <dd> <div class="block">Constructor</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/db/entity/Campaign.html#image">image</a></span> - Variable in class com.advertisementproject.campaignservice.db.entity.<a href="../com/advertisementproject/campaignservice/db/entity/Campaign.html" title="class in com.advertisementproject.campaignservice.db.entity">Campaign</a></dt> <dd> <div class="block">Image file stored as a base64 formatted string (text type in the database).</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/request/CampaignRequest.html#image">image</a></span> - Variable in class com.advertisementproject.campaignservice.request.<a href="../com/advertisementproject/campaignservice/request/CampaignRequest.html" title="class in com.advertisementproject.campaignservice.request">CampaignRequest</a></dt> <dd> <div class="block">Image in base64 string format.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/zuulgateway/security/model/UserDetailsImpl.html#isAccountNonExpired()">isAccountNonExpired()</a></span> - Method in class com.advertisementproject.zuulgateway.security.model.<a href="../com/advertisementproject/zuulgateway/security/model/UserDetailsImpl.html" title="class in com.advertisementproject.zuulgateway.security.model">UserDetailsImpl</a></dt> <dd> <div class="block">Gets a true or false value for whether the account is non-expired</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/zuulgateway/security/model/UserDetailsImpl.html#isAccountNonLocked()">isAccountNonLocked()</a></span> - Method in class com.advertisementproject.zuulgateway.security.model.<a href="../com/advertisementproject/zuulgateway/security/model/UserDetailsImpl.html" title="class in com.advertisementproject.zuulgateway.security.model">UserDetailsImpl</a></dt> <dd> <div class="block">Gets a true or false value for whether the account is non-locked, determined in our case by whether the user has valid permissions</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/zuulgateway/security/model/UserDetailsImpl.html#isCredentialsNonExpired()">isCredentialsNonExpired()</a></span> - Method in class com.advertisementproject.zuulgateway.security.model.<a href="../com/advertisementproject/zuulgateway/security/model/UserDetailsImpl.html" title="class in com.advertisementproject.zuulgateway.security.model">UserDetailsImpl</a></dt> <dd> <div class="block">Gets a true or false value for whether the credentials are non-expired</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/zuulgateway/security/model/UserDetailsImpl.html#isEnabled()">isEnabled()</a></span> - Method in class com.advertisementproject.zuulgateway.security.model.<a href="../com/advertisementproject/zuulgateway/security/model/UserDetailsImpl.html" title="class in com.advertisementproject.zuulgateway.security.model">UserDetailsImpl</a></dt> <dd> <div class="block">Gets a true or false value for whether the user is enabled</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/ValidationServiceImpl.html#isOnlyDigits(java.lang.String)">isOnlyDigits(String)</a></span> - Static method in class com.advertisementproject.userservice.service.<a href="../com/advertisementproject/userservice/service/ValidationServiceImpl.html" title="class in com.advertisementproject.userservice.service">ValidationServiceImpl</a></dt> <dd> <div class="block">Helper method to check if a string consists of only digits.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/db/entity/Campaign.html#isPercentage">isPercentage</a></span> - Variable in class com.advertisementproject.campaignservice.db.entity.<a href="../com/advertisementproject/campaignservice/db/entity/Campaign.html" title="class in com.advertisementproject.campaignservice.db.entity">Campaign</a></dt> <dd> <div class="block">Determines whether field "discount" is a percentage (true) or a fixed amount (false).</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/request/CampaignRequest.html#isPercentage">isPercentage</a></span> - Variable in class com.advertisementproject.campaignservice.request.<a href="../com/advertisementproject/campaignservice/request/CampaignRequest.html" title="class in com.advertisementproject.campaignservice.request">CampaignRequest</a></dt> <dd> <div class="block">Whether the discount is a percentage (true) or a fixed amount (false) in the campaign to create/update.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/campaignservice/db/entity/Campaign.html#isPublished">isPublished</a></span> - Variable in class com.advertisementproject.campaignservice.db.entity.<a href="../com/advertisementproject/campaignservice/db/entity/Campaign.html" title="class in com.advertisementproject.campaignservice.db.entity">Campaign</a></dt> <dd> <div class="block">Field for quickly checking if a campaign is published without needing to check dates when fetching published campaigns.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/ValidationServiceImpl.html#isValidOrganizationNumber(java.lang.String)">isValidOrganizationNumber(String)</a></span> - Method in class com.advertisementproject.userservice.service.<a href="../com/advertisementproject/userservice/service/ValidationServiceImpl.html" title="class in com.advertisementproject.userservice.service">ValidationServiceImpl</a></dt> <dd> <div class="block">Helper method to validate that a string is in valid organization number format.</div> </dd> <dt><span class="member-name-link"><a href="../com/advertisementproject/userservice/service/ValidationServiceImpl.html#isValidPersonalIdNumber(java.lang.String)">isValidPersonalIdNumber(String)</a></span> - Method in class com.advertisementproject.userservice.service.<a href="../com/advertisementproject/userservice/service/ValidationServiceImpl.html" title="class in com.advertisementproject.userservice.service">ValidationServiceImpl</a></dt> <dd> <div class="block">Helper method to validate that a string is in valid personal id number format.</div> </dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">J</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">Z</a>&nbsp;<br><a href="../allclasses-index.html">All&nbsp;Classes</a><span class="vertical-separator">|</span><a href="../allpackages-index.html">All&nbsp;Packages</a></main> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottom-nav" id="navbar.bottom"> <div class="skip-nav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <ul id="navbar.bottom.firstrow" class="nav-list" title="Navigation"> <li><a href="../index.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="nav-bar-cell1-rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <span class="skip-nav" id="skip.navbar.bottom"> <!-- --> </span></nav> </footer> </div> </div> </body> </html> <file_sep>package com.advertisementproject.emailservice.service.interfaces; import com.advertisementproject.emailservice.db.entity.EmailDetails; import com.advertisementproject.emailservice.messagebroker.dto.EmailDetailsMessage; import com.advertisementproject.emailservice.messagebroker.dto.TokenMessage; import java.util.UUID; /** * Service for managing email details in the database */ public interface EmailDetailsService { /** * Saves email details from an email details message to the database for the user id in the message * * @param emailDetailsMessage email details (except token) to be saved/added to the database for that user id */ void saveDetails(EmailDetailsMessage emailDetailsMessage); /** * Saves token from a token message to the database for the user id in the message * * @param tokenMessage message with token and a user id for which the token should be saved in the database */ void saveToken(TokenMessage tokenMessage); /** * Retrieves full email details including token for a user id if all the information is present, otherwise null. * * @param userId the user id for which to retrieve full email details * @return email details including all the information if available, otherwise null. */ EmailDetails getCompleteDetailsOrNull(UUID userId); /** * Deletes the supplied email details from the database * * @param emailDetails the email details object to delete from the database */ void deleteEmailDetails(EmailDetails emailDetails); } <file_sep>import React, { useContext, useEffect } from "react"; import Home from "../../pages/Home"; import Login from "../../pages/Login"; import Signup from "../../pages/Signup"; import Company from "../../pages/Company"; import Email from "../../pages/Email"; import Navbar from "../navbar/navbar.component"; import { Switch, Route } from "react-router-dom"; import { UserContext } from "../../context/UserContext"; import authService from "../../services/authService"; import { PrivateRoute } from "../routes/privateroute.component"; import Footer from '../footer/footer.component' function App() { const [user, userDispatch] = useContext(UserContext); useEffect(() => { authService.currentUser.subscribe((x) => { if (x !== null) { userDispatch({ type: "LOAD_USER", payload: x }); } }); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( <> <Navbar /> <Switch> <Route exact path="/" component={Home} /> <Route path="/verify/email" component={Email} /> <Route path="/login" component={Login} /> <Route path="/signup" component={Signup} /> <PrivateRoute path="/company" component={Company} roles={[user.role]} /> </Switch> <Footer/> </> ); } export default App; <file_sep>package com.advertisementproject.userservice.messagebroker.listener; import com.advertisementproject.userservice.service.interfaces.UserService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Service; import java.util.UUID; /** * MessageListener is a service that listens for messages from other microservices via RabbitMQ and then performs * appropriate actions for the messages received. When a message is sent to the listed queue, the message is received, * logged and handled in the listener method with the help of UserService. * When Confirmation Token Service has confirmed a token, it has the responsibility to inform this application that a * user should be enabled. */ @Slf4j @Service @RequiredArgsConstructor public class MessageListener { /** * Service for managing CRUD operations for Users. */ private final UserService userService; /** * Listens for messages from Confirmation Token Service including a user id for the user that should be enabled, * then enabled the user for the supplied user id. * * @param userId the user id for which user should be enabled. */ @RabbitListener(queues = "enableUser") public void enableUserListener(UUID userId) { log.info("[MESSAGE BROKER] Received enableUser message for id: " + userId); userService.enableUser(userId); } } <file_sep>package com.advertisementproject.zuulgateway.db.entity; import com.advertisementproject.zuulgateway.db.entity.types.Role; import lombok.Data; import javax.persistence.*; import java.util.UUID; /** * Users are kept up-to-date by receiving messages from Permissions Service application and then updating the * table accordingly whenever a user object is created, updated or deleted. Includes core account information, which * role the user has and whether the user is enabled. */ @Entity @Table(name = "users") @Data public class User { /** * Primary id for User entity. */ @Id private UUID id; /** * Email address for the user which must be unique. Used as a username when logging in through the Zuul Gateway * application. */ private String email; /** * Hashed password from the raw password the user submitted upon registration. Must match the password the user * enters for login. */ private String hashedPassword; /** * Phone number for the user. */ private String phoneNumber; /** * The role of the user, which determines access rights within the system, as defined in WebSecurityConfiguration. */ @Enumerated(EnumType.STRING) private Role role; /** * Street address for the user. */ private String address; /** * City for the user address. */ private String city; /** * Zip code or postal code for the user address. */ private String zipCode; /** * Whether the user account is enabled. Set to true if the user's email has been enabled, otherwise false. */ private boolean enabled; } <file_sep>package com.advertisementproject.zuulgateway.api.response; import com.advertisementproject.zuulgateway.db.entity.types.Role; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import java.io.Serializable; /** * Response after a successful login, including the user's role and a jwt token that should be attached as a bearer * token in the header for any request which requires authorization. */ @NoArgsConstructor @AllArgsConstructor @Getter public class AuthenticationResponse implements Serializable { /** * JWT authentication token for the user to attach as a bearer token in the header for any request which requires * authorization. */ private String token; /** * The role of the user that just logged in. */ private Role role; } <file_sep>package com.advertisementproject.userservice.db.entity; import com.advertisementproject.userservice.api.request.CompanyRegistrationRequest; import com.advertisementproject.userservice.api.request.CustomerRegistrationRequest; import com.advertisementproject.userservice.db.entity.types.Role; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.util.UUID; import static com.advertisementproject.userservice.db.entity.types.Role.COMPANY; import static com.advertisementproject.userservice.db.entity.types.Role.CUSTOMER; import static javax.persistence.EnumType.STRING; /** * User entity with core account information about a user. Raw password is transient and ignored for JSON which means * that it can be validated along with the rest of the fields but won't show up as JSON or be saved in the database. */ @AllArgsConstructor @NoArgsConstructor @Getter @Setter @Builder @Table(name = "users") @Entity public class User { /** * Primary id for User entity. */ @Id private UUID id; /** * Email address for the user which must be unique. Used as a username when logging in through the Zuul Gateway * application. */ @Column(unique = true) @NotNull @Pattern(regexp = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$", message = "Must enter an valid email") private String email; /** * Raw password for the user account which is not saved in the database and not exposed as JSON. It only exists in * the user class so it can easily be validated along with all the other fields. */ @Transient @JsonIgnore @Pattern(regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#&()–[{}]:;',?/*~$^+=<>]).{8,20}$", message = "Password must contain at least one digit [0-9], " + "at least one lowercase Latin character [a-z], " + "at least one uppercase Latin character [A-Z], " + "at least one special character like ! @ # & ( ) " + "and have a length of at least 8 characters and a maximum of 20 characters") private String rawPassword; /** * Hashed password from the raw password the user submitted upon registration. */ @NotNull @Size(min = 60, max = 60) private String hashedPassword; /** * Phone number for the user. */ @NotNull @Pattern(regexp = "^[0-9]{10}$", message = "PhoneNumber must be exactly 10 digits") private String phoneNumber; /** * The role of the user, which determines access rights within the system, as defined by Zuul Gateway application. */ @Enumerated(STRING) private Role role; /** * Street address for the user. */ @NotNull @Size(min = 2, max = 20, message = "Address must be 2-20 characters long") private String address; /** * City for the user address. */ @NotNull @Size(min = 2, max = 20, message = "City must be 2-20 characters long") private String city; /** * Zip code or postal code for the user address. */ @NotNull @Pattern(regexp = "^[0-9]{5}$", message = "Zip code must be 5 digits long") private String zipCode; /** * Whether the user account is enabled. Set to true if the user's email has been enabled, otherwise false. */ private boolean enabled = false; /** * Builder method for constructing a user from relevant fields in a supplied CustomerRegistrationRequest for a * supplied user id. * * @param request request including all the relevant fields needed to make a user entity * @return a new user object based on the supplied user id and request object fields */ public static User toUser(CustomerRegistrationRequest request) { return builder() .id(UUID.randomUUID()) .address(request.getAddress()) .city(request.getCity()) .zipCode(request.getZipCode()) .email(request.getEmail()) .phoneNumber(request.getPhoneNumber()) .role(CUSTOMER) .rawPassword(request.getPassword()) .hashedPassword(new BCryptPasswordEncoder(12).encode(request.getPassword())) .enabled(false) .build(); } /** * Builder method for constructing a user from relevant fields in a supplied CompanyRegistrationRequest for a * supplied user id. * * @param request request including all the relevant fields needed to make a user entity * @return a new user object based on the supplied user id and request object fields */ public static User toUser(CompanyRegistrationRequest request) { return builder() .id(UUID.randomUUID()) .address(request.getAddress()) .city(request.getCity()) .zipCode(request.getZipCode()) .email(request.getEmail()) .phoneNumber(request.getPhoneNumber()) .role(COMPANY) .rawPassword(request.<PASSWORD>()) .hashedPassword(new BCryptPasswordEncoder(12).encode(request.<PASSWORD>())) .enabled(false) .build(); } } <file_sep>package com.advertisementproject.userservice.service; import com.advertisementproject.userservice.api.exception.EmailAlreadyRegisteredException; import com.advertisementproject.userservice.api.exception.EntityNotFoundException; import com.advertisementproject.userservice.api.request.UpdateUserRequest; import com.advertisementproject.userservice.api.response.CompanyUserResponse; import com.advertisementproject.userservice.api.response.CustomerUserResponse; import com.advertisementproject.userservice.db.entity.Company; import com.advertisementproject.userservice.db.entity.Customer; import com.advertisementproject.userservice.db.entity.User; import com.advertisementproject.userservice.db.entity.types.Role; import com.advertisementproject.userservice.db.repository.CompanyRepository; import com.advertisementproject.userservice.db.repository.CustomerRepository; import com.advertisementproject.userservice.db.repository.UserRepository; import com.advertisementproject.userservice.messagebroker.publisher.MessagePublisher; import com.advertisementproject.userservice.service.interfaces.UserService; import com.advertisementproject.userservice.service.interfaces.ValidationService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Service implementation for doing CRUD operations for users, customers and companies in the database */ @Slf4j @Service @RequiredArgsConstructor public class UserServiceImpl implements UserService { /** * JPA Repository for Users. */ private final UserRepository userRepository; /** * JPA Repository for Companies. */ private final CompanyRepository companyRepository; /** * JPA Repository for Customers. */ private final CustomerRepository customerRepository; /** * Service for validating customer/company users. */ private final ValidationService validationService; /** * Service for sending messages to other microservices via message broker. */ private final MessagePublisher messagePublisher; /** * Retrieves all customer/company users * * @return list of all users with full user information including user as well as related customer/company */ @Override public List<Object> findAllUsers() { List<User> userList = userRepository.findAll(); List<Object> extendedUserList = new ArrayList<>(); for (User user : userList) { if (user.getRole().equals(Role.CUSTOMER)) { extendedUserList.add(new CustomerUserResponse(user, findCustomerById(user.getId()))); } else { extendedUserList.add(new CompanyUserResponse(user, findCompanyById(user.getId()))); } } return extendedUserList; } /** * Retrieves all info for a customer/company user * * @param id the id for which to retrieve full user information * @return full user information including user as well as related customer/company for the supplied user id * @throws EntityNotFoundException if the user is not found for the supplied user id */ @Override public Object getFullUserInfoById(UUID id) { User user = findUserById(id); return getCustomerOrCompanyUser(user); } /** * Retrieves all info for a customer/company user * * @param email the email for which to retrieve full user information * @return full user information including user as well as related customer/company for the supplied email * @throws EntityNotFoundException if the user is not found for the supplied email */ @Override public Object getFullUserInfoByEmail(String email) { User user = userRepository.findByEmail(email) .orElseThrow(() -> new EntityNotFoundException("User not found for email: " + email)); return getCustomerOrCompanyUser(user); } /** * Saves a customer user to the database and sends messages to inform other microservices that a user has been * created so they can update their databases accordingly. * * @param user the user object to be saved * @param customer the customer object to be saved * @return the newly saved customer user */ @Override public CustomerUserResponse saveCustomerUser(User user, Customer customer) { userRepository.save(user); messagePublisher.sendUserMessage(user); customerRepository.save(customer); return new CustomerUserResponse(user, customer); } /** * Saves a company user to the database and sends messages to inform other microservices that a user has been * created as well as that a company has been created so they can update their databases accordingly. * * @param user the user object to be saved * @param company the company object to be saved * @return the newly saved company user */ @Override public CompanyUserResponse saveCompanyUser(User user, Company company) { userRepository.save(user); messagePublisher.sendUserMessage(user); companyRepository.save(company); messagePublisher.sendCompanyMessage(company); return new CompanyUserResponse(user, company); } /** * Validates that a customer/company user is not already registered for a supplied email * * @param email the email to validate is not already registered. * @throws EmailAlreadyRegisteredException if the supplied email is already registered. */ @Override public void validateNotAlreadyRegistered(String email) { if (userRepository.findByEmail(email).isPresent()) { throw new EmailAlreadyRegisteredException("Email is already registered for email: " + email); } } /** * Retrieve a user object for the supplied id * * @param id the user id for which to retrieve a user object * @return the user object retrieved for the supplied id * @throws EntityNotFoundException if the user is not found in the database for the supplied id */ @Override public User findUserById(UUID id) { return userRepository.findById(id).orElseThrow( () -> new EntityNotFoundException("User not found for id: " + id) ); } /** * Retrieve a customer object for the supplied id * * @param id the user id for which to retrieve a customer object * @return the customer object retrieved for the supplied id * @throws EntityNotFoundException if the customer is not found in the database for the supplied id */ @Override public Customer findCustomerById(UUID id) { return customerRepository.findById(id).orElseThrow( () -> new EntityNotFoundException("Customer not found for id: " + id) ); } /** * Retrieve a company object for the supplied id * * @param id the user id for which to retrieve a company object * @return the company object retrieved for the supplied id * @throws EntityNotFoundException if the company is not found in the database for the supplied id */ @Override public Company findCompanyById(UUID id) { return companyRepository.findById(id).orElseThrow( () -> new EntityNotFoundException("Company not found for id: " + id) ); } /** * Deletes user and related customer/company for the supplied id. Informs other microservices that a user has been * deleted and that they should remove information related to that user id. * * @param id the user id for which to delete a customer/company user */ @Override @Transactional public void deleteUserById(UUID id) { User user = findUserById(id); if (user.getRole().equals(Role.CUSTOMER)) { customerRepository.deleteById(user.getId()); } else { companyRepository.deleteById(user.getId()); } userRepository.deleteById(id); messagePublisher.sendUserDeleteMessage(id); } /** * Updates a customer/company user with the fields supplied in the UpdateUserRequest. Informs other microservices * that a user has been updated and that they should update their own user table. If the user is a company user, * other microservices are informed that a company has been updated and they should update their own company table. * * @param id the id of the customer/company user to be updated * @param updateUserRequest request object including fields that should be updated * @return the newly updated customer/company user */ @Override @Transactional public Object updateUser(UUID id, UpdateUserRequest updateUserRequest) { User user = findUserById(id); updateUserFields(updateUserRequest, user); validationService.validateUser(user); if (user.getRole().equals(Role.CUSTOMER)) { Customer customer = findCustomerById(user.getId()); updateCustomerFields(updateUserRequest, customer); validationService.validateCustomer(customer); userRepository.save(user); messagePublisher.sendUserMessage(user); customerRepository.save(customer); return new CustomerUserResponse(user, customer); } else { Company company = findCompanyById(user.getId()); updateCompanyFields(updateUserRequest, company); validationService.validateCompany(company); userRepository.save(user); messagePublisher.sendUserMessage(user); companyRepository.save(company); messagePublisher.sendCompanyMessage(company); return new CompanyUserResponse(user, company); } } /** * Helper method to get a CustomerUserResponse or CompanyUserResponse from a supplied user depending on their role. * * @param user the user for which to get a CustomerUserResponse or CompanyUserResponse * @return CustomerUserResponse or CompanyUserResponse depending on the role of the supplied user. */ private Object getCustomerOrCompanyUser(User user) { if (user.getRole().equals(Role.CUSTOMER)) { return new CustomerUserResponse(user, findCustomerById(user.getId())); } else { return new CompanyUserResponse(user, findCompanyById(user.getId())); } } /** * Helper method to update user using the fields that are not null in the supplied UpdateUserRequest * * @param updateUserRequest request object with fields to update the user with. * @param user the user to update */ private void updateUserFields(UpdateUserRequest updateUserRequest, User user) { if (updateUserRequest.getEmail() != null) { user.setEmail(updateUserRequest.getEmail()); } if (updateUserRequest.getPassword() != null) { user.setRawPassword(updateUserRequest.getPassword()); user.setHashedPassword(new BCryptPasswordEncoder(12).encode(updateUserRequest.getPassword())); } if (updateUserRequest.getPhoneNumber() != null) { user.setPhoneNumber(updateUserRequest.getPhoneNumber()); } if (updateUserRequest.getAddress() != null) { user.setAddress(updateUserRequest.getAddress()); } if (updateUserRequest.getCity() != null) { user.setCity(updateUserRequest.getCity()); } if (updateUserRequest.getZipCode() != null) { user.setZipCode(updateUserRequest.getZipCode()); } } /** * Helper method to update customer using the fields that are not null in the supplied UpdateUserRequest * * @param updateUserRequest request object with fields to update the customer with. * @param customer the customer to update */ private void updateCustomerFields(UpdateUserRequest updateUserRequest, Customer customer) { if (updateUserRequest.getFirstName() != null) { customer.setFirstName(updateUserRequest.getFirstName()); } if (updateUserRequest.getLastName() != null) { customer.setLastName(updateUserRequest.getLastName()); } if (updateUserRequest.getPersonalIdNumber() != null) { customer.setPersonalIdNumber(updateUserRequest.getPersonalIdNumber()); } } /** * Helper method to update company using the fields that are not null in the supplied UpdateUserRequest * * @param updateUserRequest request object with fields to update the company with. * @param company the company to update */ private void updateCompanyFields(UpdateUserRequest updateUserRequest, Company company) { if (updateUserRequest.getName() != null) { company.setName(updateUserRequest.getName()); } if (updateUserRequest.getOrganizationNumber() != null) { company.setOrganizationNumber(updateUserRequest.getOrganizationNumber()); } if (updateUserRequest.getDescription() != null) { company.setDescription(updateUserRequest.getDescription()); } if (updateUserRequest.getCompanyType() != null) { company.setCompanyType(updateUserRequest.getCompanyType()); } } /** * Enables the user with supplied id * * @param userId the id of the user to be enabled * @throws EntityNotFoundException if the user is not found for the supplied id */ @Override @Transactional public void enableUser(UUID userId) { userRepository.enableUser(userId); User user = userRepository.findById(userId) .orElseThrow(() -> new EntityNotFoundException("User not found for id: " + userId)); messagePublisher.sendUserMessage(user); log.info("User enabled with id: " + userId); } }<file_sep>package com.advertisementproject.userservice.db.entity.types; /** * Enum for which role a user has. Customer users have the role CUSTOMER. Company users have the role COMPANY and may * create campaigns in the Campaign Service application for instance. ADMIN users are manually created in the database * and have full access. */ public enum Role { /** * Customer users have access to a limited amount of features, such as changing their own data, viewing published * campaigns and retrieving discount codes for those campaigns. */ CUSTOMER, /** * Company users have access to all that a customer user has and may in addition create and manage campaigns. A * company user may not access or manipulate other users' data, other than viewing published campaigns. */ COMPANY, /** * Admin users have full access to the system and may modify other users' data. If necessary, an admin user may * revoke other users' permission to use the system. */ ADMIN } <file_sep>package com.advertisementproject.zuulgateway.api.exceptions; /** * Runtime exception for when an entity is not found */ public class EntityNotFoundException extends RuntimeException { /** * Constructor * * @param message the error message */ public EntityNotFoundException(String message) { super(message); } } <file_sep>import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import CampaignCard from "../card/campaignCard.component"; import Grid from "@material-ui/core/Grid"; const useStyles = makeStyles({ gridContainer: { maxWidth: 1200, margin: "auto", direction: "row", justify: "center", alignItems: "center", spacing: 8, }, }); const CampaignList = ({ campaigns }) => { const classes = useStyles(); return ( <Grid container className={classes.gridContainer} wrap="wrap" spacing={3}> {campaigns.map((campaign) => ( <CampaignCard key={campaign.id} campaign={campaign} /> ))} </Grid> ); }; export default CampaignList; <file_sep>package com.advertisementproject.campaignservice.db.entity; import com.advertisementproject.campaignservice.db.entity.type.CompanyType; import com.advertisementproject.campaignservice.db.entity.view.View; import com.fasterxml.jackson.annotation.JsonView; import lombok.Data; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Id; import javax.validation.constraints.NotNull; import java.util.UUID; /** * Company contains information about the company that created the campaign and each campaign must be tied to a company. * If a company is removed then all related campaigns are also removed. The User Service is responsible for informing * this application of any changes to the company database so that this application also may keep an up to date copy. * * @JsonView restricts the information in a JSON response to only the annotated fields if a view is set in the controller. */ @Data @Entity public class Company { /** * Primary id for Company entity that matches user id. */ @Id private UUID userId; /** * The name of the company. */ @JsonView(value = {View.publicInfo.class}) private String name; /** * The organization number for the company, which is like an id number for companies in the Swedish system. */ @JsonView(value = {View.publicInfo.class}) private String organizationNumber; /** * Optional description of the company. */ @JsonView(value = {View.publicInfo.class}) private String description; /** * The type of company that the company can be classified as, for example "RETAIL" or "SOFTWARE". */ @NotNull @Enumerated(EnumType.STRING) @JsonView(value = {View.publicInfo.class}) private CompanyType companyType; } <file_sep>import React from "react"; import { Route, Redirect } from "react-router-dom"; import AuthApi from "../../services/authService"; export const PrivateRoute = ({ component: Component, roles, ...rest }) => ( <Route {...rest} render={(props) => { const currentUser = AuthApi.currentUserValue; if (!currentUser) { return <Redirect to={{ pathname: "/login" }} />; } if (roles && roles.indexOf(currentUser.role) === -1) { return <Redirect to={{ pathname: "/" }} />; } return <Component {...props} />; }} /> ); <file_sep>package com.advertisementproject.zuulgateway.security.configuration; import com.advertisementproject.zuulgateway.security.Utils.JwtUtils; import com.advertisementproject.zuulgateway.security.filters.JwtTokenValidationFilter; import com.advertisementproject.zuulgateway.security.filters.JwtUsernameAndPasswordAuthenticationFilter; import com.advertisementproject.zuulgateway.services.UserDetailsServiceImpl; import com.google.common.collect.ImmutableList; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; /** * Web security configuration for the entire project. CSRF is disabled and cors is activated. Requests can be set as * open to the public, only available for non logged in users or requires authorization for one or more specific role(s). * If an authorized endpoint is desired, the user must login via "/login" endpoint, which is handled by * JwtUsernameAndPasswordAuthenticationFilter. Upon successful login, the user can set the jwt token from the response * in the header of the request to the authentication locked endpoint. Then JwtTokenValidationFilter makes sure that the * id from the jwt token in the header matches a valid user that is enabled, has permissions and the correct role. * <p> * Session management is stateless. */ @RequiredArgsConstructor @EnableWebSecurity @Configuration public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { /** * Service that handles JWT related tasks such as extracting the subject from a JWT token. */ private final JwtUtils jwtUtils; /** * Service for managing user details, which is checked to see that a user exists, is enabled and has appropriate * permission. */ private final UserDetailsServiceImpl userDetailsService; /** * Configures security for the gateway application and thereby the entire system. Cross Site Request Forgery (CSRF) * is disabled. Cross Origin Resource Sharing (CORS) is enabled, allowing requests from other origins. * AntMatchers specify which endpoints each user role has access to, which endpoints are open to the public and * which require that the user is not logged in. * Session is set to stateless. * A filter is run for each request that requires authentication to make sure that the jwt token is supplied in the * header for a valid user that is enabled and has permissions. * When a user goes to the "/login" endpoint, JwtUsernameAndPasswordAuthenticationFilter is run to verify the * credentials that the user supplied to see if the user can be authenticated. * * Worth noting is that attaching the user id to the request header is done in ZuulRequestFilter, not here. * @param http HttpSecurity object used to configure security for the application. * @throws Exception any kind of exception that may occur during any request. */ @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .cors() .and() .authorizeRequests() .antMatchers("/me") .hasAnyAuthority("COMPANY", "CUSTOMER") .antMatchers("/**/v*/api-docs", "/swagger-resources/**", "/webjars/**", "/swagger-ui/**") .permitAll() .antMatchers("/user/register/**") .anonymous() .antMatchers("/confirmation-token/**") .anonymous() .antMatchers("/user") .hasAnyAuthority("CUSTOMER", "COMPANY") .antMatchers(HttpMethod.GET, "/campaign/all/published") .permitAll() .antMatchers("/campaign/discount-code/{campaignId:^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$}") .hasAnyAuthority("CUSTOMER, COMPANY") .antMatchers("/campaign", "/campaign/{campaignId:^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$}") .hasAuthority("COMPANY") .antMatchers("**") .hasAuthority("ADMIN") .anyRequest() .authenticated() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .addFilter(new JwtUsernameAndPasswordAuthenticationFilter(jwtUtils, userDetailsService, authenticationManager())) .addFilterAfter(new JwtTokenValidationFilter(jwtUtils, userDetailsService), JwtUsernameAndPasswordAuthenticationFilter.class) .authorizeRequests(); } /** * Configuration for using a custom user details service * * @param auth authentication manager builder for which to set a custom user details service * @throws Exception if an exception occurs */ @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } /** * CorsConfigurationSource configuration bean * * @return CorsConfigurationSource that accepts any URL source and applies permit values */ @Bean public CorsConfigurationSource corsConfigurationSource() { final CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(ImmutableList.of("*")); configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH")); configuration.setAllowCredentials(true); configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type", "X-Total-Count", "Content-Range")); configuration.setExposedHeaders(ImmutableList.of("Content-Range", "X-Total-Count")); final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }<file_sep>package com.advertisementproject.userservice.api.exception.handler; import com.advertisementproject.userservice.api.exception.EmailAlreadyRegisteredException; import com.advertisementproject.userservice.api.exception.IdentificationNumberException; import com.advertisementproject.userservice.api.exception.EntityNotFoundException; import com.advertisementproject.userservice.api.exception.response.ApiError; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.TypeMismatchException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.lang.NonNull; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Exception handler to provide more clear information to the api user when exceptions occur. Exceptions thrown during * a controller request will return an ApiError response object in a response entity. */ @Slf4j @RestControllerAdvice public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler { /** * Handles showing invalid method argument exceptions to the client * * @param ex the exception that was thrown * @param headers headers for the request * @param status error status * @param request the request that triggered the exception * @return Response entity with an ApiError report */ @Override @NonNull protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { List<String> errors = new ArrayList<>(); for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) { errors.add(fieldError.getField() + ": " + fieldError.getDefaultMessage()); } for (ObjectError globalError : ex.getBindingResult().getGlobalErrors()) { errors.add(globalError.getObjectName() + ": " + globalError.getDefaultMessage()); } return getAndLogApiError(ex.getMessage(), HttpStatus.BAD_REQUEST, errors); } /** * Handles showing invalid type mismatch exceptions to the client * * @param ex the exception that was thrown * @param headers headers for the request * @param status error status * @param request the request that triggered the exception * @return Response entity with an ApiError report */ @Override protected ResponseEntity<Object> handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { log.info(ex.getClass().getName()); // final String error = ex.getValue() + " value for " + ex.getPropertyName() + " should be of type " + ex.getRequiredType(); List<String> errors = Collections.singletonList(error); return getAndLogApiError(ex.getMessage(), HttpStatus.BAD_REQUEST, errors); } /** * Handles showing constraint violation exceptions to the client * * @param ex the exception that was thrown * @return Response entity with an ApiError report */ @ExceptionHandler({ConstraintViolationException.class}) public ResponseEntity<Object> handleConstraintViolation( ConstraintViolationException ex) { List<String> errors = new ArrayList<>(); for (ConstraintViolation<?> violation : ex.getConstraintViolations()) { String violationPath = violation.getPropertyPath().toString(); errors.add(violationPath.substring(violationPath.lastIndexOf('.') + 1) + ": " + violation.getMessage()); } return getAndLogApiError("Field error(s) for request", HttpStatus.BAD_REQUEST, errors); } /** * Handles showing email already registered exceptions to the client * * @param ex the exception that was thrown * @return Response entity with an ApiError report */ @ExceptionHandler({EmailAlreadyRegisteredException.class}) public ResponseEntity<Object> handleConflictError(Exception ex) { return getAndLogApiError(ex, HttpStatus.CONFLICT); } /** * Handles showing user not found exceptions to the client * * @param ex the exception that was thrown * @return Response entity with an ApiError report */ @ExceptionHandler({EntityNotFoundException.class}) public ResponseEntity<Object> handleNotFoundException(Exception ex) { return getAndLogApiError(ex, HttpStatus.NOT_FOUND); } /** * Handles showing bad request exceptions related to personal id number or organization number to the client * * @param ex the exception that was thrown * @return Response entity with an ApiError report */ @ExceptionHandler({IdentificationNumberException.class}) public ResponseEntity<Object> handleCustomBadRequestException(Exception ex) { return getAndLogApiError(ex, HttpStatus.BAD_REQUEST); } /** * Handles showing internal server exceptions to the client * * @param ex the exception that was thrown * @return Response entity with an ApiError report */ @ExceptionHandler({Exception.class}) public ResponseEntity<Object> handleInternalServerError(Exception ex) { return getAndLogApiError(ex, HttpStatus.INTERNAL_SERVER_ERROR); } /** * Helper method for creating a response entity with a ApiError report * * @param ex the exception that was thrown * @param httpStatus the error status * @return Response entity with an ApiError report */ private ResponseEntity<Object> getAndLogApiError(Exception ex, HttpStatus httpStatus) { ApiError apiError = ApiError.builder() .status(httpStatus) .message(ex.getMessage()) .timestamp(Instant.now()) .build(); log.warn(apiError.toString()); return new ResponseEntity<>(apiError, httpStatus); } /** * Helper method for creating a response entity with a ApiError report pertaining to potentially multiple errors * * @param errorMessage a general error message for the errors * @param httpStatus the error status * @param errors a list of errors that occurred * @return Response entity with an ApiError report */ private ResponseEntity<Object> getAndLogApiError(String errorMessage, HttpStatus httpStatus, List<String> errors) { ApiError apiError = ApiError.builder() .status(httpStatus) .message(errorMessage) .timestamp(Instant.now()) .errors(errors) .build(); log.warn(apiError.toString()); return new ResponseEntity<>(apiError, httpStatus); } } <file_sep>package com.advertisementproject.permissionservice.messagebroker.publisher; import com.advertisementproject.permissionservice.db.entity.Permission; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.stereotype.Service; import java.util.UUID; /** * MessagePublisher is a service for publishing messages asynchronously to other microservices via RabbitMQ. * RabbitTemplate is used to send the message and ObjectMapper is used to convert objects to JSON */ @Service @RequiredArgsConstructor public class MessagePublisher { /** * Used to send messages via RabbitMQ message broker. */ private final RabbitTemplate rabbitTemplate; /** * Used to map objects to JSON string so it can be sent as a message. */ private final ObjectMapper objectMapper; /** * Sends a permission object to a fanout exchange so that any microservice that needs to be updated about when * permission is created or updated can receive the update by having a queue connected to the exchange. * * @param permission the permissions object that has been created or updated */ public void sendPermissionMessage(Permission permission) { try { String permissionsString = objectMapper.writeValueAsString(permission); rabbitTemplate.convertAndSend("permission", "", permissionsString); } catch (JsonProcessingException e) { e.printStackTrace(); } } /** * Sends a user id to a fanout exchange so that any microservice that needs to be updated about when * permission is removed for a user can receive the update by having a queue connected to the exchange. * * @param userId the id for the user who's permission has been removed */ public void sendPermissionsDeleteMessage(UUID userId) { rabbitTemplate.convertAndSend("permission.delete", "", userId); } } <file_sep>package com.advertisementproject.userservice.db.config; import com.zaxxer.hikari.HikariDataSource; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Configuration for the data source, controlled by environment variables. */ @Configuration public class DataSourceConfig { /** * Username for the database connection, set through environment variable. */ private final String USERNAME = System.getenv("POSTGRES_USER"); /** * Password for the database connection, set through environment variable. */ private final String PASSWORD = System.getenv("POSTGRES_PASSWORD"); /** * Database connection URL, which is set to postgresql but host and database is set through environment variables. */ private final String URL = "jdbc:postgresql://" + System.getenv("POSTGRES_HOST") + ":5432/" + System.getenv("POSTGRES_DB"); /** * HikariDataSource configuration bean. * * @return a configured hikari data source for connecting to a database. */ @Bean public HikariDataSource hikariDataSource() { return DataSourceBuilder.create() .username(USERNAME) .password(<PASSWORD>) .url(URL) .type(HikariDataSource.class) .build(); } } <file_sep>package com.advertisementproject.permissionservice.exception; /** * Custom RuntimeException for when the requested permission is not found in the database */ public class PermissionNotFoundException extends RuntimeException { /** * Constructor * * @param message the message to be shown for the exception */ public PermissionNotFoundException(String message) { super(message); } }<file_sep>package com.advertisementproject.campaignservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * Campaign Service Application manages campaigns and gets updates from the User Service Application about companies. * Each campaign must be created by a company and company information will be displayed alongside the company in * response to requests. Most endpoints will only be open to users with the COMPANY or ADMIN role but there are some * endpoints with limited information that are open to CUSTOMER users or even the public. * There are scheduled jobs to automatically publish campaigns that are set to be published as well as to remove * expired campaigns from the database. * <p> * Registers with Eureka via @EnableDiscoveryClient. All controller access rights are defined by the Zuul Gateway * application. * * @author <NAME>, <NAME>, <NAME> */ @SpringBootApplication @EnableDiscoveryClient public class CampaignServiceApplication { /** * Runs the application * * @param args optional command line arguments that are currently not implemented */ public static void main(String[] args) { SpringApplication.run(CampaignServiceApplication.class, args); } } <file_sep>package com.advertisementproject.permissionservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * Permission Service Application is a microservice for managing user permissions and informing other microservices * about the state of user permission. The controller endpoints are intended for ADMIN users only as that is a * restricted privilege normal users should not have access to. * <p> * Registers with Eureka via @EnableDiscoveryClient. All controller access rights are defined by the Zuul Gateway * application. * * @author <NAME>, <NAME>, <NAME> */ @EnableDiscoveryClient @SpringBootApplication public class PermissionServiceApplication { /** * Runs the application * * @param args optional command line arguments that are currently not implemented */ public static void main(String[] args) { SpringApplication.run(PermissionServiceApplication.class, args); } } <file_sep>package com.advertisementproject.zuulgateway.db.repositories; import com.advertisementproject.zuulgateway.db.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; import java.util.UUID; /** * Standard JPA Repository for getting and modifying users in the database. Includes option to find a user by email. */ @Repository public interface UserRepository extends JpaRepository<User, UUID> { /** * Retrieves an optional for a user including the user if the email matches, otherwise an empty optional. * * @param email the email for which to retrieve a user optional. * @return user optional containing a user matching the email or an empty optional if there is no match. */ Optional<User> findByEmail(String email); } <file_sep>package com.advertisementproject.zuulgateway.security.Utils; import com.advertisementproject.zuulgateway.security.model.UserDetailsImpl; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.stereotype.Service; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Utilities class for creating JSON Web Tokens (JWT) and extracting the subject from them */ @Service public class JwtUtils { /** * Value for how many hours a jwt token should last before it expires. */ private final Long EXPIRATION_VALUE = 24L; /** * Secret key for signing jwt tokens and extracting data from a jwt token. */ private final String JWT_SECRET = "ABCABCABCABCABCABCABCABCABCABCABCABCABC"; /** * Extracts the subject (user id in our case) from a jwt token. * * @param token the token to extract the subject (user id) from * @return the extracted subject (user id) * @throws io.jsonwebtoken.ExpiredJwtException if the token is expired * @throws io.jsonwebtoken.UnsupportedJwtException if the jwt token format is not supported * @throws io.jsonwebtoken.MalformedJwtException if the jwt token is malformed, typically not including exactly 2 periods * @throws io.jsonwebtoken.SignatureException if the jwt token signature is invalid * @throws IllegalArgumentException if the argument is not a valid string */ public String extractSubject(String token) { return Jwts.parser() .setSigningKey(JWT_SECRET) .parseClaimsJws(token) .getBody() .getSubject(); } /** * Creates a jwt token that expires in 24 hours with authorities from user details as claims and user id from * user details as subject. Signs the token using a HS256 signature algorithm and a secret key. * * @param userDetails user details to get subject and claims from * @return a signed 24 hour token based on user details which can be used to authenticate requests */ public String createToken(UserDetailsImpl userDetails) { Map<String, Object> claims = new HashMap<>(); claims.put("authorities", userDetails.getAuthorities()); String subject = userDetails.getUser().getId().toString(); return Jwts.builder() .setClaims(claims) .setSubject(subject) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS256, JWT_SECRET) .compact(); } /** * Helper method for generating an expiration date * * @return expiration timestamp 24 hours later than current timestamp */ private Date generateExpirationDate() { Instant expiry = Instant.now().plus(EXPIRATION_VALUE, ChronoUnit.HOURS); return Date.from(expiry); } } <file_sep>package com.advertisementproject.userservice.api.request; import lombok.Data; import javax.validation.constraints.NotNull; /** * Request object with information required to register a customer user */ @Data public class CustomerRegistrationRequest { /** * The first name of the customer to be registered. */ @NotNull private final String firstName; /** * The last name of the customer to be registered. */ @NotNull private final String lastName; /** * The personal id of the customer to be registered. */ @NotNull private final String personalIdNumber; /** * The email address for the customer to be registered. */ @NotNull private final String email; /** * The account password for the customer to be registered. */ @NotNull private final String password; /** * The address of the customer to be registered. */ @NotNull private final String address; /** * The city of the customer to be registered. */ @NotNull private final String city; /** * The zip code of the customer to be registered. */ @NotNull private final String zipCode; /** * The phone number to the customer to be registered. */ @NotNull private final String phoneNumber; } <file_sep>package com.advertisementproject.userservice.api.swagger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; /** * Swagger configuration file. Defines a docket bean that includes basic configurations such as base package as well as * API information to display. */ @Configuration public class SwaggerConfig { /** * Docket configuration bean * @return docket with basic configuration and api information */ @Bean public Docket docket() { return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.advertisementproject")) .paths(PathSelectors.any()) .build(); } /** * Defines api information for swagger api documentation * @return ApiInfo object with hard coded api information for this application */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("User Service API") .description("User Service allows for creation and management of users." + "Most users will be company users or customer users, but admin users can be manually created in the database. " + "Registration controller ensures registration of users while user controller manages everything else for users. " + "This service communicates with other services via message broker.") .contact(new Contact("Campaign Company", "http://campaign-company.com", "<EMAIL>")) .version("3.0") .build(); } }<file_sep>package com.advertisementproject.permissionservice.messagebroker.listener; import com.advertisementproject.permissionservice.service.interfaces.PermissionService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Service; import java.util.UUID; /** * MessageListener is a service that listens for messages from other microservices via RabbitMQ and then performs * appropriate actions for the messages received. When a message is sent to the listed queue, the message is received, * logged and handled in the listener method with the help of PermissionService. */ @Slf4j @Service @RequiredArgsConstructor public class MessageListener { /** * Service for managing CRUD operations for Permissions. */ private final PermissionService permissionService; /** * Listens for messages to add permission to a specific user and then adds permission for the user id supplied * * @param userId the user id for which to grant permissions */ @RabbitListener(queues = "#{permissionAddQueue.name}") public void permissionsAddListener(UUID userId) { log.info("[MESSAGE BROKER] Received permissionsAdd message for id: " + userId); permissionService.createPermission(userId); } /** * Listens for messages to remove permission for a specific user and then removes permission for the user id supplied * * @param userId the user id for which to remove permission */ @RabbitListener(queues = "#{permissionDeleteQueue.name}") public void permissionsDeleteListener(UUID userId) { log.info("[MESSAGE BROKER] Received permissionsDelete message for id: " + userId); permissionService.removePermission(userId); } }<file_sep>package com.advertisementproject.userservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * User Service Application registers and manages users. Each user may have a role as a CUSTOMER, COMPANY or ADMIN. * CUSTOMER and COMPANY users will have a customer or company object respectively with the same id as the user id. * ADMIN users have total access, COMPANY has access to do more things than a CUSTOMER and CUSTOMER has limited access * but more access than a client that is not logged in as a user. * In total, this application is responsible for three database tables: users - customer - company * <p> * Whenever this application registers new entities or changes information, it informs other microservices about it. * Currently no other microservice cares about customer information so no update messages are sent for customers. * <p> * Registers with Eureka via @EnableDiscoveryClient. All controller access rights are defined by the Zuul Gateway * application. * * @author <NAME>, <NAME>, <NAME> */ @EnableDiscoveryClient @SpringBootApplication public class UserServiceApplication { /** * Runs the application * * @param args optional command line arguments that are currently not implemented */ public static void main(String[] args) { SpringApplication.run(UserServiceApplication.class, args); } } <file_sep>package com.advertisementproject.campaignservice.db.repository; import com.advertisementproject.campaignservice.db.entity.Company; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.UUID; /** * Standard JPA Repository for getting and modifying companies in the database */ @Repository public interface CompanyRepository extends JpaRepository<Company, UUID> { }
758059c8cc4a3a90973c47b62ad3d18307438d39
[ "HTML", "JavaScript", "Markdown", "Java", "Dockerfile" ]
75
Java
daniel-hughes-nackademin/Microservices-with-jwt
80f32e8ccd7aa3660b8dca5efcbd1d4ae458efa7
c37565c8282c6cb829f2298209dd51660a90dceb
refs/heads/main
<file_sep># Hellhound Heresy A visual novel about tarot cards and hellhounds Created for Mini Jam #69 <file_sep>/* Tarot card class Holds information about a tarot card (name, meaning, etc.) */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class TarotCard : MonoBehaviour { [SerializeField] private string name_of_card = ""; // The name of the card [SerializeField] private string card_meaning_folder = ""; // Where the files with the card's meanings are stored // The current filename format for cards is [Name of Card] + Upright / Reversed. To avoid clogging up the Inspector, the values of the file names are initialized in Awake, but if you wanted to change the file names, you could add the [SerializeField] attribute instead. private string card_upright_meaning_file = ""; private string card_reversed_meaning_file = ""; private GameManager game_manager = null; // Need this reference in order to show card meanings in the dialogue box private CardManager card_manager = null; // Need this reference to do a UI effect private void Awake () { game_manager = GameObject.FindObjectOfType<GameManager>().GetComponent<GameManager>(); card_manager = GameObject.FindObjectOfType<CardManager>().GetComponent<CardManager>(); card_upright_meaning_file = name_of_card + "Upright"; card_reversed_meaning_file = name_of_card + "Reversed"; } // Represents the player selecting this card public void ChooseCard () { StartCoroutine(ShowCardMeaning()); } // Reveal the card's meaning in the dialogue box private IEnumerator ShowCardMeaning() { game_manager.RecordCardName(name_of_card); yield return StartCoroutine(card_manager.FocusOnSelectedCard(this.gameObject)); yield return StartCoroutine(game_manager.ShowCardChoices(card_meaning_folder + card_upright_meaning_file, card_meaning_folder + card_reversed_meaning_file)); } } <file_sep>/* UI Effect Manager Handles various UI effects, such as fade-ins or parallax */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIEffectManager : MonoBehaviour { // Fade an image in or out public IEnumerator FadeImage (Image image, float total_time, Color a, Color b, bool reverse) { if (reverse) { Color tmp = a; a = b; b = tmp; } float elapsed_time = 0; // How much time has passed while (elapsed_time < total_time) { elapsed_time += Time.deltaTime; if (image != null) image.color = Color.Lerp(a, b, elapsed_time / total_time); yield return null; } } // Fade a list of images in or out public IEnumerator FadeImage (Transform transform, float total_time, Color a, Color b, bool reverse) { foreach (Transform child in transform) { StartCoroutine(FadeImage(child.GetComponent<Image>(), total_time, a, b, reverse)); } yield return null; } // Move an object to create a parallax effect public void MoveObjectBasedOnMousePosition(GameObject object_to_move, Vector2 center_point, Vector2 mouse_position, float distance, float max_distance) { object_to_move.transform.position = new Vector2(center_point.x + Mathf.Clamp(mouse_position.x * distance, -max_distance, max_distance), center_point.y + Mathf.Clamp(mouse_position.y * distance, -max_distance, max_distance)); } } <file_sep>/* Dialogue Box Manager Updates information in the dialogue box, such as the character's name or speech */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class DialogueBoxManager : MonoBehaviour { [SerializeField] private TextMeshProUGUI name_box = null; // Where the character's name is displayed in the UI [SerializeField] private TextMeshProUGUI dialogue_box = null; // Where the character's speech is displayed in the UI // Update the character name displayed in the text box public void UpdateCharacterName (string name) { name_box.text = name; } // Update dialogue public IEnumerator UpdateDialogue(string speech) { do { dialogue_box.text = speech; yield return null; } while (!Input.GetKeyDown(KeyCode.Mouse0) && !Input.GetKey(KeyCode.Mouse1)); // To be later updated with a keybinding of the user's choice. } // Clear the dialogue box of names and speeches public void ClearBox() { UpdateCharacterName(""); dialogue_box.text = ""; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { [SerializeField] private string[] main_dialogue_filenames; // Contains all dialogue file locations [SerializeField] private string[] correct_card_names; // Contains the names of the correct cards [SerializeField] private string[] order_of_hounds; // The order of the hounds [SerializeField] private int[] hound_checkpoint_counts; // Each hound has a number of checkpoints --> use this to keep track of failures. The length of hound_checkpoint_counts should be the same as order_of_hounds. [SerializeField] private string failure_message_folder; // Where the failure messages are stored [SerializeField] private string ending_folder; // Where the endings are stored [SerializeField] private string good_ending_file; // Where the "good" ending is stored [SerializeField] private string bad_ending_file; // Where the normal "bad" ending is stored [SerializeField] private string bad_ending_file_2; // Where the variant "bad" ending is stored [SerializeField] private int number_of_chances = 3; // The max number of chances we have before it's game-over private ContentManager content_manager = null; private ButtonManager button_manager = null; private CardManager card_manager = null; private CutsceneManager cutscene_manager = null; [SerializeField] private LivesSystem lives_system = null; private bool allow_reversed = false; // Allows the player to present a card reversed private int file_index = 0; // Which file are we starting with private int card_index = 0; // Which answer are we checking private int hound_index = 0; // Which hound we're looking at private int hound_checkpoint = 0; // Which index are we looking at private int mistake_checkpoint = 0; // How many wrong choices have we made in the game? private int repeat_checkpoint = 0; // Are we repeating the same choice? private string last_chosen_card = ""; // The name of the previously chosen card private string current_chosen_card = ""; // The name of the card chosen private void Start() { content_manager = this.GetComponent<ContentManager>(); button_manager = this.GetComponent<ButtonManager>(); card_manager = this.GetComponent<CardManager>(); cutscene_manager = this.GetComponent<CutsceneManager>(); StartCoroutine(PlayIntro()); } // Play the introduction sequence public IEnumerator PlayIntro () { yield return StartCoroutine(content_manager.ProcessContent(main_dialogue_filenames[file_index], 0)); yield return StartCoroutine(cutscene_manager.ShowTransitionScreen()); file_index += 1; yield return StartCoroutine(content_manager.ProcessContent(main_dialogue_filenames[file_index], 0)); } // Reveal the available cards public IEnumerator ShowCardChoices(string path_to_upright, string path_to_reversed) { card_manager.EnableCards(false); yield return StartCoroutine(content_manager.ProcessContent(path_to_upright, 0)); if (allow_reversed) yield return StartCoroutine(content_manager.ProcessContent(path_to_reversed, 0)); button_manager.ShowButtons(true, allow_reversed); } // Record a card's name so we can check it later public void RecordCardName(string card_name) { current_chosen_card = card_name; } // Check the card and make sure it's correct public IEnumerator CheckCard (string card_state) { card_manager.ResetCards(); button_manager.ShowButtons(false, false); // Example player_response: ZuckerborkSunUpright0 string player_response = order_of_hounds[hound_index] + current_chosen_card + card_state + hound_checkpoint; if (player_response == correct_card_names[card_index]) { yield return StartCoroutine(PlayNextMessage(player_response)); yield return null; } else if (repeat_checkpoint + mistake_checkpoint + 1 > number_of_chances) { yield return StartCoroutine(PlayFailureMessage(player_response)); if (last_chosen_card == current_chosen_card) yield return StartCoroutine(content_manager.ProcessContent(new string[] {ending_folder + bad_ending_file_2, ending_folder + bad_ending_file}, 0)); else yield return StartCoroutine(content_manager.ProcessContent(ending_folder + bad_ending_file, 0)); cutscene_manager.PlayBadEnding(); } else yield return StartCoroutine(PlayFailureMessage(player_response)); last_chosen_card = current_chosen_card; } // If the choice was right, play the next piece of dialogue private IEnumerator PlayNextMessage(string state) { file_index += 1; yield return StartCoroutine(content_manager.ProcessContent(failure_message_folder + state + "a", 0)); if (file_index > main_dialogue_filenames.Length - 1) { yield return StartCoroutine(content_manager.ProcessContent(ending_folder + good_ending_file, 0)); cutscene_manager.PlayGoodEnding(); } else { StartCoroutine(content_manager.ProcessContent(main_dialogue_filenames[file_index], 0)); UpdateCheckpoint(); } } // If the choice was wrong, play the unique failure message for that card private IEnumerator PlayFailureMessage(string state) { yield return StartCoroutine(content_manager.ProcessContent(failure_message_folder + state + "a", 0)); if (repeat_checkpoint + mistake_checkpoint + 1 > number_of_chances) { yield return StartCoroutine(content_manager.ProcessContent(failure_message_folder + state + "b", 0)); } // Check if this is a situation where we chose the same card again else if (last_chosen_card == current_chosen_card) { yield return StartCoroutine(content_manager.ProcessContent(failure_message_folder + order_of_hounds[hound_index] + "Repeat" + repeat_checkpoint, 0)); button_manager.GoBackToCards(); repeat_checkpoint += 1; } else { yield return StartCoroutine(content_manager.ProcessContent(new string[]{failure_message_folder + state + "b", failure_message_folder + order_of_hounds[hound_index] + "Mistake" + mistake_checkpoint}, 0)); mistake_checkpoint += 1; button_manager.GoBackToCards(); } lives_system.RemoveLife(); } // Update the checkpoints so that they match the flow of the story private void UpdateCheckpoint() { if (hound_checkpoint > hound_checkpoint_counts[hound_index]) { if (hound_index < order_of_hounds.Length - 1) { hound_checkpoint = 0; mistake_checkpoint = 0; repeat_checkpoint = 0; last_chosen_card = ""; hound_index += 1; card_index += 1; } } else { hound_checkpoint += 1; card_index += 1; if (hound_checkpoint == 1) allow_reversed = true; } } // Get the name of the current hound public string GetCurrentHound() { return order_of_hounds[hound_index]; } } <file_sep>// Handles the card display using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CardManager : MonoBehaviour { [SerializeField] private GameObject card_display = null; // The GameObject that the cards will be parented to [SerializeField] private string card_folder_path = null; // The path to the folder that holds the cards in the project hierarchy [SerializeField] private float fade_duration = 0f; // How long does it take for a card to fade-in or fade-out? private string[] last_known_cards = null; // The last known cards displayed on-screen private bool last_known_card_state = false; // The last known card state (interactable / not interactable) private Color original_color = Color.white; private UIEffectManager ui_effect_manager = null; // Needed to fade-in the cards // Initialize UIEffectManager private void Awake() { ui_effect_manager = this.GetComponent<UIEffectManager>(); original_color = card_display.GetComponent<Image>().color; } // Display a set of cards on screen public IEnumerator ShowCards (string[] card_names) { foreach (string c in card_names) { Button card = Instantiate(Resources.Load<Button>(card_folder_path + c)); if (card != null) { card.transform.SetParent(card_display.transform, false); } } EnableCards(false); // Don't allow a player to click on a card while the effect occurs yield return StartCoroutine(ui_effect_manager.FadeImage(card_display.transform, fade_duration, new Color(0f, 0f, 0f, 0f), Color.white, false)); card_display.SetActive(true); RecordCardNames(card_names); // Needed for the back button --> otherwise we don't know what cards we presented last time. } // Determines whether the player can interact with the cards public void EnableCards (bool make_cards_interactable) { foreach (Transform child in card_display.transform) { child.GetComponent<Button>().enabled = make_cards_interactable; } RecordInteractivity(make_cards_interactable); } // Display a set of cards on-screen based on previously known information // Do NOT use this version of the method if you want to present a new set of choices -- only the previously recorded set is displayed public void ShowCards () { StartCoroutine(ShowCards(last_known_cards)); EnableCards(last_known_card_state); } // Remove all cards from the screen public void ResetCards () { foreach (Transform child in card_display.transform) { GameObject.Destroy(child.gameObject); } card_display.SetActive(false); } // Records information about the cards and whether they were interactive or not // This is information is being used for method overloading private void RecordCardNames (string[] card_names) { last_known_cards = card_names; } // Records information about the cards and whether they were interactive or not // This is information is being used for method overloading private void RecordInteractivity (bool make_cards_interactable) { last_known_card_state = make_cards_interactable; } // Focus on the selected card (UI Effect) public IEnumerator FocusOnSelectedCard (GameObject card) { if (card_display.transform.childCount <= 1) yield return null; else { yield return StartCoroutine(ui_effect_manager.FadeImage(card_display.transform, fade_duration, new Color(0f, 0f, 0f, 0f), Color.white, true)); foreach (Transform child in card_display.transform) { if (child.gameObject != card) child.gameObject.SetActive(false); } yield return StartCoroutine(ui_effect_manager.FadeImage(card.GetComponent<Image>(), fade_duration, new Color(0f, 0f, 0f, 0f), Color.white, false)); } } // Disable the card display background // This is use for a mini-cutscene public void DisableCardDisplayBackground(bool disable_card_background) { if (disable_card_background) card_display.GetComponent<Image>().color = new Color(0f, 0f, 0f, 0f); else card_display.GetComponent<Image>().color = original_color; } }<file_sep>/* Button Manager Controls which buttons are displayed on-screen */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ButtonManager : MonoBehaviour { [SerializeField] private GameObject button_display = null; // The object that displays the presentation buttons. [SerializeField] private GameObject reversed_button = null; // The button that allows the player to display a card reversed private CardManager card_manager = null; private GameManager game_manager = null; private void Awake() { card_manager = this.GetComponent<CardManager>(); game_manager = this.GetComponent<GameManager>(); } // Display the buttons on-screen public void ShowButtons(bool show_buttons, bool show_reversed) { reversed_button.SetActive(show_reversed); button_display.SetActive(show_buttons); } // Button that allows the player to present the card in its upright position public void PresentCardUpright() { StartCoroutine(game_manager.CheckCard("Upright")); } // Button that allows the player to present the card in its reversed position public void PresentCardReversed() { StartCoroutine(game_manager.CheckCard("Reversed")); } // Back button function: Return to the card selection screen public void GoBackToCards() { card_manager.ResetCards(); card_manager.ShowCards(); card_manager.EnableCards(true); ShowButtons(false, false); } } <file_sep>/* CutsceneManager Handles the intro transition and game-over screens Current Endings: - Bad Ending (Make too many mistakes) - Good Ending */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class CutsceneManager : MonoBehaviour { [SerializeField] private Image transition_background = null; // The background of the game-over screen [SerializeField] private TextMeshProUGUI game_over_title = null; // What the game-over screen says [SerializeField] private Button quit_button = null; // Reference to the quit button [SerializeField] private TextMeshProUGUI button_label = null; // What the button says [SerializeField] private float transition_duration = 0f; // How long the transition screen fade-in lasts private UIEffectManager ui_effect_manager = null; // Needed to fade in the transition screen private Color original_color = Color.white; // The original color of the background private void Awake() { ui_effect_manager = this.GetComponent<UIEffectManager>(); original_color = transition_background.color; } // Show the intro public IEnumerator ShowTransitionScreen() { yield return StartCoroutine(ui_effect_manager.FadeImage(transition_background, transition_duration, original_color, new Color(0f, 0f, 0f, 0f), false)); transition_background.gameObject.SetActive(false); // Need to disable this object or else we can't interact with the cards } // Show the game over screen private IEnumerator ShowGameOverScreen() { yield return StartCoroutine(ui_effect_manager.FadeImage(transition_background, transition_duration, transition_background.color, original_color, false)); game_over_title.gameObject.SetActive(true); quit_button.gameObject.SetActive(true); } // Show the good ending public void PlayGoodEnding() { transition_background.gameObject.SetActive(true); game_over_title.text = "<b><size=120%><font=\"SawarabiGothic\">Fortune Favors the Bold</b></font>\n<size=85%>Zuckerbork enjoyed your reading, but you still have a long way to go.</size>"; button_label.text = "To be continued another time"; StartCoroutine(ShowGameOverScreen()); } // Show the bad ending public void PlayBadEnding() { transition_background.gameObject.SetActive(true); game_over_title.text = "<b><size=120%><font=\"SawarabiGothic\">A Tragic Demise</b></font>\n<size=85%>You died, but at least you satiated a hound's hunger.</size>"; button_label.text = "The end"; StartCoroutine(ShowGameOverScreen()); } } <file_sep>/* Sprite Manager Handles tasks related to sprite swapping */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SpriteManager : MonoBehaviour { [SerializeField] private string background_image_folder; // The folder where background sprites are stored [SerializeField] private string character_image_folder; // The folder where character sprites are stored [SerializeField] private Image background_image; // The background image object [SerializeField] private Image character_image; // The character image object // Update the background image public void UpdateBackground(string background_image_name) { Sprite bg = Resources.Load<Sprite>(background_image_folder + background_image_name); if (bg != null) background_image.sprite = bg; } // Update the character image public void UpdateCharacter(string character, string emotion_image_name) { Sprite ch = Resources.Load<Sprite>(character_image_folder + character + "/" + emotion_image_name); if (ch != null) character_image.sprite = ch; } } <file_sep>/* Lives System Updates the UI to show how many lives (also referred to in other scripts as chances) are left */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class LivesSystem : MonoBehaviour { [SerializeField] private GameObject lives_ui = null; public void RemoveLife() { int number_of_children = lives_ui.transform.childCount; if (number_of_children > 0) Destroy(lives_ui.transform.GetChild(number_of_children - 1).gameObject); } } <file_sep>/* Content Manager Processes a .txt file */ using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ContentManager : MonoBehaviour { [SerializeField][MinAttribute(0)] private int temp_size = 128; // Represents the max size of the content holder private ContentParser content_parser = null; private DialogueBoxManager dialogue_box_manager = null; private CardManager card_manager = null; private GameManager game_manager = null; private SpriteManager sprite_manager = null; private bool cutscene_enabled = false; private string last_recorded_cutscene = ""; private void Awake() { content_parser = this.GetComponent<ContentParser>(); dialogue_box_manager = this.GetComponent<DialogueBoxManager>(); card_manager = this.GetComponent<CardManager>(); game_manager = this.GetComponent<GameManager>(); sprite_manager = this.GetComponent<SpriteManager>(); } // Travels through the dialogue line-by-line and processes information // public IEnumerator ProcessContent(string[] file_names, int file_index, int file_line_index) public IEnumerator ProcessContent(string file_name, int file_line_index) { string[] temp_lines = new string[temp_size]; // for (int i = file_index; i < file_names.Length; ++i) // { // temp_lines = content_parser.GetContent(file_names[i]); temp_lines = content_parser.GetContent(file_name); foreach (string line in temp_lines) { // If the line is null or empty, there's nothing to match if (string.IsNullOrEmpty(line)) continue; // Chose to cache results so we don't call functions multiple times string scene = content_parser.GetScene(line); string character = content_parser.GetCharacter(line); string dialogue = content_parser.GetDialogue(line); string emotion = content_parser.GetEmotion(line); string choices = content_parser.GetChoices(line); string cutscene = content_parser.GetCutscene(line); // Assume that a match was found if (!string.IsNullOrEmpty(scene)) { sprite_manager.UpdateBackground(scene); } if (!string.IsNullOrEmpty(emotion)) { sprite_manager.UpdateCharacter(game_manager.GetCurrentHound(), emotion); } if (!string.IsNullOrEmpty(cutscene)) { /*yield return StartCoroutine(card_manager.ShowCards(Regex.Split(cutscene.Replace(" ", string.Empty), "\\|\\|"))); card_manager.EnableCards(false); card_manager.DisableCardDisplayBackground(true);*/ SaveCutscene(cutscene); cutscene_enabled = true; } if (!string.IsNullOrEmpty(choices)) { dialogue_box_manager.ClearBox(); yield return StartCoroutine(card_manager.ShowCards(Regex.Split(choices.Replace(" ", string.Empty), "\\|\\|"))); card_manager.EnableCards(true); continue; } if (!string.IsNullOrEmpty(character)) dialogue_box_manager.UpdateCharacterName(character); if (!string.IsNullOrEmpty(dialogue)) { if (cutscene_enabled) { yield return StartCoroutine(card_manager.ShowCards(Regex.Split(last_recorded_cutscene.Replace(" ", string.Empty), "\\|\\|"))); card_manager.EnableCards(false); card_manager.DisableCardDisplayBackground(true); } yield return StartCoroutine(dialogue_box_manager.UpdateDialogue(dialogue)); if (cutscene_enabled) { card_manager.ResetCards(); card_manager.DisableCardDisplayBackground(false); cutscene_enabled = false; } }; } dialogue_box_manager.ClearBox(); } public IEnumerator ProcessContent(string[] file_names, int file_line_index) { foreach (string file in file_names) { yield return StartCoroutine(ProcessContent(file, file_line_index)); } } // Save information about the cutscene so we care fire it with the next line of dialogue private void SaveCutscene(string cutscene) { last_recorded_cutscene = cutscene; } } <file_sep>/* Moving UI Script for moving UI elements (such as the background) */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovingUI : MonoBehaviour { [SerializeField] private UIEffectManager ui_effect_manager = null; [SerializeField] private float distance = 0f; // How far this element should move [SerializeField] private float max_distance = 0f; // How far the element can move private Vector2 center_point; // Where the object is located relative to the scene at the start of the game private void Start() { center_point = this.transform.position; } private void Update() { if (ui_effect_manager != null) { Vector2 mouse_position = Camera.main.ScreenToViewportPoint(Input.mousePosition); ui_effect_manager.MoveObjectBasedOnMousePosition(this.gameObject, center_point, mouse_position, distance, max_distance); } } } <file_sep>/* GameOverButtons Implements functionality for the button on the game-over screen */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameOverButtons : MonoBehaviour { public void ReturnToMainMenu() { SceneManager.LoadScene(0); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseManager : MonoBehaviour { private static MouseManager mouse; [SerializeField] private Texture2D cursor_sprite = null; private void Awake() { if (mouse != null && mouse != this) Destroy (this.gameObject); else { Cursor.SetCursor(cursor_sprite, Vector2.zero, CursorMode.Auto); mouse=this; } } } <file_sep>/* Content Parser Gets information from a .txt. file and returns the content stored inside it */ using System.Text.RegularExpressions; // Necessary for Regex using System.Collections; using System.Collections.Generic; using UnityEngine; public class ContentParser : MonoBehaviour { /* Script formatting notes: <<This is where you put a scene name (no quotes allowed)>> Character name goes here: "Dialogue is here." [Emotions are here] ((Choices are indiciated like this || and separated like this)) {{Cutscene cards are indiciated like this || and separated like this}} --> This syntax will show cards on-screen but disable their interactivity. */ private Regex scene_regex = new Regex("^<<(?!(:|\"))(?'scene'.*)>>$", RegexOptions.Compiled); private Regex char_regex = new Regex("^(?'character'.*?):", RegexOptions.Compiled); private Regex dialogue_regex = new Regex("(\"|\')(?'dialogue'.*)(\"|\')", RegexOptions.Compiled); private Regex emotion_regex = new Regex("(?!\\B\"[^\"]*)\\[(?'emotion'.*)\\](?![^\"]*\"\\B)", RegexOptions.Compiled); private Regex choice_regex = new Regex("^\\(\\((?!(:|\"))(?'choice'.*)\\)\\)$", RegexOptions.Compiled); private Regex cutscene_regex = new Regex("^{{(?!(:|\"))(?'cutscene'.*)}}$"); // Returns the lines listed in a .txt file // We assume that valid paths refer to locations relative to Resources, not Assets public string[] GetContent (string file_name) { TextAsset text = Resources.Load<TextAsset>(file_name); try { return Regex.Split(text.text, "\n|\r|\r\n"); } catch { Debug.LogError("Warning: ContentParser failed to read " + file_name); return new string[0]; } } public string GetScene (string line) { return FindRegexMatch(line, scene_regex, "scene"); } public string GetCharacter (string line) { return FindRegexMatch(line, char_regex, "character"); } public string GetDialogue (string line) { return FindRegexMatch(line, dialogue_regex, "dialogue"); } public string GetEmotion (string line) { return FindRegexMatch(line, emotion_regex, "emotion"); } public string GetChoices (string line) { return FindRegexMatch(line, choice_regex, "choice"); } public string GetCutscene (string line) { return FindRegexMatch(line, cutscene_regex, "cutscene"); } private string FindRegexMatch(string line, Regex pattern, string group_name) { if (!pattern.IsMatch(line)) return ""; GroupCollection groups = pattern.Match(line).Groups; return groups[group_name].Value; } }
c2ec274e9db4858c6301821be4b2583a23eee0fd
[ "Markdown", "C#" ]
15
Markdown
something999/HellhoundVN
f666b73dd664ae4c25771e44a9e2b785ac13e457
f07c3dc7c61ca12901cf284cf70da3588979e975
refs/heads/master
<repo_name>andreaspreuss/build-recipes<file_sep>/nextcloud/nextcloud-server.files/B_DEBIAN/DEBIAN/postinst #!/bin/bash cd /var/www/nextcloud mkdir data chown -R www-data: apps data config
1b98cf1d27d37b3d0d27cfe5a5b592291f14e689
[ "Shell" ]
1
Shell
andreaspreuss/build-recipes
e79e6b0c6cd7baadddbd4277461664952739960a
fb409bd1cc253953cb943c3a02c85f79ab3863be
refs/heads/master
<repo_name>bbhunter/cname<file_sep>/cname.py import sys import queue import threading import dns.resolver from dns.rcode import to_text from dns.exception import DNSException from colorama import Fore, init #enable coloring on win try: import win_unicode_console win_unicode_console.enable() init() except ImportError: pass #queue and lock var domains = queue.Queue() lock = threading.Lock() # reading args try: sublist = sys.argv[1] except IndexError: sublist = "" # reading file try: subfile = open(sublist, 'r') except IOError: subfile = sublist.split(",") # setting dns resolver my_resolver = dns.resolver.Resolver() my_resolver.nameservers = ['8.8.8.8'] # populate queue with domains for sub in subfile: domains.put(sub.strip()) try: subfile.close() except AttributeError: pass # checking cname def Check(domain): try: answer = my_resolver.query(domain, 'CNAME') for data in answer: with lock: cname_string = str(data.target).rstrip(".") #cname_error = to_text(answer.response.rcode()).lower() print("{0:30}{1} -->\t {2}{3}".format(domain, Fore.LIGHTBLUE_EX, Fore.RESET, cname_string)) except DNSException: pass domains.task_done() # starting threads while not domains.empty(): domain = domains.get() try: threading.Thread(target=Check,args=(domain,)).start() # avoid thread start error except RuntimeError: domains.task_done() domains.put(domain) # wait until all threads done domains.join() <file_sep>/README.md ## Installation - `git clone https://github.com/melbadry9/cname.git` - `pip3 -r install requirements.txt` ## Usage - `python3 cname.py file.txt` - `python3 cname.py domain.com,example.com` ## Donation [![Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://buymeacoffee.com/melbadry9)
33acac63e2043f6ab0b51f4d7ee578bb50f2efcf
[ "Markdown", "Python" ]
2
Python
bbhunter/cname
f13d0b894cb5fd26ff85677f0766aebe60dda513
c5299f63a0caa1a0203b92c34ab02ab703c2cbf8
refs/heads/master
<file_sep>import os import datetime import tarfile import pysftp sftp_user = 'sftpuser' sftp_password = '<PASSWORD>' sftp_host = '172.16.31.10' sftp_port = 22 documentroot = '/htdocs' documentroot = '/htdocs' def upload(archiveName): with pysftp.Connection(username=sftp_user,port=sftp_port,host=sftp_host,password=sftp_password) as sftp: sftp.put(archiveName) for directory in os.listdir(documentroot): objectmethod = datetime.datetime.now() abspath = os.path.join(documentroot,directory) timestamp = '{}-{}-{}-{}-{}'.format(objectmethod.day,objectmethod.month,objectmethod.year,objectmethod.hour,objectmethod.minute) filename = '/tmp/backup/{}-{}.tar.gz'.format(directory,timestamp) with tarfile.open(filename,'w:gz') as tar: os.chdir(abspath) tar.add('.') upload(filename) os.remove(filename) <file_sep># Create the backup of website files and store at the remote backup server The below code can backup the files from a user specified directory to a user specified tar.gz file in a preferred location using python code. ## Tasks - List the directories which need to take the backup. - Find out the absolute path of the directories - Create the time stamp and tar.gz file within the specified directory - Change the absolute path of the directory and copy the content - Creating an sftp server - Creating paysft connection - Upload the backup file to the remote backup server and remove the same from the source server. ### List the directories which need to take the backup. Here I am going take list the direcory to take the backup under the directory /htdocs. ```python import os documentroot = '/htdocs' for directory in os.listdir(documentroot): print(directory) ``` ### Result ```bash ubuntu@/:~$ python3 listdirectory.py zerocover.net landmark.com ubuntu@/:~$ ``` ### Find out the absolute path of the directories ```python import os documentroot = '/htdocs' for directory in os.listdir(documentroot): abspath = os.path.join(documentroot,directory) print(abspath) ``` ### Result ```bash ubuntu@/:~$ python3 absolutepath.py /htdocs/zerocover.net /htdocs/landmark.com ``` ### Create the time stamp and tar.gz file within the specified directory The backup file is stored with the creating time. Here I am creating timestamp with the format date-month-year-minute-hour and place the directory in the /tmp/backup/ folder. To create a timestamp and tar file, we need to initialize the module datetime and tarfile. ```python import os import datetime import tarfile documentroot = '/htdocs' for directory in os.listdir(documentroot): objectmethod = datetime.datetime.now() abspath = os.path.join(documentroot,directory) timestamp = '{}-{}-{}-{}-{}'.format(objectmethod.day,objectmethod.month,objectmethod.year,objectmethod.hour,objectmethod.minute) filename = '/tmp/backup/{}-{}.tar.gz'.format(directory,timestamp) with tarfile.open(filename,'w:gz') as tar: print(tar) ``` ### Result ``` ubuntu@/:/tmp/backup$ pwd /tmp/backup ubuntu@/:/tmp/backup$ ll total 20 -rw-rw-r-- 1 ubuntu ubuntu 77 Aug 15 06:57 landmark.com-15-8-2019-6-57.tar.gz -rw-rw-r-- 1 ubuntu ubuntu 78 Aug 15 06:57 zerocover.net-15-8-2019-6-57.tar.gz ubuntu@/:/tmp/backup$ du -sch landmark.com-15-8-2019-6-57.tar.gz 4.0K landmark.com-15-8-2019-6-57.tar.gz 4.0K total ``` ### Change the absolute path of the directory and copy the content Here I am going to change the absolute path of the directory the current location of the files and copy all content to the backup file. ```python import os import datetime import tarfile documentroot = '/htdocs' for directory in os.listdir(documentroot): objectmethod = datetime.datetime.now() abspath = os.path.join(documentroot,directory) timestamp = '{}-{}-{}-{}-{}'.format(objectmethod.day,objectmethod.month,objectmethod.year,objectmethod.hour,objectmethod.minute) filename = '/tmp/backup/{}-{}.tar.gz'.format(directory,timestamp) with tarfile.open(filename,'w:gz') as tar: os.chdir(abspath) tar.add('.') ``` ### Result ```bash ubuntu@/:/tmp/backup$ ll total 21704 -rw-rw-r-- 1 ubuntu ubuntu 532 Aug 15 07:08 backup.py -rw-rw-r-- 1 ubuntu ubuntu 11098489 Aug 15 07:09 landmark.com-15-8-2019-7-9.tar.gz -rw-rw-r-- 1 ubuntu ubuntu 11111050 Aug 15 07:09 zerocover.net-15-8-2019-7-9.tar.gz ubuntu@/:/tmp/backup$ du -sch landmark.com-15-8-2019-7-9.tar.gz 11M landmark.com-15-8-2019-7-9.tar.gz 11M total ``` ### Creating sftp server You can create the FTP user at the remote backup server with the password authentication privillage. ```bash sudo useradd sftpuser $ sudo passwd sftpuser Changing password for user sftpuser. New password: Retype new password: passwd: all authentication tokens updated successfully. sudo vim /etc/ssh/sshd_config # To disable tunneled clear text passwords, change to no here! PasswordAuthentication yes #PermitEmptyPasswords no #PasswordAuthentication no ``` ### Creating pysftp connection ``` import pysftp sftp_user = 'sftpuser' sftp_password = '<PASSWORD>' sftp_host = '172.31.21.199' sftp_port = 22 sftp = pysftp.Connection(username=sftp_user,port=sftp_port,host=sftp_host,password=sftp_password) sftp.put('/tmp/backupname') sftp.close() ``` ### Upload the backup file to the remote backup server and remove the same from the source server ```python import os import datetime import tarfile import pysftp sftp_user = 'sftpuser' sftp_password = '<PASSWORD>' sftp_host = '192.168.3.11' sftp_port = 22 documentroot = '/htdocs' documentroot = '/htdocs' def upload(archiveName): with pysftp.Connection(username=sftp_user,port=sftp_port,host=sftp_host,password=<PASSWORD>) as sftp: sftp.put(archiveName) for directory in os.listdir(documentroot): objectmethod = datetime.datetime.now() abspath = os.path.join(documentroot,directory) timestamp = '{}-{}-{}-{}-{}'.format(objectmethod.day,objectmethod.month,objectmethod.year,objectmethod.hour,objectmethod.minute) filename = '/tmp/backup/{}-{}.tar.gz'.format(directory,timestamp) with tarfile.open(filename,'w:gz') as tar: os.chdir(abspath) tar.add('.') upload(filename) os.remove(filename) ``` ### Result ```bash [sftpuser@/ ~]$ ll total 21692 -rw-rw-r-- 1 sftpuser sftpuser 11098489 Aug 15 08:04 landmark.com-15-8-2019-8-4.tar.gz -rw-rw-r-- 1 sftpuser sftpuser 11111050 Aug 15 08:04 zerocover.net-15-8-2019-8-4.tar.gz [sftpuser@/ ~]$ ```
0f9f26a42e1d89d0dab4e8cb6a588941e4304a88
[ "Markdown", "Python" ]
2
Python
Syamlal-M/backup-process-
00e8ad90665bf1db3ebeec0e5174541725a101fc
f90b8cbdebc620274d86fdeba8129598696a788b
refs/heads/master
<repo_name>rk-react-dev/Flight-Details<file_sep>/src/sagas/rootSagas.js import { call, put, takeEvery } from 'redux-saga/effects' import {fetchCheapFlightDetails, fetchBusinessFlightDetails} from './api' import {saveFlightDetails} from '../actions/index' function* fetchData(action) { try { const flightDetailsCheap = yield call(fetchCheapFlightDetails); const flightDetailsBussiness = yield call(fetchBusinessFlightDetails); const busiData=flightDetailsBussiness.data.map((flight, index)=>{ return { route : flight.departure +'-'+ flight.arrival, departure : flight.departureTime, arrival : flight.arrivalTime } }) const AllFlightdetails=[...flightDetailsCheap.data, ...busiData]; yield put(saveFlightDetails(AllFlightdetails)); } catch (e) { // yield put({type: "USER_FETCH_FAILED", message: e.message}); } } function* rootSagas() { yield takeEvery("FETCH_FLIGHT_DETAILS", fetchData); } export default rootSagas;<file_sep>/src/reducers/rootReducer.js import _ from 'lodash'; const initialState = { flightDetails: [], pageWiseFlights: [], totalPages: 0, pageSize: 10, } function rootReducer(state = initialState, action) { switch (action.type) { case 'GET_FLIGHT_DETAILS': const flightDetails = action.payload; const pageWiseFlights = _.chunk(flightDetails, state.pageSize); const totalPages=flightDetails.length/10; return { ...state, flightDetails: flightDetails, pageWiseFlights: pageWiseFlights, totalPages: totalPages} default: return state; } } export default rootReducer;<file_sep>/README.md # Flight Details application In this project we can see flights details, filtering, seraching.<br /><br /> We can add new Flight details. ​ ## `How to setup the code base` ​ ### `cloning the repo` ​ fire following command to clone the repo ``` git clone https://github.com/rk-react-dev/Flight-Details.git ``` ​ ### `Installing required packages` ``` npm install ``` Fire above command in command prompt by using project folder. It will install required packages. ​ ### `Running the Application` ​ fire the below command in context to current project folder to start the application ``` npm start ``` ​ Runs the app in the development mode.<br /> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. ​ The page will reload if you make edits.<br /> You will also see any lint errors in the console. ​ ### `Testing the code` ​ ``` npm test ``` Launches the test runner in the interactive watch mode.<file_sep>/src/actions/index.js export const saveFlightDetails = payload => ({ type: 'GET_FLIGHT_DETAILS', payload })<file_sep>/src/App.js import React from 'react'; import './App.css'; import FlightDetails from './components/FlightDetails' import AddFlight from './components/AddFlight' import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; function App() { return ( <Router> <div> <nav> <ul> <li> <Link to="/">Flight Details</Link> </li> <li> <Link to="/flightDetails">AddFlight</Link> </li> </ul> </nav> <Switch> <Route path="/flightDetails"> <AddFlight /> </Route> <Route path="/"> <FlightDetails /> </Route> </Switch> </div> </Router> ); } export default App;
4951dc5d41565bfc912a3da020aeee4a83e7a349
[ "JavaScript", "Markdown" ]
5
JavaScript
rk-react-dev/Flight-Details
18d65299ad88e755a719e19c5e649454129142c8
d9226f3fa04917c238094f91b3372becc9138ad3
refs/heads/master
<file_sep>package astarasikov.github.io.camandnettest; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import astarasikov.github.io.camandnettest.dummy.DummyContent; public class CameraFragment extends Fragment { public CameraFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return new MyCameraView(this.getActivity()); } }
654c77b6fd620f64e47ce7a277b9b70e6ce4bd59
[ "Java" ]
1
Java
JuannyWang/android-graphics-experiments
53dc6463f4f07311104c2d44a6070581dc1b3022
2d28c54fafa93e5b14b9f97c5f5f0f055cc9bb70
refs/heads/master
<file_sep>package com.bridgelabz; import java.util.Comparator; public class SortByName implements Comparator<Person> { public int compare(Person firstPerson, Person secondPerson) { return (firstPerson.getLastName().compareTo(secondPerson.getLastName())); } } class SortByCity implements Comparator<Person> { public int compare(Person firstPerson, Person secondPerson) { return (firstPerson.getCity().compareTo(secondPerson.getCity())); } } class SortByState implements Comparator<Person> { public int compare(Person firstPerson, Person secondPerson) { return (firstPerson.getState().compareTo(secondPerson.getState())); } } class SortByZip implements Comparator<Person> { public int compare(Person firstPerson, Person secondPerson) { return (firstPerson.getZip().compareTo(secondPerson.getZip())); } }
c6aefc5b02066dcbf5041157ebdb32ef48f4641d
[ "Java" ]
1
Java
vegirevathi/AdvancedAddressBook
b05d006cf2ec74e6e66bd77d514ebf1a87ed459e
1a85600f9cbbf15906ff4fbf03218fb5e6ba8928
refs/heads/master
<file_sep># ClamShell Java library for data persistence and network communication. For more information: www.clam.io <file_sep>package clam.io.update; public class SoftwareVersionUpdateChecker { } <file_sep>package clam.io.network.messages; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import clam.io.network.NetworkClient; import clam.io.network.Node; import clam.io.network.Service; public class RegisterServiceRequest extends Request { public RegisterServiceRequest (String serviceName) { this.serviceName=serviceName; } } <file_sep>package clam.io.network.messages; public class Request extends Message { } <file_sep>package clam.io.network; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import clam.io.network.messages.DisconnectMessage; import clam.io.network.messages.Message; import clam.io.network.messages.RegisterServiceRequest; import clam.io.network.messages.Request; import clam.io.network.messages.Response; public class NetworkClient { public String host = null; public int port = 3125; public Node node = null; public NetworkClient(String host, int port) throws Exception { this.host = host; this.port = port; Socket s = new Socket(host, port); node = new Node(new ObjectOutputStream(s.getOutputStream()), new ObjectInputStream(s.getInputStream())); } public void attach(final Service service) throws Exception { final Response response = node.process ( new RegisterServiceRequest (service.serviceName)); new Thread () { public void run () { try { if (response.result==true) { while (true) { Message message = node.receive(); if (message instanceof Response) { System.out.println("Error in attachment: Got an unrequested 'response'! "+message); System.exit(0); } if (message instanceof DisconnectMessage){ break; } else if (message instanceof Request) { node.send(service.process((Request) message)); } else { service.handle(message); } } } else { throw new Exception ("IOClient: unable to attach "+service); } } catch (Exception e) { } } }.start(); } }
60655d03852265b8a41b6dec4738eb18fc720717
[ "Markdown", "Java" ]
5
Markdown
sloetjes/ClamShell
649d0d7d77bf3aa13bc43983fdd38345bdf2e13b
bf66a5afd0a36a01a3380cda44dc0b868d9f8962
refs/heads/main
<repo_name>bhatvikrant/v-drive<file_sep>/src/lib/firebase.ts import firebase from "firebase/compat/app"; import "firebase/compat/auth"; import "firebase/compat/firestore"; import "firebase/compat/storage"; import "firebase/compat/analytics"; import "firebase/compat/performance"; const firebaseConfig = { apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY, authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID, storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET, messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID, appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID, measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID, }; if (!firebase.apps.length) { firebase.initializeApp(firebaseConfig); // Check that `window` is in scope for the analytics module! if (typeof window !== "undefined") { // Enable analytics. https://firebase.google.com/docs/analytics/get-started if ("measurementId" in firebaseConfig) { firebase.analytics(); firebase.performance(); } } /* eslint-disable */ console.log("Firebase was successfully init."); } const firestore = firebase.firestore(); export const db = { folders: firestore.collection("folders"), files: firestore.collection("files"), formatDoc: doc => ({ id: doc.id, ...doc.data(), }), getCurrentTimeStamp: firebase.firestore.FieldValue.serverTimestamp, }; export default firebase;
b29b59d7fe815ce43e5b4506b7bdc88632a41292
[ "TypeScript" ]
1
TypeScript
bhatvikrant/v-drive
b866f6c5c8cbd1364a2512c5db643366c7fa8d13
25b1eba2ba478020bf130ef9ea1d524f6ec27b89
refs/heads/master
<repo_name>sunyoungbaek/homework<file_sep>/google_trend_interest.py import sys from pytrends.request import TrendReq def googleTrendInterest(words): pytrend = TrendReq(hl='en-US', geo='US') pytrend.build_payload([words[0], words[1], words[0] + ' ' + words[1]], cat=0, timeframe='today 5-y') result = pytrend.interest_over_time() result = result.iloc[:, :3].sum() return result if __name__== "__main__": query = sys.argv[1] words = query.lower().split() # If query is not a bigram, return message if len(words) != 2: sys.stdout.write('this word is not a bigram') else: df = googleTrendInterest(words) sys.stdout.write(str(dict(df))) <file_sep>/word_probs.py import pandas as pd from urllib.request import urlopen from collections import defaultdict from collections import OrderedDict import numpy as np from word_counts import wordCounts class WordProbs: # static variable - % of unknown unique words based on the corpus unknownWordProb = 0.05 def __init__(self, wordCount): self.wordCount = wordCount def _getUnigramProb(self, word): uc = self.wordCount.getUnigramCount(word) tc = self.wordCount.getTotalUnigramCount() # Total vocabulary size: V = N(unique words in corpus) + N(unique unseen words). # N(unique unseen words) is interpolated from seen vocab size. V = self.wordCount.getUniqueUnigramCount() * 1 / (1 - self.unknownWordProb) # Laplace smooth by assuming 1 missing observation of all vocabulary return (uc + 1) / (tc + V) def _getBigramGivenUnigramProb(self, word1, word2): bc = self.wordCount.getBigramCount(word1, word2) uc1 = self.wordCount.getUnigramCount(word1) ubc1 = self.wordCount.getUniqueBigramCountAfterGivenWord(word1) # add 1 to all unigram counts for smoothing smoothingFactor = ubc1 / (ubc1 + uc1 + 1) return (1 - smoothingFactor) * bc / (uc1 + 1) + smoothingFactor * self._getUnigramProb(word2) def _getBigramProb(self, word1, word2): return self._getUnigramProb(word1) * self._getBigramGivenUnigramProb(word1, word2) def _getRelativeStrengthScore(self, word1, word2): return max(self._getBigramGivenUnigramProb(word1, word2) / self._getUnigramProb(word2), 1.0) def _addDictionaries(self, dict_A, dict_B, a, b): dict_full = defaultdict(lambda : 0) for k, v in dict_A.items(): dict_full[k] = dict_full[k] + v * a for k, v in dict_B.items(): dict_full[k] = dict_full[k] + v * b return dict_full def _createBigram(self, word_A, word_B): return (word_A.decode() + ' ' + word_B.decode()).encode() def _probabilityOfFormingBigram(self, w1, w2): # Cap odds at 100 to not have NaN error x = min(self._getRelativeStrengthScore(w1, w2) - 1.0, 100) return (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)) def _scoreWeights(self, words): memory = [{}] * len(words) memory[len(words) - 1] = {words[len(words) - 1]: 1.0} for i in range(len(words) - 1, 0, -1): p = self._probabilityOfFormingBigram(words[i-1], words[i]) bigram = self._createBigram(words[i-1], words[i]) # Each word can form a bigram with the next word with probability p, # or be a standlone unigram with probability (1-p) if i == len(words) - 1: case1 = {bigram: 2.0} case2 = self._addDictionaries({words[i-1]: 1.0}, memory[i], 1, 1) else: case1 = self._addDictionaries({bigram: 2.0}, memory[i+1], 1, 1) case2 = self._addDictionaries({words[i-1]: 1.0}, memory[i], 1, 1) memory[i-1] = self._addDictionaries(case1, case2, p, 1-p) return memory[0] def _normalizeWeights(self, weights): decodedWeights = {} totalVal = sum(list(weights.values())) for k, v in weights.items(): decodedWeights[k.decode()] = v / totalVal return decodedWeights def getUniBigramWeights(self, query): words = query.lower().encode().split() if len(words) == 0: return {} weights = dict(self._scoreWeights(words)) normalizedWeights = self._normalizeWeights(weights) return normalizedWeights # Create a WordProbs object based on the WordCount wordProbs = WordProbs(wordCounts) <file_sep>/main.py import sys from word_probs import wordProbs if __name__== "__main__": weights = wordProbs.getUniBigramWeights(sys.argv[1]) sys.stdout.write(str(weights)) <file_sep>/README.md # Homework ## Commands python main.py "mountain view startup" python google_trend_interest.py "ipad walmart" ## Sample Result from Main.py 'mountain view startp': {'mountain view': 0.4899983193661052, 'startup': 0.3333333333333333, 'mountain': 0.08833417365028073, 'view startup': 0.0, 'view': 0.08833417365028073} 'ipad walmart': {'ipad walmart': 0.0, 'ipad': 0.5, 'walmart': 0.5} 'ice cream social in san francisco': {'ice cream': 0.3333333333333333, 'social in': 0.0, 'san francisco': 0.3333333333333333, 'san': 0.0, 'francisco': 0.0, 'social': 0.16666666666666666, 'in san': 0.0, 'in': 0.16666666666666666, 'ice': 0.0, 'cream social': 0.0, 'cream': 0.0} 'beauty and the beast': {'beauty and': 0.07082758985981812, 'the beast': 0.34969838165787204, 'the': 0.026321459438805428, 'beast': 0.07515080917106398, 'beauty': 0.21458620507009094, 'and the': 0.0976586994645171, 'and': 0.16575685533783238} 'the fastest animal in the world': {'the fastest': 0.3333333320697086, 'animal in': 0.0, 'the world': 0.0002792506540196216, 'the': 4.476094505927714e-09, 'world': 0.16652704133965684, 'animal': 0.16666666666666663, 'in the': 0.3330540749907493, 'in': 0.00013962917129199207, 'fastest animal': 0.0, 'fastest': 6.318123246806805e-10} 'how to learn a foreign language' {'how to': 0.33333127904757676, 'learn a': 0.0, 'foreign language': 0.006939595346527511, 'foreign': 0.0, 'language': 0.16319686899340288, 'learn': 0.16666563953342817, 'a foreign': 0.32639373798680577, 'a': 0.0034697976732637557, 'how': 1.0271428782515633e-06, 'to learn': 2.054266476946977e-06, 'to': 9.639778074978371e-12} ## What's to be improved Small weights (<0.1) are generally meaningless. They should be muted and re-normalized. In 'beauty and the beast', 'beauty' (0.21) and (0.16) the beast (0.35) are the main scorers. 'and' is just conjunction and could have been lower weighted. In ''the fastest animal in the world', 'the fastest' (0.33) 'animal' (0.17), 'in the' (0.33), 'world' (0.16) are the main scorers. Instead of 'in the' + 'world', it would make more sense as 'in' + 'the world' grammatically. In 'how to learn a foreign language', 'how to' (0.33) 'learn' (0.17) 'a foreign' (0.33) 'language' (0.16) are the main scorers. Here, 'a foreign' doesn't really make sense, and it shoube 'a' + 'foreign language' instead. But since 'a' is so often used whenever 'foreign' modifier is used, this model doesn't know how to separate them (even though P(w2|w1) must be small, this model doesn't seem to penalize 'a''s frequency enough). In all cases, we can see that 'in', 'and', 'the' are overweighted or over-joined (detected as bigram). Exploring how to weaken their importance using f(-log(uni/bigram prob)) can be helpful. Probabilities functions are already provided in WordProbs class. ## Attempt to use Google Trend I used pytrends package. (Make sure to pip install git+https://github.com/GeneralMills/pytrends. Version 4.6 has a major bug) Explored using top_charts() and trending_searches(), but most of them are people's names or trendy terms (movie, show, game names, etc), so they were not useful. I provided a file to look at unigram/bigram interests in Google Trend, given bigram query. This helps understanding strength of unigrams/bigrams. <file_sep>/word_counts.py import pandas as pd from urllib.request import urlopen from collections import defaultdict from collections import OrderedDict import numpy as np class WordCounts: def __init__(self, unigramUrl, bigramUrl): self.unigramUrl = unigramUrl self.bigramUrl = bigramUrl # initialize unigram variables self.unigramCounts = defaultdict(lambda : 0) self.totalUnigrams = 0 self.numUnigramKeys = 0 self._initializeUnigramCounts() # initialize bigram variables self.bigramCounts = defaultdict(lambda : defaultdict(lambda: 0)) self.totalBigrams = 0 self.numBigramKeys = 0 self._initializeBigramCounts() def _initializeUnigramCounts(self): data = urlopen(self.unigramUrl) nk, tot = 0, 0 for line in data: word, count = line.split() self.unigramCounts[word] = int(count) nk += 1 tot += int(count) self.numUnigramKeys = nk self.totalUnigrams = tot def _initializeBigramCounts(self): data = urlopen(self.bigramUrl) nk, tot = 0, 0 for line in data: word1, word2, count = line.split() self.bigramCounts[word1][word2] = int(count) nk += 1 tot += int(count) self.numBigramKeys = nk self.totalBigrams = tot def getUnigramCount(self, word): return self.unigramCounts[word] def getTotalUnigramCount(self): return self.totalUnigrams def getUniqueUnigramCount(self): return self.numUnigramKeys def addUnigram(self, word): # if unigram is never seen before, add to unique unigram if self.unigramCounts[word] == 0: self.numUnigramKeys += 1 self.unigramCounts[word] = self.unigramCounts[word] + 1 self.totalUnigrams += 1 def getBigramCount(self, word1, word2): return self.bigramCounts[word1][word2] def getTotalBigramCount(self): return self.totalBigrams def getUniqueBigramCount(self): return self.numBigramKeys def getUniqueBigramCountAfterGivenWord(self, word): return len(self.bigramCounts[word].keys()) def addBigram(self, word1, word2): if self.bigramCounts[word1][word2] == 0: self.numBigramCounts += 1 self.bigramCounts[word1][word2] = self.bigramCounts[word1][word2] + 1 self.totalBigrams += 1 # Define unigram and bigram corpus URL unigramUrl = 'https://norvig.com/ngrams/count_1w.txt' bigramUrl = 'https://norvig.com/ngrams/count_2w.txt' # Create a WordCounts object based on the URLs wordCounts = WordCounts(unigramUrl, bigramUrl)
6f0bc76ee06c0dffa0aa4a04233e0129069a4ead
[ "Markdown", "Python" ]
5
Python
sunyoungbaek/homework
2a1fb06e77affeb66b9de769c176aba4f1c888c4
8edeaa8f793ab84339cfd8601e1f350824d1d697
refs/heads/master
<file_sep>using UnityEngine; namespace Assets.Resources.Scripts { public class PlayerMovement : MonoBehaviour { private Vector3 _movePosition; public float Speed = 3; private bool _isPositionSet; void Update() { CheckForNewPosition(); // TODO: Do actual pathfinding here instead of just walking through walls! if(_isPositionSet) transform.position = Vector3.MoveTowards(transform.position, _movePosition, Speed * Time.deltaTime); } private void CheckForNewPosition() { if (Input.GetMouseButtonDown(0)) { CheckForTile(Camera.main.ScreenPointToRay(Input.mousePosition)); } if(Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0) CheckForTile(new Ray(transform.position - new Vector3(Input.GetAxisRaw("Horizontal"), -.1f, Input.GetAxisRaw("Vertical")), Vector3.down)); } private void CheckForTile(Ray pos) { RaycastHit hit; if (Physics.Raycast(pos, out hit)) { _isPositionSet = true; _movePosition = hit.collider.transform.position; } } } }<file_sep>using Dungeon.Generator.Generation; using UnityEngine; namespace Assets.Resources.Scripts { public class Director : MonoBehaviour { public GameObject Tile; public GameObject Player; private bool _isPlayerPlaced; void Start() { var g = Generator.Generate(MapSize.Small, 42); for (var z = 0; z < g.Height; z++) { for (var x = 0; x < g.Width; x++) { if (g[x, z] == 1) { if (!_isPlayerPlaced) { Player.transform.position = new Vector3(x, 0, z); _isPlayerPlaced = true; } var t = (GameObject) Instantiate(Tile); t.transform.position = new Vector3(x, 0, z); } } } } } }
46976d9614745827a30c9aea289cee43c57f9755
[ "C#" ]
2
C#
EricFreeman/UnityDungeons
ba05dfe2b1c056721af47617699535b8df001064
914b64180e2d2d65df956e86563019277831cf1f
refs/heads/master
<repo_name>cristianbatist/crud-mvc5-ef-angularjs<file_sep>/Emp_XPTO/CRUD_MVC5_AngularJs/Controllers/FuncionarioController.cs using CRUD_MVC5_AngularJs.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CRUD_MVC5_AngularJs.Controllers { public class FuncionarioController : Controller { #region Método para Listar Funcionário - READ // GET Funcionario/GetFuncionario public JsonResult GetFuncionário() { using (var db = new FuncionariosEntities()) { List<Funcionario> listarFuncionarios = db.Funcionarios.ToList(); return Json(listarFuncionarios, JsonRequestBehavior.AllowGet); } } #endregion } }<file_sep>/Emp_XPTO/CRUD_MVC5_AngularJs/AngularJsApp/Funcionario/Service.js /** * Arquivo: Service.js * Data: 10/12/2017 * Descrição: arquivo responsável por carregar os dados via $http.get - do MVC Controller * (onde transformará os dados em Json) * Author: <NAME> */ funcionarioApp.service('funcionarioService', function($http) { this.getTodosFuncionarios = function() { return $http.get("/Funcionario/GetFuncionário"); } })<file_sep>/Emp_XPTO/CRUD_MVC5_AngularJs/AngularJsApp/Funcionario/Controller.js /** * Arquivo: Controller.js * Data: 10/12/2017 * Descrição: Esse arquivo irá conter o código do 'funcionarioCtrl' a qual controlará os módulos de * 'funcionarios' * Author: <NAME> */ // Controller - Funcionário: funcionarioApp.controller('funcionarioCtrl', function ($scope, funcionarioService) { //Aqui estamos carregando todos os dados gravados do Funcionário quando a página for recarregada: carregarFuncionarios(); function carregarFuncionarios() { var listarFuncionarios = funcionarioService.getTodosFuncionarios(); listarFuncionarios.then(function (d) { //se tudo der certo: $scope.Funcionarios = d.data; }, function () { alert("Ocorreu um erro ao tentar listar todos os funcionários!"); }); } });
55afc234b0a000be0f2384f8ff22457833465b09
[ "JavaScript", "C#" ]
3
C#
cristianbatist/crud-mvc5-ef-angularjs
fadd518dfed0ea20482c77423b39a5a604cca2fa
1d50f510fdbb79528be124af40d98a0a3af0b159